diff --git a/.gitignore b/.gitignore
index 30f0f0cbc2..e841cc4bf5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,8 +7,11 @@
# Eclipse
.settings/
+*.project
+*.classpath
.prefs
*.prefs
+.metadata/
# Intellij
.idea/
@@ -21,3 +24,6 @@
# Maven
log/
target/
+
+spring-openid/src/main/resources/application.properties
+.recommenders/
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000000..9c5cdb8f2d
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "testgitrepo"]
+ path = testgitrepo
+ url = /home/prd/Development/projects/idea/tutorials/spring-boot/src/main/resources/testgitrepo/
diff --git a/.project b/.project
deleted file mode 100644
index 2d04570bfe..0000000000
--- a/.project
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
- parent
-
-
-
-
-
-
-
-
diff --git a/README.md b/README.md
index da46989455..f0d3d29da7 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,7 @@
The "REST with Spring" Classes
==============================
-After 5 months of work, here's the Master Class:
+After 5 months of work, here's the Master Class of REST With Spring:
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
@@ -19,3 +19,8 @@ Any IDE can be used to work with the projects, but if you're using Eclipse, cons
- import the included **formatter** in Eclipse:
`https://github.com/eugenp/tutorials/tree/master/eclipse`
+
+
+CI - Jenkins
+================================
+This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials/)**
diff --git a/RemoteSystemsTempFiles/.project b/RemoteSystemsTempFiles/.project
deleted file mode 100644
index 5447a64fa9..0000000000
--- a/RemoteSystemsTempFiles/.project
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
- RemoteSystemsTempFiles
-
-
-
-
-
-
- org.eclipse.rse.ui.remoteSystemsTempNature
-
-
diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml
new file mode 100644
index 0000000000..6d07394b87
--- /dev/null
+++ b/annotations/annotation-processing/pom.xml
@@ -0,0 +1,50 @@
+
+
+ 4.0.0
+
+
+ com.baeldung
+ 1.0.0-SNAPSHOT
+ annotations
+ ../
+
+
+ annotation-processing
+
+
+ 1.0-rc2
+ 3.5.1
+
+
+
+
+
+ com.google.auto.service
+ auto-service
+ ${auto-service.version}
+ provided
+
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ 1.8
+ 1.8
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java
new file mode 100644
index 0000000000..0883e108e7
--- /dev/null
+++ b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProcessor.java
@@ -0,0 +1,132 @@
+package com.baeldung.annotation.processor;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import javax.annotation.processing.*;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.type.ExecutableType;
+import javax.tools.Diagnostic;
+import javax.tools.JavaFileObject;
+
+import com.google.auto.service.AutoService;
+
+@SupportedAnnotationTypes("com.baeldung.annotation.processor.BuilderProperty")
+@SupportedSourceVersion(SourceVersion.RELEASE_8)
+@AutoService(Processor.class)
+public class BuilderProcessor extends AbstractProcessor {
+
+ @Override
+ public boolean process(Set extends TypeElement> annotations, RoundEnvironment roundEnv) {
+ for (TypeElement annotation : annotations) {
+
+ Set extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
+
+ Map> annotatedMethods = annotatedElements.stream()
+ .collect(Collectors.partitioningBy(element ->
+ ((ExecutableType) element.asType()).getParameterTypes().size() == 1
+ && element.getSimpleName().toString().startsWith("set")));
+
+ List setters = annotatedMethods.get(true);
+ List otherMethods = annotatedMethods.get(false);
+
+ otherMethods.forEach(element ->
+ processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
+ "@BuilderProperty must be applied to a setXxx method with a single argument", element));
+
+ if (setters.isEmpty()) {
+ continue;
+ }
+
+ String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString();
+
+ Map setterMap = setters.stream().collect(Collectors.toMap(
+ setter -> setter.getSimpleName().toString(),
+ setter -> ((ExecutableType) setter.asType())
+ .getParameterTypes().get(0).toString()
+ ));
+
+ try {
+ writeBuilderFile(className, setterMap);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ return true;
+ }
+
+ private void writeBuilderFile(String className, Map setterMap) throws IOException {
+
+ String packageName = null;
+ int lastDot = className.lastIndexOf('.');
+ if (lastDot > 0) {
+ packageName = className.substring(0, lastDot);
+ }
+
+ String simpleClassName = className.substring(lastDot + 1);
+ String builderClassName = className + "Builder";
+ String builderSimpleClassName = builderClassName.substring(lastDot + 1);
+
+ JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(builderClassName);
+ try (PrintWriter out = new PrintWriter(builderFile.openWriter())) {
+
+ if (packageName != null) {
+ out.print("package ");
+ out.print(packageName);
+ out.println(";");
+ out.println();
+ }
+
+ out.print("public class ");
+ out.print(builderSimpleClassName);
+ out.println(" {");
+ out.println();
+
+ out.print(" private ");
+ out.print(simpleClassName);
+ out.print(" object = new ");
+ out.print(simpleClassName);
+ out.println("();");
+ out.println();
+
+ out.print(" public ");
+ out.print(simpleClassName);
+ out.println(" build() {");
+ out.println(" return object;");
+ out.println(" }");
+ out.println();
+
+ setterMap.entrySet().forEach(setter -> {
+ String methodName = setter.getKey();
+ String argumentType = setter.getValue();
+
+ out.print(" public ");
+ out.print(builderSimpleClassName);
+ out.print(" ");
+ out.print(methodName);
+
+ out.print("(");
+
+ out.print(argumentType);
+ out.println(" value) {");
+ out.print(" object.");
+ out.print(methodName);
+ out.println("(value);");
+ out.println(" return this;");
+ out.println(" }");
+ out.println();
+ });
+
+ out.println("}");
+
+ }
+ }
+
+}
diff --git a/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java
new file mode 100644
index 0000000000..84fcc73850
--- /dev/null
+++ b/annotations/annotation-processing/src/main/java/com/baeldung/annotation/processor/BuilderProperty.java
@@ -0,0 +1,8 @@
+package com.baeldung.annotation.processor;
+
+import java.lang.annotation.*;
+
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.SOURCE)
+public @interface BuilderProperty {
+}
diff --git a/annotations/annotation-user/pom.xml b/annotations/annotation-user/pom.xml
new file mode 100644
index 0000000000..f76f691f93
--- /dev/null
+++ b/annotations/annotation-user/pom.xml
@@ -0,0 +1,51 @@
+
+
+ 4.0.0
+
+
+ annotations
+ com.baeldung
+ 1.0.0-SNAPSHOT
+ ../
+
+
+ annotation-user
+
+
+
+
+ com.baeldung
+ annotation-processing
+ ${project.parent.version}
+
+
+
+ junit
+ junit
+ 4.12
+ test
+
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.5.1
+
+ 1.8
+ 1.8
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java b/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java
new file mode 100644
index 0000000000..23787ba4f4
--- /dev/null
+++ b/annotations/annotation-user/src/main/java/com/baeldung/annotation/Person.java
@@ -0,0 +1,29 @@
+package com.baeldung.annotation;
+
+import com.baeldung.annotation.processor.BuilderProperty;
+
+public class Person {
+
+ private int age;
+
+ private String name;
+
+ public int getAge() {
+ return age;
+ }
+
+ @BuilderProperty
+ public void setAge(int age) {
+ this.age = age;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ @BuilderProperty
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
diff --git a/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java
new file mode 100644
index 0000000000..72f9ac8bc7
--- /dev/null
+++ b/annotations/annotation-user/src/test/java/com/baeldung/annotation/PersonBuilderTest.java
@@ -0,0 +1,22 @@
+package com.baeldung.annotation;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class PersonBuilderTest {
+
+ @Test
+ public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
+
+ Person person = new PersonBuilder()
+ .setAge(25)
+ .setName("John")
+ .build();
+
+ assertEquals(25, person.getAge());
+ assertEquals("John", person.getName());
+
+ }
+
+}
diff --git a/annotations/pom.xml b/annotations/pom.xml
new file mode 100644
index 0000000000..f691674cf1
--- /dev/null
+++ b/annotations/pom.xml
@@ -0,0 +1,20 @@
+
+
+
+ parent-modules
+ com.baeldung
+ 1.0.0-SNAPSHOT
+
+ 4.0.0
+
+ annotations
+ pom
+
+
+ annotation-processing
+ annotation-user
+
+
+
\ No newline at end of file
diff --git a/annotations/readme.md b/annotations/readme.md
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/annotations/readme.md
@@ -0,0 +1 @@
+
diff --git a/apache-cxf/cxf-introduction/pom.xml b/apache-cxf/cxf-introduction/pom.xml
new file mode 100644
index 0000000000..232a4f0089
--- /dev/null
+++ b/apache-cxf/cxf-introduction/pom.xml
@@ -0,0 +1,47 @@
+
+
+
+ 4.0.0
+ cxf-introduction
+
+ com.baeldung
+ apache-cxf
+ 0.0.1-SNAPSHOT
+
+
+ 3.1.6
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+
+ com.baeldung.cxf.introduction.Server
+
+
+
+ maven-surefire-plugin
+ 2.19.1
+
+
+ **/StudentTest.java
+
+
+
+
+
+
+
+ org.apache.cxf
+ cxf-rt-frontend-jaxws
+ ${cxf.version}
+
+
+ org.apache.cxf
+ cxf-rt-transports-http-jetty
+ ${cxf.version}
+
+
+
diff --git a/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Baeldung.java b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Baeldung.java
new file mode 100644
index 0000000000..472d38b8e1
--- /dev/null
+++ b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Baeldung.java
@@ -0,0 +1,16 @@
+package com.baeldung.cxf.introduction;
+
+import java.util.Map;
+
+import javax.jws.WebService;
+import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
+
+@WebService
+public interface Baeldung {
+ public String hello(String name);
+
+ public String helloStudent(Student student);
+
+ @XmlJavaTypeAdapter(StudentMapAdapter.class)
+ public Map getStudents();
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/BaeldungImpl.java b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/BaeldungImpl.java
new file mode 100644
index 0000000000..240f6bb1da
--- /dev/null
+++ b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/BaeldungImpl.java
@@ -0,0 +1,24 @@
+package com.baeldung.cxf.introduction;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import javax.jws.WebService;
+
+@WebService(endpointInterface = "com.baeldung.cxf.introduction.Baeldung")
+public class BaeldungImpl implements Baeldung {
+ private Map students = new LinkedHashMap();
+
+ public String hello(String name) {
+ return "Hello " + name;
+ }
+
+ public String helloStudent(Student student) {
+ students.put(students.size() + 1, student);
+ return "Hello " + student.getName();
+ }
+
+ public Map getStudents() {
+ return students;
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java
new file mode 100644
index 0000000000..0e5af60b9d
--- /dev/null
+++ b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java
@@ -0,0 +1,15 @@
+package com.baeldung.cxf.introduction;
+
+import javax.xml.ws.Endpoint;
+
+public class Server {
+ public static void main(String args[]) throws InterruptedException {
+ BaeldungImpl implementor = new BaeldungImpl();
+ String address = "http://localhost:8080/baeldung";
+ Endpoint.publish(address, implementor);
+ System.out.println("Server ready...");
+ Thread.sleep(60 * 1000);
+ System.out.println("Server exiting");
+ System.exit(0);
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Student.java b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Student.java
new file mode 100644
index 0000000000..cad8f94d97
--- /dev/null
+++ b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Student.java
@@ -0,0 +1,8 @@
+package com.baeldung.cxf.introduction;
+
+import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
+
+@XmlJavaTypeAdapter(StudentAdapter.class)
+public interface Student {
+ public String getName();
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentAdapter.java b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentAdapter.java
new file mode 100644
index 0000000000..29b829d808
--- /dev/null
+++ b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentAdapter.java
@@ -0,0 +1,16 @@
+package com.baeldung.cxf.introduction;
+
+import javax.xml.bind.annotation.adapters.XmlAdapter;
+
+public class StudentAdapter extends XmlAdapter {
+ public StudentImpl marshal(Student student) throws Exception {
+ if (student instanceof StudentImpl) {
+ return (StudentImpl) student;
+ }
+ return new StudentImpl(student.getName());
+ }
+
+ public Student unmarshal(StudentImpl student) throws Exception {
+ return student;
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentImpl.java b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentImpl.java
new file mode 100644
index 0000000000..bc9dd27afe
--- /dev/null
+++ b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentImpl.java
@@ -0,0 +1,23 @@
+package com.baeldung.cxf.introduction;
+
+import javax.xml.bind.annotation.XmlType;
+
+@XmlType(name = "Student")
+public class StudentImpl implements Student {
+ private String name;
+
+ StudentImpl() {
+ }
+
+ public StudentImpl(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMap.java b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMap.java
new file mode 100644
index 0000000000..4c40886c42
--- /dev/null
+++ b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMap.java
@@ -0,0 +1,39 @@
+package com.baeldung.cxf.introduction;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlType;
+
+@XmlType(name = "StudentMap")
+public class StudentMap {
+ private List entries = new ArrayList();
+
+ @XmlElement(nillable = false, name = "entry")
+ public List getEntries() {
+ return entries;
+ }
+
+ @XmlType(name = "StudentEntry")
+ public static class StudentEntry {
+ private Integer id;
+ private Student student;
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setStudent(Student student) {
+ this.student = student;
+ }
+
+ public Student getStudent() {
+ return student;
+ }
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMapAdapter.java b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMapAdapter.java
new file mode 100644
index 0000000000..f156676a5f
--- /dev/null
+++ b/apache-cxf/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMapAdapter.java
@@ -0,0 +1,27 @@
+package com.baeldung.cxf.introduction;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import javax.xml.bind.annotation.adapters.XmlAdapter;
+
+public class StudentMapAdapter extends XmlAdapter> {
+ public StudentMap marshal(Map boundMap) throws Exception {
+ StudentMap valueMap = new StudentMap();
+ for (Map.Entry boundEntry : boundMap.entrySet()) {
+ StudentMap.StudentEntry valueEntry = new StudentMap.StudentEntry();
+ valueEntry.setStudent(boundEntry.getValue());
+ valueEntry.setId(boundEntry.getKey());
+ valueMap.getEntries().add(valueEntry);
+ }
+ return valueMap;
+ }
+
+ public Map unmarshal(StudentMap valueMap) throws Exception {
+ Map boundMap = new LinkedHashMap();
+ for (StudentMap.StudentEntry studentEntry : valueMap.getEntries()) {
+ boundMap.put(studentEntry.getId(), studentEntry.getStudent());
+ }
+ return boundMap;
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentTest.java b/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentTest.java
new file mode 100644
index 0000000000..e1e5b60ec3
--- /dev/null
+++ b/apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentTest.java
@@ -0,0 +1,65 @@
+package com.baeldung.cxf.introduction;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Map;
+
+import javax.xml.namespace.QName;
+import javax.xml.ws.Service;
+import javax.xml.ws.soap.SOAPBinding;
+
+import com.baeldung.cxf.introduction.Baeldung;
+import com.baeldung.cxf.introduction.Student;
+import com.baeldung.cxf.introduction.StudentImpl;
+
+public class StudentTest {
+ private static QName SERVICE_NAME = new QName("http://introduction.cxf.baeldung.com/", "Baeldung");
+ private static QName PORT_NAME = new QName("http://introduction.cxf.baeldung.com/", "BaeldungPort");
+
+ private Service service;
+ private Baeldung baeldungProxy;
+ private BaeldungImpl baeldungImpl;
+
+ {
+ service = Service.create(SERVICE_NAME);
+ String endpointAddress = "http://localhost:8080/baeldung";
+ service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
+ }
+
+ @Before
+ public void reinstantiateBaeldungInstances() {
+ baeldungImpl = new BaeldungImpl();
+ baeldungProxy = service.getPort(PORT_NAME, Baeldung.class);
+ }
+
+ @Test
+ public void whenUsingHelloMethod_thenCorrect() {
+ String endpointResponse = baeldungProxy.hello("Baeldung");
+ String localResponse = baeldungImpl.hello("Baeldung");
+ assertEquals(localResponse, endpointResponse);
+ }
+
+ @Test
+ public void whenUsingHelloStudentMethod_thenCorrect() {
+ Student student = new StudentImpl("John Doe");
+ String endpointResponse = baeldungProxy.helloStudent(student);
+ String localResponse = baeldungImpl.helloStudent(student);
+ assertEquals(localResponse, endpointResponse);
+ }
+
+ @Test
+ public void usingGetStudentsMethod_thenCorrect() {
+ Student student1 = new StudentImpl("Adam");
+ baeldungProxy.helloStudent(student1);
+
+ Student student2 = new StudentImpl("Eve");
+ baeldungProxy.helloStudent(student2);
+
+ Map students = baeldungProxy.getStudents();
+ assertEquals("Adam", students.get(1).getName());
+ assertEquals("Eve", students.get(2).getName());
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-spring/.gitignore b/apache-cxf/cxf-spring/.gitignore
new file mode 100644
index 0000000000..2f7896d1d1
--- /dev/null
+++ b/apache-cxf/cxf-spring/.gitignore
@@ -0,0 +1 @@
+target/
diff --git a/apache-cxf/cxf-spring/pom.xml b/apache-cxf/cxf-spring/pom.xml
new file mode 100644
index 0000000000..85e68300f0
--- /dev/null
+++ b/apache-cxf/cxf-spring/pom.xml
@@ -0,0 +1,129 @@
+
+ 4.0.0
+ cxf-spring
+ war
+
+ com.baeldung
+ apache-cxf
+ 0.0.1-SNAPSHOT
+
+
+
+
+ org.apache.cxf
+ cxf-rt-frontend-jaxws
+ ${cxf.version}
+
+
+ org.apache.cxf
+ cxf-rt-transports-http-jetty
+ ${cxf.version}
+
+
+ org.springframework
+ spring-context
+ ${spring.version}
+
+
+ org.springframework
+ spring-webmvc
+ ${spring.version}
+
+
+ javax.servlet
+ javax.servlet-api
+ 3.1.0
+
+
+
+
+
+
+ maven-war-plugin
+ 2.6
+
+ false
+
+
+
+ maven-surefire-plugin
+ ${surefire.version}
+
+
+ StudentTest.java
+
+
+
+
+
+
+
+
+ integration
+
+
+
+ org.codehaus.cargo
+ cargo-maven2-plugin
+ 1.4.19
+
+
+ tomcat8x
+ embedded
+
+
+
+ localhost
+ 8081
+
+
+
+
+
+ start-server
+ pre-integration-test
+
+ start
+
+
+
+ stop-server
+ post-integration-test
+
+ stop
+
+
+
+
+
+
+ maven-surefire-plugin
+ ${surefire.version}
+
+
+ integration-test
+
+ test
+
+
+
+ none
+
+
+
+
+
+
+
+
+
+
+
+
+ 3.1.6
+ 4.3.1.RELEASE
+ 2.19.1
+
+
+
diff --git a/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/AppInitializer.java b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/AppInitializer.java
new file mode 100644
index 0000000000..a4faa0f287
--- /dev/null
+++ b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/AppInitializer.java
@@ -0,0 +1,21 @@
+package com.baeldung.cxf.spring;
+
+import javax.servlet.ServletContext;
+import javax.servlet.ServletRegistration;
+
+import org.apache.cxf.transport.servlet.CXFServlet;
+import org.springframework.web.WebApplicationInitializer;
+import org.springframework.web.context.ContextLoaderListener;
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
+
+public class AppInitializer implements WebApplicationInitializer {
+ @Override
+ public void onStartup(ServletContext container) {
+ AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
+ context.register(ServiceConfiguration.class);
+ container.addListener(new ContextLoaderListener(context));
+
+ ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new CXFServlet());
+ dispatcher.addMapping("/services/*");
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/Baeldung.java b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/Baeldung.java
new file mode 100644
index 0000000000..b66e4c2fbf
--- /dev/null
+++ b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/Baeldung.java
@@ -0,0 +1,10 @@
+package com.baeldung.cxf.spring;
+
+import javax.jws.WebService;
+
+@WebService
+public interface Baeldung {
+ String hello(String name);
+
+ String register(Student student);
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/BaeldungImpl.java b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/BaeldungImpl.java
new file mode 100644
index 0000000000..911ce7f876
--- /dev/null
+++ b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/BaeldungImpl.java
@@ -0,0 +1,17 @@
+package com.baeldung.cxf.spring;
+
+import javax.jws.WebService;
+
+@WebService(endpointInterface = "com.baeldung.cxf.spring.Baeldung")
+public class BaeldungImpl implements Baeldung {
+ private int counter;
+
+ public String hello(String name) {
+ return "Hello " + name + "!";
+ }
+
+ public String register(Student student) {
+ counter++;
+ return student.getName() + " is registered student number " + counter;
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/ClientConfiguration.java b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/ClientConfiguration.java
new file mode 100644
index 0000000000..021bcc6f66
--- /dev/null
+++ b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/ClientConfiguration.java
@@ -0,0 +1,21 @@
+package com.baeldung.cxf.spring;
+
+import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ClientConfiguration {
+ @Bean(name = "client")
+ public Object generateProxy() {
+ return proxyFactoryBean().create();
+ }
+
+ @Bean
+ public JaxWsProxyFactoryBean proxyFactoryBean() {
+ JaxWsProxyFactoryBean proxyFactory = new JaxWsProxyFactoryBean();
+ proxyFactory.setServiceClass(Baeldung.class);
+ proxyFactory.setAddress("http://localhost:8081/services/baeldung");
+ return proxyFactory;
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/ServiceConfiguration.java b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/ServiceConfiguration.java
new file mode 100644
index 0000000000..0bc60fb790
--- /dev/null
+++ b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/ServiceConfiguration.java
@@ -0,0 +1,24 @@
+package com.baeldung.cxf.spring;
+
+import javax.xml.ws.Endpoint;
+
+import org.apache.cxf.Bus;
+import org.apache.cxf.bus.spring.SpringBus;
+import org.apache.cxf.jaxws.EndpointImpl;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class ServiceConfiguration {
+ @Bean(name = Bus.DEFAULT_BUS_ID)
+ public SpringBus springBus() {
+ return new SpringBus();
+ }
+
+ @Bean
+ public Endpoint endpoint() {
+ EndpointImpl endpoint = new EndpointImpl(springBus(), new BaeldungImpl());
+ endpoint.publish("http://localhost:8081/services/baeldung");
+ return endpoint;
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/Student.java b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/Student.java
new file mode 100644
index 0000000000..eb58057eb6
--- /dev/null
+++ b/apache-cxf/cxf-spring/src/main/java/com/baeldung/cxf/spring/Student.java
@@ -0,0 +1,20 @@
+package com.baeldung.cxf.spring;
+
+public class Student {
+ private String name;
+
+ Student() {
+ }
+
+ public Student(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java b/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java
new file mode 100644
index 0000000000..7466944e04
--- /dev/null
+++ b/apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java
@@ -0,0 +1,29 @@
+package com.baeldung.cxf.spring;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.AnnotationConfigApplicationContext;
+
+public class StudentTest {
+ private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class);
+ private Baeldung baeldungProxy = (Baeldung) context.getBean("client");
+
+ @Test
+ public void whenUsingHelloMethod_thenCorrect() {
+ String response = baeldungProxy.hello("John Doe");
+ assertEquals("Hello John Doe!", response);
+ }
+
+ @Test
+ public void whenUsingRegisterMethod_thenCorrect() {
+ Student student1 = new Student("Adam");
+ Student student2 = new Student("Eve");
+ String student1Response = baeldungProxy.register(student1);
+ String student2Response = baeldungProxy.register(student2);
+
+ assertEquals("Adam is registered student number 1", student1Response);
+ assertEquals("Eve is registered student number 2", student2Response);
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml
new file mode 100644
index 0000000000..022fc59f9b
--- /dev/null
+++ b/apache-cxf/pom.xml
@@ -0,0 +1,41 @@
+
+ 4.0.0
+ com.baeldung
+ apache-cxf
+ 0.0.1-SNAPSHOT
+ pom
+
+ cxf-introduction
+ cxf-spring
+
+
+
+ junit
+ junit
+ 4.12
+ test
+
+
+
+ install
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.5.1
+
+ 1.8
+ 1.8
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ 1.5.0
+
+
+
+
+
diff --git a/apache-fop/.classpath b/apache-fop/.classpath
deleted file mode 100644
index 63439b10fa..0000000000
--- a/apache-fop/.classpath
+++ /dev/null
@@ -1,37 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/apache-fop/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/apache-fop/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch
deleted file mode 100644
index 627021fb96..0000000000
--- a/apache-fop/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
diff --git a/apache-fop/.project b/apache-fop/.project
deleted file mode 100644
index d91e323034..0000000000
--- a/apache-fop/.project
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
- apache-fop
-
-
-
-
-
- org.eclipse.jdt.core.javabuilder
-
-
-
-
- org.eclipse.wst.common.project.facet.core.builder
-
-
-
-
- org.eclipse.wst.validation.validationbuilder
-
-
-
-
- org.eclipse.m2e.core.maven2Builder
-
-
-
-
-
- org.eclipse.jem.workbench.JavaEMFNature
- org.eclipse.wst.common.modulecore.ModuleCoreNature
- org.eclipse.jdt.core.javanature
- org.eclipse.m2e.core.maven2Nature
- org.eclipse.wst.common.project.facet.core.nature
-
-
diff --git a/apache-fop/.springBeans b/apache-fop/.springBeans
deleted file mode 100644
index a79097f40d..0000000000
--- a/apache-fop/.springBeans
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
- 1
-
-
-
-
-
-
- src/main/webapp/WEB-INF/api-servlet.xml
-
-
-
-
diff --git a/apache-fop/pom.xml b/apache-fop/pom.xml
index 95505f9374..658d567a90 100644
--- a/apache-fop/pom.xml
+++ b/apache-fop/pom.xml
@@ -1,6 +1,6 @@
4.0.0
- org.baeldung
+ com.baeldung
apache-fop
0.1-SNAPSHOT
@@ -142,16 +142,12 @@
-
- 4.1.5.RELEASE
- 3.2.5.RELEASE
-
- 4.3.8.Final
- 5.1.34
+ 4.3.11.Final
+ 5.1.38
- 2.5.5
+ 2.7.2
1.7.9
@@ -161,7 +157,7 @@
5.1.3.Final
- 17.0
+ 19.0
3.3.2
@@ -172,14 +168,14 @@
4.4
4.4
- 2.4.0
+ 2.9.0
- 3.2
+ 3.5.1
2.6
- 2.18.1
+ 2.19.1
2.7
- 1.4.12
+ 1.4.18
diff --git a/assertj/pom.xml b/assertj/pom.xml
new file mode 100644
index 0000000000..421afd40a5
--- /dev/null
+++ b/assertj/pom.xml
@@ -0,0 +1,49 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ assertj
+ 1.0.0-SNAPSHOT
+
+
+
+ com.google.guava
+ guava
+ 19.0
+
+
+ junit
+ junit
+ 4.12
+ test
+
+
+ org.assertj
+ assertj-core
+ 3.5.1
+ test
+
+
+ org.assertj
+ assertj-guava
+ 3.0.0
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.3
+
+ 1.8
+ 1.8
+
+
+
+
+
\ No newline at end of file
diff --git a/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Dog.java b/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Dog.java
new file mode 100644
index 0000000000..623f71214c
--- /dev/null
+++ b/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Dog.java
@@ -0,0 +1,19 @@
+package com.baeldung.assertj.introduction.domain;
+
+public class Dog {
+ private String name;
+ private Float weight;
+
+ public Dog(String name, Float weight) {
+ this.name = name;
+ this.weight = weight;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Float getWeight() {
+ return weight;
+ }
+}
diff --git a/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Person.java b/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Person.java
new file mode 100644
index 0000000000..90ef787ebe
--- /dev/null
+++ b/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Person.java
@@ -0,0 +1,19 @@
+package com.baeldung.assertj.introduction.domain;
+
+public class Person {
+ private String name;
+ private Integer age;
+
+ public Person(String name, Integer age) {
+ this.name = name;
+ this.age = age;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Integer getAge() {
+ return age;
+ }
+}
diff --git a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java
new file mode 100644
index 0000000000..fc134ece00
--- /dev/null
+++ b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java
@@ -0,0 +1,141 @@
+package com.baeldung.assertj.introduction;
+
+import com.baeldung.assertj.introduction.domain.Dog;
+import com.baeldung.assertj.introduction.domain.Person;
+import org.assertj.core.util.Maps;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+
+import static org.assertj.core.api.Assertions.*;
+
+public class AssertJCoreTest {
+
+ @Test
+ public void whenComparingReferences_thenNotEqual() throws Exception {
+ Dog fido = new Dog("Fido", 5.15f);
+ Dog fidosClone = new Dog("Fido", 5.15f);
+
+ assertThat(fido).isNotEqualTo(fidosClone);
+ }
+
+ @Test
+ public void whenComparingFields_thenEqual() throws Exception {
+ Dog fido = new Dog("Fido", 5.15f);
+ Dog fidosClone = new Dog("Fido", 5.15f);
+
+ assertThat(fido).isEqualToComparingFieldByFieldRecursively(fidosClone);
+ }
+
+ @Test
+ public void whenCheckingForElement_thenContains() throws Exception {
+ List list = Arrays.asList("1", "2", "3");
+
+ assertThat(list)
+ .contains("1");
+ }
+
+ @Test
+ public void whenCheckingForElement_thenMultipleAssertions() throws Exception {
+ List list = Arrays.asList("1", "2", "3");
+
+ assertThat(list).isNotEmpty();
+ assertThat(list).startsWith("1");
+ assertThat(list).doesNotContainNull();
+
+ assertThat(list)
+ .isNotEmpty()
+ .contains("1")
+ .startsWith("1")
+ .doesNotContainNull()
+ .containsSequence("2", "3");
+ }
+
+ @Test
+ public void whenCheckingRunnable_thenIsInterface() throws Exception {
+ assertThat(Runnable.class).isInterface();
+ }
+
+ @Test
+ public void whenCheckingCharacter_thenIsUnicode() throws Exception {
+ char someCharacter = 'c';
+
+ assertThat(someCharacter)
+ .isNotEqualTo('a')
+ .inUnicode()
+ .isGreaterThanOrEqualTo('b')
+ .isLowerCase();
+ }
+
+ @Test
+ public void whenAssigningNSEExToException_thenIsAssignable() throws Exception {
+ assertThat(Exception.class).isAssignableFrom(NoSuchElementException.class);
+ }
+
+ @Test
+ public void whenComparingWithOffset_thenEquals() throws Exception {
+ assertThat(5.1).isEqualTo(5, withPrecision(1d));
+ }
+
+ @Test
+ public void whenCheckingString_then() throws Exception {
+ assertThat("".isEmpty()).isTrue();
+ }
+
+ @Test
+ public void whenCheckingFile_then() throws Exception {
+ final File someFile = File.createTempFile("aaa", "bbb");
+ someFile.deleteOnExit();
+
+ assertThat(someFile)
+ .exists()
+ .isFile()
+ .canRead()
+ .canWrite();
+ }
+
+ @Test
+ public void whenCheckingIS_then() throws Exception {
+ InputStream given = new ByteArrayInputStream("foo".getBytes());
+ InputStream expected = new ByteArrayInputStream("foo".getBytes());
+
+ assertThat(given).hasSameContentAs(expected);
+ }
+
+ @Test
+ public void whenGivenMap_then() throws Exception {
+ Map map = Maps.newHashMap(2, "a");
+
+ assertThat(map)
+ .isNotEmpty()
+ .containsKey(2)
+ .doesNotContainKeys(10)
+ .contains(entry(2, "a"));
+ }
+
+ @Test
+ public void whenGivenException_then() throws Exception {
+ Exception ex = new Exception("abc");
+
+ assertThat(ex)
+ .hasNoCause()
+ .hasMessageEndingWith("c");
+ }
+
+ @Ignore // IN ORDER TO TEST, REMOVE THIS LINE
+ @Test
+ public void whenRunningAssertion_thenDescribed() throws Exception {
+ Person person = new Person("Alex", 34);
+
+ assertThat(person.getAge())
+ .as("%s's age should be equal to 100")
+ .isEqualTo(100);
+ }
+}
diff --git a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java
new file mode 100644
index 0000000000..aee803ada1
--- /dev/null
+++ b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJGuavaTest.java
@@ -0,0 +1,121 @@
+package com.baeldung.assertj.introduction;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.ArrayListMultimap;
+import com.google.common.collect.HashBasedTable;
+import com.google.common.collect.Multimap;
+import com.google.common.collect.Multimaps;
+import com.google.common.collect.Range;
+import com.google.common.collect.Table;
+import com.google.common.collect.TreeRangeMap;
+import com.google.common.io.Files;
+import org.assertj.guava.data.MapEntry;
+import org.junit.Test;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.HashSet;
+
+import static org.assertj.guava.api.Assertions.assertThat;
+import static org.assertj.guava.api.Assertions.entry;
+
+public class AssertJGuavaTest {
+
+ @Test
+ public void givenTwoEmptyFiles_whenComparingContent_thenEqual() throws Exception {
+ final File temp1 = File.createTempFile("bael", "dung1");
+ final File temp2 = File.createTempFile("bael", "dung2");
+
+ assertThat(Files.asByteSource(temp1))
+ .hasSize(0)
+ .hasSameContentAs(Files.asByteSource(temp2));
+ }
+
+ @Test
+ public void givenMultimap_whenVerifying_thenCorrect() throws Exception {
+ final Multimap mmap = ArrayListMultimap.create();
+ mmap.put(1, "one");
+ mmap.put(1, "1");
+
+ assertThat(mmap)
+ .hasSize(2)
+ .containsKeys(1)
+ .contains(entry(1, "one"))
+ .contains(entry(1, "1"));
+ }
+
+ @Test
+ public void givenMultimaps_whenVerifyingContent_thenCorrect() throws Exception {
+ final Multimap mmap1 = ArrayListMultimap.create();
+ mmap1.put(1, "one");
+ mmap1.put(1, "1");
+ mmap1.put(2, "two");
+ mmap1.put(2, "2");
+
+ final Multimap mmap1_clone = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new);
+ mmap1_clone.put(1, "one");
+ mmap1_clone.put(1, "1");
+ mmap1_clone.put(2, "two");
+ mmap1_clone.put(2, "2");
+
+ final Multimap mmap2 = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new);
+ mmap2.put(1, "one");
+ mmap2.put(1, "1");
+
+ assertThat(mmap1)
+ .containsAllEntriesOf(mmap2)
+ .containsAllEntriesOf(mmap1_clone)
+ .hasSameEntriesAs(mmap1_clone);
+ }
+
+ @Test
+ public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
+ final Optional something = Optional.of("something");
+
+ assertThat(something)
+ .isPresent()
+ .extractingValue()
+ .isEqualTo("something");
+ }
+
+ @Test
+ public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
+ final Range range = Range.openClosed("a", "g");
+
+ assertThat(range)
+ .hasOpenedLowerBound()
+ .isNotEmpty()
+ .hasClosedUpperBound()
+ .contains("b");
+ }
+
+ @Test
+ public void givenRangeMap_whenVerifying_thenShouldBeCorrect() throws Exception {
+ final TreeRangeMap map = TreeRangeMap.create();
+
+ map.put(Range.closed(0, 60), "F");
+ map.put(Range.closed(61, 70), "D");
+
+ assertThat(map)
+ .isNotEmpty()
+ .containsKeys(0)
+ .contains(MapEntry.entry(34, "F"));
+ }
+
+ @Test
+ public void givenTable_whenVerifying_thenShouldBeCorrect() throws Exception {
+ final Table table = HashBasedTable.create(2, 2);
+
+ table.put(1, "A", "PRESENT");
+ table.put(1, "B", "ABSENT");
+
+ assertThat(table)
+ .hasRowCount(1)
+ .containsValues("ABSENT")
+ .containsCell(1, "B", "ABSENT");
+ }
+
+
+
+
+}
diff --git a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java
new file mode 100644
index 0000000000..0cdbd0f7ea
--- /dev/null
+++ b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJJava8Test.java
@@ -0,0 +1,132 @@
+package com.baeldung.assertj.introduction;
+
+import org.junit.Test;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.function.Predicate;
+
+import static java.time.LocalDate.ofYearDay;
+import static java.util.Arrays.asList;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class AssertJJava8Test {
+
+ @Test
+ public void givenOptional_shouldAssert() throws Exception {
+ final Optional givenOptional = Optional.of("something");
+
+ assertThat(givenOptional)
+ .isPresent()
+ .hasValue("something");
+ }
+
+ @Test
+ public void givenPredicate_shouldAssert() throws Exception {
+ final Predicate predicate = s -> s.length() > 4;
+
+ assertThat(predicate)
+ .accepts("aaaaa", "bbbbb")
+ .rejects("a", "b")
+ .acceptsAll(asList("aaaaa", "bbbbb"))
+ .rejectsAll(asList("a", "b"));
+ }
+
+ @Test
+ public void givenLocalDate_shouldAssert() throws Exception {
+ final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
+ final LocalDate todayDate = LocalDate.now();
+
+ assertThat(givenLocalDate)
+ .isBefore(LocalDate.of(2020, 7, 8))
+ .isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
+
+ assertThat(todayDate)
+ .isAfter(LocalDate.of(1989, 7, 8))
+ .isToday();
+ }
+
+ @Test
+ public void givenLocalDateTime_shouldAssert() throws Exception {
+ final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
+
+ assertThat(givenLocalDate)
+ .isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
+ }
+
+ @Test
+ public void givenLocalTime_shouldAssert() throws Exception {
+ final LocalTime givenLocalTime = LocalTime.of(12, 15);
+
+ assertThat(givenLocalTime)
+ .isAfter(LocalTime.of(1, 0))
+ .hasSameHourAs(LocalTime.of(12, 0));
+ }
+
+ @Test
+ public void givenList_shouldAssertFlatExtracting() throws Exception {
+ final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
+
+ assertThat(givenList)
+ .flatExtracting(LocalDate::getYear)
+ .contains(2015);
+ }
+
+ @Test
+ public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
+ final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
+
+ assertThat(givenList)
+ .flatExtracting(LocalDate::isLeapYear)
+ .contains(true);
+ }
+
+ @Test
+ public void givenList_shouldAssertFlatExtractingClass() throws Exception {
+ final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
+
+ assertThat(givenList)
+ .flatExtracting(Object::getClass)
+ .contains(LocalDate.class);
+ }
+
+ @Test
+ public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
+ final List givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
+
+ assertThat(givenList)
+ .flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth)
+ .contains(2015, 6);
+ }
+
+ @Test
+ public void givenString_shouldSatisfy() throws Exception {
+ final String givenString = "someString";
+
+ assertThat(givenString)
+ .satisfies(s -> {
+ assertThat(s).isNotEmpty();
+ assertThat(s).hasSize(10);
+ });
+ }
+
+ @Test
+ public void givenString_shouldMatch() throws Exception {
+ final String emptyString = "";
+
+ assertThat(emptyString)
+ .matches(String::isEmpty);
+ }
+
+ @Test
+ public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
+ final List givenList = Arrays.asList("");
+
+ assertThat(givenList)
+ .hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
+ }
+}
diff --git a/autovalue-tutorial/pom.xml b/autovalue-tutorial/pom.xml
new file mode 100644
index 0000000000..d1f8e825fc
--- /dev/null
+++ b/autovalue-tutorial/pom.xml
@@ -0,0 +1,37 @@
+
+ 4.0.0
+ com.baeldung
+ autovalue-tutorial
+ 1.0
+ AutoValue
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.3
+
+ 7
+ 7
+ false
+
+
+
+
+
+
+ com.google.auto.value
+ auto-value
+ 1.2
+
+
+
+ junit
+ junit
+ 4.3
+ test
+
+
+
+
diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoney.java b/autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoney.java
new file mode 100644
index 0000000000..ef39f499d1
--- /dev/null
+++ b/autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoney.java
@@ -0,0 +1,15 @@
+package com.baeldung.autovalue;
+
+import com.google.auto.value.AutoValue;
+
+@AutoValue
+public abstract class AutoValueMoney {
+ public abstract String getCurrency();
+
+ public abstract long getAmount();
+
+ public static AutoValueMoney create(String currency, long amount) {
+ return new AutoValue_AutoValueMoney(currency, amount);
+
+ }
+}
diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java b/autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java
new file mode 100644
index 0000000000..a7ac93e45b
--- /dev/null
+++ b/autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java
@@ -0,0 +1,23 @@
+package com.baeldung.autovalue;
+
+import com.google.auto.value.AutoValue;
+
+@AutoValue
+public abstract class AutoValueMoneyWithBuilder {
+ public abstract String getCurrency();
+
+ public abstract long getAmount();
+
+ static Builder builder() {
+ return new AutoValue_AutoValueMoneyWithBuilder.Builder();
+ }
+
+ @AutoValue.Builder
+ abstract static class Builder {
+ abstract Builder setCurrency(String currency);
+
+ abstract Builder setAmount(long amount);
+
+ abstract AutoValueMoneyWithBuilder build();
+ }
+}
diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/Foo.java b/autovalue-tutorial/src/main/java/com/baeldung/autovalue/Foo.java
new file mode 100644
index 0000000000..bb90070f6d
--- /dev/null
+++ b/autovalue-tutorial/src/main/java/com/baeldung/autovalue/Foo.java
@@ -0,0 +1,51 @@
+package com.baeldung.autovalue;
+
+import java.util.Objects;
+
+public final class Foo {
+ private final String text;
+ private final int number;
+
+ public Foo(String text, int number) {
+ this.text = text;
+ this.number = number;
+ }
+
+ public String getText() {
+ return text;
+ }
+
+ public int getNumber() {
+ return number;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(text, number);
+ }
+
+ @Override
+ public String toString() {
+ return "Foo [text=" + text + ", number=" + number + "]";
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Foo other = (Foo) obj;
+ if (number != other.number)
+ return false;
+ if (text == null) {
+ if (other.text != null)
+ return false;
+ } else if (!text.equals(other.text))
+ return false;
+ return true;
+ }
+
+}
diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/ImmutableMoney.java b/autovalue-tutorial/src/main/java/com/baeldung/autovalue/ImmutableMoney.java
new file mode 100644
index 0000000000..04d29b6b09
--- /dev/null
+++ b/autovalue-tutorial/src/main/java/com/baeldung/autovalue/ImmutableMoney.java
@@ -0,0 +1,52 @@
+package com.baeldung.autovalue;
+public final class ImmutableMoney {
+ private final long amount;
+ private final String currency;
+ public ImmutableMoney(long amount, String currency) {
+ this.amount = amount;
+ this.currency = currency;
+ }
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + (int) (amount ^ (amount >>> 32));
+ result = prime * result
+ + ((currency == null) ? 0 : currency.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ ImmutableMoney other = (ImmutableMoney) obj;
+ if (amount != other.amount)
+ return false;
+ if (currency == null) {
+ if (other.currency != null)
+ return false;
+ } else if (!currency.equals(other.currency))
+ return false;
+ return true;
+ }
+
+ public long getAmount() {
+ return amount;
+ }
+
+ public String getCurrency() {
+ return currency;
+ }
+
+ @Override
+ public String toString() {
+ return "ImmutableMoney [amount=" + amount + ", currency=" + currency
+ + "]";
+ }
+
+}
diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/MutableMoney.java b/autovalue-tutorial/src/main/java/com/baeldung/autovalue/MutableMoney.java
new file mode 100644
index 0000000000..6cf8b75f7d
--- /dev/null
+++ b/autovalue-tutorial/src/main/java/com/baeldung/autovalue/MutableMoney.java
@@ -0,0 +1,35 @@
+package com.baeldung.autovalue;
+
+public class MutableMoney {
+ @Override
+ public String toString() {
+ return "MutableMoney [amount=" + amount + ", currency=" + currency
+ + "]";
+ }
+
+ public long getAmount() {
+ return amount;
+ }
+
+ public void setAmount(long amount) {
+ this.amount = amount;
+ }
+
+ public String getCurrency() {
+ return currency;
+ }
+
+ public void setCurrency(String currency) {
+ this.currency = currency;
+ }
+
+ private long amount;
+ private String currency;
+
+ public MutableMoney(long amount, String currency) {
+ super();
+ this.amount = amount;
+ this.currency = currency;
+ }
+
+}
diff --git a/autovalue-tutorial/src/test/java/com/baeldung/autovalue/MoneyTest.java b/autovalue-tutorial/src/test/java/com/baeldung/autovalue/MoneyTest.java
new file mode 100644
index 0000000000..af3afe84fb
--- /dev/null
+++ b/autovalue-tutorial/src/test/java/com/baeldung/autovalue/MoneyTest.java
@@ -0,0 +1,59 @@
+package com.baeldung.autovalue;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+public class MoneyTest {
+ @Test
+ public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
+ MutableMoney m1 = new MutableMoney(10000, "USD");
+ MutableMoney m2 = new MutableMoney(10000, "USD");
+ assertFalse(m1.equals(m2));
+ }
+
+ @Test
+ public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() {
+ ImmutableMoney m1 = new ImmutableMoney(10000, "USD");
+ ImmutableMoney m2 = new ImmutableMoney(10000, "USD");
+ assertTrue(m1.equals(m2));
+ }
+
+ @Test
+ public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() {
+ AutoValueMoney m = AutoValueMoney.create("USD", 10000);
+ assertEquals(m.getAmount(), 10000);
+ assertEquals(m.getCurrency(), "USD");
+ }
+
+ @Test
+ public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() {
+ AutoValueMoney m1 = AutoValueMoney.create("USD", 5000);
+ AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
+ assertTrue(m1.equals(m2));
+ }
+ @Test
+ public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
+ AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
+ AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
+ assertFalse(m1.equals(m2));
+ }
+ @Test
+ public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() {
+ AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
+ AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
+ assertTrue(m1.equals(m2));
+ }
+ @Test
+ public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
+ AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
+ AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
+ assertFalse(m1.equals(m2));
+ }
+ @Test
+ public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
+ AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
+ assertEquals(m.getAmount(), 5000);
+ assertEquals(m.getCurrency(), "USD");
+ }
+}
diff --git a/cdi/pom.xml b/cdi/pom.xml
new file mode 100644
index 0000000000..b771857938
--- /dev/null
+++ b/cdi/pom.xml
@@ -0,0 +1,52 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ cdi
+ 1.0-SNAPSHOT
+
+
+
+ org.springframework
+ spring-core
+ ${spring.version}
+
+
+ org.springframework
+ spring-context
+ ${spring.version}
+
+
+
+ org.aspectj
+ aspectjweaver
+ 1.8.9
+
+
+ org.jboss.weld.se
+ weld-se-core
+ 2.3.5.Final
+
+
+
+ junit
+ junit
+ 4.12
+ test
+
+
+ org.springframework
+ spring-test
+ ${spring.version}
+ test
+
+
+
+
+
+ 4.3.1.RELEASE
+
+
+
\ No newline at end of file
diff --git a/cdi/src/main/java/com/baeldung/interceptor/Audited.java b/cdi/src/main/java/com/baeldung/interceptor/Audited.java
new file mode 100644
index 0000000000..3df4bef95e
--- /dev/null
+++ b/cdi/src/main/java/com/baeldung/interceptor/Audited.java
@@ -0,0 +1,14 @@
+package com.baeldung.interceptor;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import javax.interceptor.InterceptorBinding;
+
+@InterceptorBinding
+@Target({ ElementType.METHOD, ElementType.TYPE })
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Audited {
+}
diff --git a/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java b/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java
new file mode 100644
index 0000000000..c62d9a4127
--- /dev/null
+++ b/cdi/src/main/java/com/baeldung/interceptor/AuditedInterceptor.java
@@ -0,0 +1,20 @@
+package com.baeldung.interceptor;
+
+import javax.interceptor.AroundInvoke;
+import javax.interceptor.Interceptor;
+import javax.interceptor.InvocationContext;
+
+@Audited
+@Interceptor
+public class AuditedInterceptor {
+ public static boolean calledBefore = false;
+ public static boolean calledAfter = false;
+
+ @AroundInvoke
+ public Object auditMethod(InvocationContext ctx) throws Exception {
+ calledBefore = true;
+ Object result = ctx.proceed();
+ calledAfter = true;
+ return result;
+ }
+}
diff --git a/cdi/src/main/java/com/baeldung/service/SuperService.java b/cdi/src/main/java/com/baeldung/service/SuperService.java
new file mode 100644
index 0000000000..e15f049342
--- /dev/null
+++ b/cdi/src/main/java/com/baeldung/service/SuperService.java
@@ -0,0 +1,10 @@
+package com.baeldung.service;
+
+import com.baeldung.interceptor.Audited;
+
+public class SuperService {
+ @Audited
+ public String deliverService(String uid) {
+ return uid;
+ }
+}
diff --git a/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java b/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java
new file mode 100644
index 0000000000..e48039706d
--- /dev/null
+++ b/cdi/src/main/java/com/baeldung/spring/aspect/SpringTestAspect.java
@@ -0,0 +1,23 @@
+package com.baeldung.spring.aspect;
+
+import java.util.List;
+
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.springframework.beans.factory.annotation.Autowired;
+
+@Aspect
+public class SpringTestAspect {
+ @Autowired
+ private List accumulator;
+
+ @Around("execution(* com.baeldung.spring.service.SpringSuperService.*(..))")
+ public Object auditMethod(ProceedingJoinPoint jp) throws Throwable {
+ String methodName = jp.getSignature().getName();
+ accumulator.add("Call to " + methodName);
+ Object obj = jp.proceed();
+ accumulator.add("Method called successfully: " + methodName);
+ return obj;
+ }
+}
diff --git a/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java b/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java
new file mode 100644
index 0000000000..b30c4a1326
--- /dev/null
+++ b/cdi/src/main/java/com/baeldung/spring/configuration/AppConfig.java
@@ -0,0 +1,30 @@
+package com.baeldung.spring.configuration;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+
+import com.baeldung.spring.aspect.SpringTestAspect;
+import com.baeldung.spring.service.SpringSuperService;
+
+@Configuration
+@EnableAspectJAutoProxy
+public class AppConfig {
+ @Bean
+ public SpringSuperService springSuperService() {
+ return new SpringSuperService();
+ }
+
+ @Bean
+ public SpringTestAspect springTestAspect() {
+ return new SpringTestAspect();
+ }
+
+ @Bean
+ public List getAccumulator() {
+ return new ArrayList();
+ }
+}
diff --git a/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java b/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java
new file mode 100644
index 0000000000..082eb2e0f8
--- /dev/null
+++ b/cdi/src/main/java/com/baeldung/spring/service/SpringSuperService.java
@@ -0,0 +1,7 @@
+package com.baeldung.spring.service;
+
+public class SpringSuperService {
+ public String getInfoFromService(String code) {
+ return code;
+ }
+}
diff --git a/cdi/src/main/resources/META-INF/beans.xml b/cdi/src/main/resources/META-INF/beans.xml
new file mode 100644
index 0000000000..d41b35e7d9
--- /dev/null
+++ b/cdi/src/main/resources/META-INF/beans.xml
@@ -0,0 +1,8 @@
+
+
+ com.baeldung.interceptor.AuditedInterceptor
+
+
\ No newline at end of file
diff --git a/cdi/src/test/java/com/baeldung/test/TestInterceptor.java b/cdi/src/test/java/com/baeldung/test/TestInterceptor.java
new file mode 100644
index 0000000000..3529a796d2
--- /dev/null
+++ b/cdi/src/test/java/com/baeldung/test/TestInterceptor.java
@@ -0,0 +1,38 @@
+package com.baeldung.test;
+
+import org.jboss.weld.environment.se.Weld;
+import org.jboss.weld.environment.se.WeldContainer;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.baeldung.interceptor.AuditedInterceptor;
+import com.baeldung.service.SuperService;
+
+public class TestInterceptor {
+ Weld weld;
+ WeldContainer container;
+
+ @Before
+ public void init() {
+ weld = new Weld();
+ container = weld.initialize();
+ }
+
+ @After
+ public void shutdown() {
+ weld.shutdown();
+ }
+
+ @Test
+ public void givenTheService_whenMethodAndInterceptorExecuted_thenOK() {
+ SuperService superService = container.select(SuperService.class).get();
+ String code = "123456";
+ superService.deliverService(code);
+
+ Assert.assertTrue(AuditedInterceptor.calledBefore);
+ Assert.assertTrue(AuditedInterceptor.calledAfter);
+ }
+
+}
diff --git a/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java b/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java
new file mode 100644
index 0000000000..1f3a8d83e3
--- /dev/null
+++ b/cdi/src/test/java/com/baeldung/test/TestSpringInterceptor.java
@@ -0,0 +1,34 @@
+package com.baeldung.test;
+
+import static org.hamcrest.CoreMatchers.is;
+
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import com.baeldung.spring.configuration.AppConfig;
+import com.baeldung.spring.service.SpringSuperService;
+
+@RunWith(SpringRunner.class)
+@ContextConfiguration(classes = { AppConfig.class })
+public class TestSpringInterceptor {
+ @Autowired
+ SpringSuperService springSuperService;
+
+ @Autowired
+ private List accumulator;
+
+ @Test
+ public void givenService_whenServiceAndAspectExecuted_thenOk() {
+ String code = "123456";
+ String result = springSuperService.getInfoFromService(code);
+ Assert.assertThat(accumulator.size(), is(2));
+ Assert.assertThat(accumulator.get(0), is("Call to getInfoFromService"));
+ Assert.assertThat(accumulator.get(1), is("Method called successfully: getInfoFromService"));
+ }
+}
diff --git a/core-java-8/.classpath b/core-java-8/.classpath
deleted file mode 100644
index 5efa587d72..0000000000
--- a/core-java-8/.classpath
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/core-java-8/.project b/core-java-8/.project
deleted file mode 100644
index 235c555abb..0000000000
--- a/core-java-8/.project
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
- core-java-8
-
-
-
-
-
- org.eclipse.jdt.core.javabuilder
-
-
-
-
- org.eclipse.m2e.core.maven2Builder
-
-
-
-
-
- org.eclipse.jem.workbench.JavaEMFNature
- org.eclipse.jdt.core.javanature
- org.eclipse.m2e.core.maven2Nature
-
-
diff --git a/core-java-8/.settings/.jsdtscope b/core-java-8/.settings/.jsdtscope
deleted file mode 100644
index 7b3f0c8b9f..0000000000
--- a/core-java-8/.settings/.jsdtscope
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/core-java-8/.settings/org.eclipse.jdt.core.prefs b/core-java-8/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index c38ccc1294..0000000000
--- a/core-java-8/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,101 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.8
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.8
diff --git a/core-java-8/.settings/org.eclipse.jdt.ui.prefs b/core-java-8/.settings/org.eclipse.jdt.ui.prefs
deleted file mode 100644
index d84d2a7f8c..0000000000
--- a/core-java-8/.settings/org.eclipse.jdt.ui.prefs
+++ /dev/null
@@ -1,57 +0,0 @@
-eclipse.preferences.version=1
-editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
-sp_cleanup.add_default_serial_version_id=true
-sp_cleanup.add_generated_serial_version_id=false
-sp_cleanup.add_missing_annotations=true
-sp_cleanup.add_missing_deprecated_annotations=true
-sp_cleanup.add_missing_methods=false
-sp_cleanup.add_missing_nls_tags=false
-sp_cleanup.add_missing_override_annotations=true
-sp_cleanup.add_missing_override_annotations_interface_methods=true
-sp_cleanup.add_serial_version_id=false
-sp_cleanup.always_use_blocks=true
-sp_cleanup.always_use_parentheses_in_expressions=true
-sp_cleanup.always_use_this_for_non_static_field_access=false
-sp_cleanup.always_use_this_for_non_static_method_access=false
-sp_cleanup.convert_functional_interfaces=false
-sp_cleanup.convert_to_enhanced_for_loop=true
-sp_cleanup.correct_indentation=true
-sp_cleanup.format_source_code=true
-sp_cleanup.format_source_code_changes_only=true
-sp_cleanup.make_local_variable_final=true
-sp_cleanup.make_parameters_final=true
-sp_cleanup.make_private_fields_final=false
-sp_cleanup.make_type_abstract_if_missing_method=false
-sp_cleanup.make_variable_declarations_final=true
-sp_cleanup.never_use_blocks=false
-sp_cleanup.never_use_parentheses_in_expressions=false
-sp_cleanup.on_save_use_additional_actions=true
-sp_cleanup.organize_imports=true
-sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
-sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
-sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
-sp_cleanup.qualify_static_member_accesses_with_declaring_class=true
-sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
-sp_cleanup.remove_private_constructors=true
-sp_cleanup.remove_trailing_whitespaces=true
-sp_cleanup.remove_trailing_whitespaces_all=true
-sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
-sp_cleanup.remove_unnecessary_casts=true
-sp_cleanup.remove_unnecessary_nls_tags=false
-sp_cleanup.remove_unused_imports=true
-sp_cleanup.remove_unused_local_variables=false
-sp_cleanup.remove_unused_private_fields=true
-sp_cleanup.remove_unused_private_members=false
-sp_cleanup.remove_unused_private_methods=true
-sp_cleanup.remove_unused_private_types=true
-sp_cleanup.sort_members=false
-sp_cleanup.sort_members_all=false
-sp_cleanup.use_anonymous_class_creation=false
-sp_cleanup.use_blocks=true
-sp_cleanup.use_blocks_only_for_return_and_throw=false
-sp_cleanup.use_lambda=false
-sp_cleanup.use_parentheses_in_expressions=false
-sp_cleanup.use_this_for_non_static_field_access=true
-sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
-sp_cleanup.use_this_for_non_static_method_access=true
-sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
diff --git a/core-java-8/.settings/org.eclipse.m2e.core.prefs b/core-java-8/.settings/org.eclipse.m2e.core.prefs
deleted file mode 100644
index f897a7f1cb..0000000000
--- a/core-java-8/.settings/org.eclipse.m2e.core.prefs
+++ /dev/null
@@ -1,4 +0,0 @@
-activeProfiles=
-eclipse.preferences.version=1
-resolveWorkspaceProjects=true
-version=1
diff --git a/core-java-8/.springBeans b/core-java-8/.springBeans
deleted file mode 100644
index a79097f40d..0000000000
--- a/core-java-8/.springBeans
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
- 1
-
-
-
-
-
-
- src/main/webapp/WEB-INF/api-servlet.xml
-
-
-
-
diff --git a/core-java-8/README.md b/core-java-8/README.md
index 9bb6bb811c..c130e6bd41 100644
--- a/core-java-8/README.md
+++ b/core-java-8/README.md
@@ -3,4 +3,22 @@
## Core Java 8 Cookbooks and Examples
### Relevant Articles:
-// - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
+- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
+- [Java – Directory Size](http://www.baeldung.com/java-folder-size)
+- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
+- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
+- [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
+- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
+- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
+- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
+- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
+- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
+- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
+- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces)
+- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture)
+- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
+- [Guide to Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
+- [The Java 8 Stream API Tutorial](http://www.baeldung.com/java-8-streams)
+- [New Features in Java 8](http://www.baeldung.com/java-8-new-features)
+- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
+- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml
index 07d3bcd146..566eb4e43a 100644
--- a/core-java-8/pom.xml
+++ b/core-java-8/pom.xml
@@ -1,10 +1,12 @@
-
+
4.0.0
- org.baeldung
- spring-rest
- 0.1-SNAPSHOT
- spring-rest
+ com.baeldung
+ 1.0.0-SNAPSHOT
+ core-java8
+
+ core-java8
@@ -40,6 +42,12 @@
3.3.2
+
+ org.slf4j
+ slf4j-api
+ ${org.slf4j.version}
+
+
@@ -56,6 +64,13 @@
test
+
+ org.assertj
+ assertj-core
+ 3.5.1
+ test
+
+
org.mockito
mockito-core
@@ -97,6 +112,9 @@
+
+ UTF-8
+
1.7.13
1.0.13
@@ -114,9 +132,9 @@
1.10.19
- 3.3
+ 3.5.1
2.6
- 2.18.1
+ 2.19.1
2.7
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java b/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java
new file mode 100644
index 0000000000..125b6fbe38
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java
@@ -0,0 +1,16 @@
+package com.baeldung.datetime;
+
+import java.time.Duration;
+import java.time.LocalTime;
+import java.time.Period;
+
+public class UseDuration {
+
+ public LocalTime modifyDates(LocalTime localTime,Duration duration){
+ return localTime.plus(duration);
+ }
+
+ public Duration getDifferenceBetweenDates(LocalTime localTime1,LocalTime localTime2){
+ return Duration.between(localTime1, localTime2);
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java
new file mode 100644
index 0000000000..47b1b3f67d
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java
@@ -0,0 +1,46 @@
+package com.baeldung.datetime;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.temporal.ChronoUnit;
+import java.time.temporal.TemporalAdjusters;
+
+public class UseLocalDate {
+
+ public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth){
+ return LocalDate.of(year, month, dayOfMonth);
+ }
+
+ public LocalDate getLocalDateUsingParseMethod(String representation){
+ return LocalDate.parse(representation);
+ }
+
+ public LocalDate getLocalDateFromClock(){
+ LocalDate localDate = LocalDate.now();
+ return localDate;
+ }
+
+ public LocalDate getNextDay(LocalDate localDate){
+ return localDate.plusDays(1);
+ }
+
+ public LocalDate getPreviousDay(LocalDate localDate){
+ return localDate.minus(1, ChronoUnit.DAYS);
+ }
+
+ public DayOfWeek getDayOfWeek(LocalDate localDate){
+ DayOfWeek day = localDate.getDayOfWeek();
+ return day;
+ }
+
+ public LocalDate getFirstDayOfMonth(){
+ LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
+ return firstDayOfMonth;
+ }
+
+ public LocalDateTime getStartOfDay(LocalDate localDate){
+ LocalDateTime startofDay = localDate.atStartOfDay();
+ return startofDay;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
new file mode 100644
index 0000000000..7aa1eaa276
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
@@ -0,0 +1,11 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDateTime;
+
+public class UseLocalDateTime {
+
+ public LocalDateTime getLocalDateTimeUsingParseMethod(String representation){
+ return LocalDateTime.parse(representation);
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java
new file mode 100644
index 0000000000..e13fd10d6f
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java
@@ -0,0 +1,35 @@
+package com.baeldung.datetime;
+
+import java.time.LocalTime;
+import java.time.temporal.ChronoUnit;
+
+public class UseLocalTime {
+
+ public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds){
+ LocalTime localTime = LocalTime.of(hour, min, seconds);
+ return localTime;
+ }
+
+ public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation){
+ LocalTime localTime = LocalTime.parse(timeRepresentation);
+ return localTime;
+ }
+
+ public LocalTime getLocalTimeFromClock(){
+ LocalTime localTime = LocalTime.now();
+ return localTime;
+ }
+
+ public LocalTime addAnHour(LocalTime localTime){
+ LocalTime newTime = localTime.plus(1,ChronoUnit.HOURS);
+ return newTime;
+ }
+
+ public int getHourFromLocalTime(LocalTime localTime){
+ return localTime.getHour();
+ }
+
+ public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute){
+ return localTime.withMinute(minute);
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java b/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java
new file mode 100644
index 0000000000..326cfad650
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java
@@ -0,0 +1,15 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDate;
+import java.time.Period;
+
+public class UsePeriod {
+
+ public LocalDate modifyDates(LocalDate localDate,Period period){
+ return localDate.plus(period);
+ }
+
+ public Period getDifferenceBetweenDates(LocalDate localDate1,LocalDate localDate2){
+ return Period.between(localDate1, localDate2);
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java b/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java
new file mode 100644
index 0000000000..1ddb096cf6
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java
@@ -0,0 +1,19 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.util.Calendar;
+import java.util.Date;
+
+public class UseToInstant {
+
+ public LocalDateTime convertDateToLocalDate(Date date){
+ LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
+ return localDateTime;
+ }
+
+ public LocalDateTime convertDateToLocalDate(Calendar calendar){
+ LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
+ return localDateTime;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
new file mode 100644
index 0000000000..0369de9835
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
@@ -0,0 +1,13 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+
+public class UseZonedDateTime {
+
+ public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime,ZoneId zoneId){
+ ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
+ return zonedDateTime;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/enums/Pizza.java b/core-java-8/src/main/java/com/baeldung/enums/Pizza.java
new file mode 100644
index 0000000000..5bc2d9a9eb
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/enums/Pizza.java
@@ -0,0 +1,91 @@
+package com.baeldung.enums;
+
+import java.util.EnumMap;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class Pizza {
+
+ private static EnumSet deliveredPizzaStatuses =
+ EnumSet.of(PizzaStatusEnum.DELIVERED);
+
+ private PizzaStatusEnum status;
+
+ public enum PizzaStatusEnum {
+ ORDERED(5) {
+ @Override
+ public boolean isOrdered() {
+ return true;
+ }
+ },
+ READY(2) {
+ @Override
+ public boolean isReady() {
+ return true;
+ }
+ },
+ DELIVERED(0) {
+ @Override
+ public boolean isDelivered() {
+ return true;
+ }
+ };
+
+ private int timeToDelivery;
+
+ public boolean isOrdered() {
+ return false;
+ }
+
+ public boolean isReady() {
+ return false;
+ }
+
+ public boolean isDelivered() {
+ return false;
+ }
+
+ public int getTimeToDelivery() {
+ return timeToDelivery;
+ }
+
+ PizzaStatusEnum(int timeToDelivery) {
+ this.timeToDelivery = timeToDelivery;
+ }
+ }
+
+ public PizzaStatusEnum getStatus() {
+ return status;
+ }
+
+ public void setStatus(PizzaStatusEnum status) {
+ this.status = status;
+ }
+
+ public boolean isDeliverable() {
+ return this.status.isReady();
+ }
+
+ public void printTimeToDeliver() {
+ System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
+ }
+
+ public static List getAllUndeliveredPizzas(List input) {
+ return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
+ }
+
+ public static EnumMap> groupPizzaByStatus(List pzList) {
+ return pzList.stream().collect(
+ Collectors.groupingBy(Pizza::getStatus,
+ () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
+ }
+
+ public void deliver() {
+ if (isDeliverable()) {
+ PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
+ this.setStatus(PizzaStatusEnum.DELIVERED);
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java
new file mode 100644
index 0000000000..ed65919387
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java
@@ -0,0 +1,18 @@
+package com.baeldung.enums;
+
+public enum PizzaDeliveryStrategy {
+ EXPRESS {
+ @Override
+ public void deliver(Pizza pz) {
+ System.out.println("Pizza will be delivered in express mode");
+ }
+ },
+ NORMAL {
+ @Override
+ public void deliver(Pizza pz) {
+ System.out.println("Pizza will be delivered in normal mode");
+ }
+ };
+
+ public abstract void deliver(Pizza pz);
+}
diff --git a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java
new file mode 100644
index 0000000000..5ccff5e959
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java
@@ -0,0 +1,22 @@
+package com.baeldung.enums;
+
+
+public enum PizzaDeliverySystemConfiguration {
+ INSTANCE;
+
+ PizzaDeliverySystemConfiguration() {
+ // Do the configuration initialization which
+ // involves overriding defaults like delivery strategy
+ }
+
+ private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
+
+ public static PizzaDeliverySystemConfiguration getInstance() {
+ return INSTANCE;
+ }
+
+ public PizzaDeliveryStrategy getDeliveryStrategy() {
+ return deliveryStrategy;
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java b/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java
new file mode 100644
index 0000000000..f1ab2d8d09
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java
@@ -0,0 +1,49 @@
+package com.baeldung.forkjoin;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.ForkJoinTask;
+import java.util.concurrent.RecursiveAction;
+import java.util.logging.Logger;
+
+public class CustomRecursiveAction extends RecursiveAction {
+
+ private String workLoad = "";
+ private static final int THRESHOLD = 4;
+
+ private static Logger logger = Logger.getAnonymousLogger();
+
+ public CustomRecursiveAction(String workLoad) {
+ this.workLoad = workLoad;
+ }
+
+ @Override
+ protected void compute() {
+
+ if (workLoad.length() > THRESHOLD) {
+ ForkJoinTask.invokeAll(createSubtasks());
+ } else {
+ processing(workLoad);
+ }
+ }
+
+ private Collection createSubtasks() {
+
+ List subtasks =
+ new ArrayList<>();
+
+ String partOne = workLoad.substring(0, workLoad.length() / 2);
+ String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length());
+
+ subtasks.add(new CustomRecursiveAction(partOne));
+ subtasks.add(new CustomRecursiveAction(partTwo));
+
+ return subtasks;
+ }
+
+ private void processing(String work) {
+ String result = work.toUpperCase();
+ logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread().getName());
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java b/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java
new file mode 100644
index 0000000000..5d4d97b805
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java
@@ -0,0 +1,51 @@
+package com.baeldung.forkjoin;
+
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.ForkJoinTask;
+import java.util.concurrent.RecursiveTask;
+
+public class CustomRecursiveTask extends RecursiveTask {
+
+ private int[] arr;
+
+ private static final int THRESHOLD = 20;
+
+ public CustomRecursiveTask(int[] arr) {
+ this.arr = arr;
+ }
+
+ @Override
+ protected Integer compute() {
+
+ if (arr.length > THRESHOLD) {
+
+ return ForkJoinTask.invokeAll(createSubtasks())
+ .stream()
+ .mapToInt(ForkJoinTask::join)
+ .sum();
+
+ } else {
+ return processing(arr);
+ }
+ }
+
+ private Collection createSubtasks() {
+ List dividedTasks = new ArrayList<>();
+ dividedTasks.add(new CustomRecursiveTask(
+ Arrays.copyOfRange(arr, 0, arr.length / 2)));
+ dividedTasks.add(new CustomRecursiveTask(
+ Arrays.copyOfRange(arr, arr.length / 2, arr.length)));
+ return dividedTasks;
+ }
+
+ private Integer processing(int[] arr) {
+ return Arrays.stream(arr)
+ .filter(a -> a > 10 && a < 27)
+ .map(a -> a * 10)
+ .sum();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java b/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java
new file mode 100644
index 0000000000..521616600f
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java
@@ -0,0 +1,10 @@
+package com.baeldung.forkjoin.util;
+
+
+import java.util.concurrent.ForkJoinPool;
+
+public class PoolUtil {
+
+ public static ForkJoinPool forkJoinPool = new ForkJoinPool(2);
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java b/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java
new file mode 100644
index 0000000000..1f89503288
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java
@@ -0,0 +1,14 @@
+package com.baeldung.java_8_features;
+
+public class Address {
+
+ private String street;
+
+ public String getStreet() {
+ return street;
+ }
+
+ public void setStreet(String street) {
+ this.street = street;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java b/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java
new file mode 100644
index 0000000000..ff9be6ab06
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java
@@ -0,0 +1,4 @@
+package com.baeldung.java_8_features;
+
+public class CustomException extends RuntimeException {
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java b/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java
new file mode 100644
index 0000000000..811937dba7
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java
@@ -0,0 +1,13 @@
+package com.baeldung.java_8_features;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class Detail {
+
+ private static final List PARTS = Arrays.asList("turbine", "pump");
+
+ public List getParts() {
+ return PARTS;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java b/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java
new file mode 100644
index 0000000000..8d6c517ac5
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java
@@ -0,0 +1,16 @@
+package com.baeldung.java_8_features;
+
+import java.util.Optional;
+
+public class OptionalAddress {
+
+ private String street;
+
+ public Optional getStreet() {
+ return Optional.ofNullable(street);
+ }
+
+ public void setStreet(String street) {
+ this.street = street;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java b/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java
new file mode 100644
index 0000000000..ff06cd21d6
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java
@@ -0,0 +1,16 @@
+package com.baeldung.java_8_features;
+
+import java.util.Optional;
+
+public class OptionalUser {
+
+ private OptionalAddress address;
+
+ public Optional getAddress() {
+ return Optional.of(address);
+ }
+
+ public void setAddress(OptionalAddress address) {
+ this.address = address;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/User.java b/core-java-8/src/main/java/com/baeldung/java_8_features/User.java
new file mode 100644
index 0000000000..3708d276c8
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/User.java
@@ -0,0 +1,40 @@
+package com.baeldung.java_8_features;
+
+import java.util.Optional;
+
+public class User {
+
+ private String name;
+
+ private Address address;
+
+ public Address getAddress() {
+ return address;
+ }
+
+ public void setAddress(Address address) {
+ this.address = address;
+ }
+
+ public User() {
+ }
+
+ public User(String name) {
+ this.name = name;
+ }
+
+ public static boolean isRealUser(User user) {
+ return true;
+ }
+
+ public String getOrThrow() {
+ String value = null;
+ Optional valueOpt = Optional.ofNullable(value);
+ String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
+ return result;
+ }
+
+ public boolean isLegalName(String name) {
+ return name.length() > 3 && name.length() < 16;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java b/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java
new file mode 100644
index 0000000000..011173bcaf
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java
@@ -0,0 +1,18 @@
+package com.baeldung.java_8_features;
+
+public interface Vehicle {
+
+ void moveTo(long altitude, long longitude);
+
+ static String producer() {
+ return "N&F Vehicles";
+ }
+
+ default long[] startPosition() {
+ return new long[]{23, 15};
+ }
+
+ default String getOverview() {
+ return "ATV made by " + producer();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java b/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java
new file mode 100644
index 0000000000..83e55f5f4d
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java
@@ -0,0 +1,9 @@
+package com.baeldung.java_8_features;
+
+public class VehicleImpl implements Vehicle {
+
+ @Override
+ public void moveTo(long altitude, long longitude) {
+ //do nothing
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/streamApi/Product.java b/core-java-8/src/main/java/com/baeldung/streamApi/Product.java
new file mode 100644
index 0000000000..18f3a61904
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/streamApi/Product.java
@@ -0,0 +1,51 @@
+package com.baeldung.streamApi;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+/**
+ * Created by Alex Vengr
+ */
+public class Product {
+
+ private int price;
+
+ private String name;
+
+ private boolean utilize;
+
+ public Product(int price, String name) {
+ this(price);
+ this.name = name;
+ }
+
+ public Product(int price) {
+ this.price = price;
+ }
+
+ public Product() {
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public void setPrice(int price) {
+ this.price = price;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+ public static Stream streamOf(List list) {
+ return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/threadpool/CountingTask.java b/core-java-8/src/main/java/com/baeldung/threadpool/CountingTask.java
new file mode 100644
index 0000000000..05aa14c5ae
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/threadpool/CountingTask.java
@@ -0,0 +1,22 @@
+package com.baeldung.threadpool;
+
+import java.util.concurrent.ForkJoinTask;
+import java.util.concurrent.RecursiveTask;
+import java.util.stream.Collectors;
+
+public class CountingTask extends RecursiveTask {
+
+ private final TreeNode node;
+
+ public CountingTask(TreeNode node) {
+ this.node = node;
+ }
+
+ @Override
+ protected Integer compute() {
+ return node.value + node.children.stream()
+ .map(childNode -> new CountingTask(childNode).fork())
+ .collect(Collectors.summingInt(ForkJoinTask::join));
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java b/core-java-8/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java
new file mode 100644
index 0000000000..4775fde930
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java
@@ -0,0 +1,29 @@
+package com.baeldung.threadpool;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import com.google.common.util.concurrent.MoreExecutors;
+
+/**
+ * This class demonstrates the usage of Guava's exiting executor services that keep the VM from hanging.
+ * Without the exiting executor service, the task would hang indefinitely.
+ * This behaviour cannot be demonstrated in JUnit tests, as JUnit kills the VM after the tests.
+ */
+public class ExitingExecutorServiceExample {
+
+ public static void main(String... args) {
+
+ ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
+ ExecutorService executorService = MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS);
+
+ executorService.submit(() -> {
+ while (true) {
+ }
+ });
+
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/threadpool/TreeNode.java b/core-java-8/src/main/java/com/baeldung/threadpool/TreeNode.java
new file mode 100644
index 0000000000..9b43152074
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/threadpool/TreeNode.java
@@ -0,0 +1,18 @@
+package com.baeldung.threadpool;
+
+import java.util.Set;
+
+import com.google.common.collect.Sets;
+
+public class TreeNode {
+
+ int value;
+
+ Set children;
+
+ public TreeNode(int value, TreeNode... children) {
+ this.value = value;
+ this.children = Sets.newHashSet(children);
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java
new file mode 100644
index 0000000000..6648d5f926
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java
@@ -0,0 +1,30 @@
+package com.baeldung.unzip;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+public class UnzipFile {
+ public static void main(final String[] args) throws IOException {
+ final String fileZip = "src/main/resources/compressed.zip";
+ final byte[] buffer = new byte[1024];
+ final ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
+ ZipEntry zipEntry = zis.getNextEntry();
+ while (zipEntry != null) {
+ final String fileName = zipEntry.getName();
+ final File newFile = new File("src/main/resources/unzipTest/" + fileName);
+ final FileOutputStream fos = new FileOutputStream(newFile);
+ int len;
+ while ((len = zis.read(buffer)) > 0) {
+ fos.write(buffer, 0, len);
+ }
+ fos.close();
+ zipEntry = zis.getNextEntry();
+ }
+ zis.closeEntry();
+ zis.close();
+ }
+}
\ No newline at end of file
diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java b/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java
new file mode 100644
index 0000000000..7da71a093d
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java
@@ -0,0 +1,43 @@
+package com.baeldung.zip;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+public class ZipDirectory {
+ public static void main(final String[] args) throws IOException {
+ final String sourceFile = "src/main/resources/zipTest";
+ final FileOutputStream fos = new FileOutputStream("src/main/resources/dirCompressed.zip");
+ final ZipOutputStream zipOut = new ZipOutputStream(fos);
+ final File fileToZip = new File(sourceFile);
+
+ zipFile(fileToZip, fileToZip.getName(), zipOut);
+ zipOut.close();
+ fos.close();
+ }
+
+ private static void zipFile(final File fileToZip, final String fileName, final ZipOutputStream zipOut) throws IOException {
+ if (fileToZip.isHidden()) {
+ return;
+ }
+ if (fileToZip.isDirectory()) {
+ final File[] children = fileToZip.listFiles();
+ for (final File childFile : children) {
+ zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
+ }
+ return;
+ }
+ final FileInputStream fis = new FileInputStream(fileToZip);
+ final ZipEntry zipEntry = new ZipEntry(fileName);
+ zipOut.putNextEntry(zipEntry);
+ final byte[] bytes = new byte[1024];
+ int length;
+ while ((length = fis.read(bytes)) >= 0) {
+ zipOut.write(bytes, 0, length);
+ }
+ fis.close();
+ }
+}
\ No newline at end of file
diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java
new file mode 100644
index 0000000000..f9ccac9713
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java
@@ -0,0 +1,28 @@
+package com.baeldung.zip;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+public class ZipFile {
+ public static void main(final String[] args) throws IOException {
+ final String sourceFile = "src/main/resources/zipTest/test1.txt";
+ final FileOutputStream fos = new FileOutputStream("src/main/resources/compressed.zip");
+ final ZipOutputStream zipOut = new ZipOutputStream(fos);
+ final File fileToZip = new File(sourceFile);
+ final FileInputStream fis = new FileInputStream(fileToZip);
+ final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
+ zipOut.putNextEntry(zipEntry);
+ final byte[] bytes = new byte[1024];
+ int length;
+ while ((length = fis.read(bytes)) >= 0) {
+ zipOut.write(bytes, 0, length);
+ }
+ zipOut.close();
+ fis.close();
+ fos.close();
+ }
+}
\ No newline at end of file
diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java b/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java
new file mode 100644
index 0000000000..fc86147e43
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java
@@ -0,0 +1,33 @@
+package com.baeldung.zip;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+public class ZipMultipleFiles {
+ public static void main(final String[] args) throws IOException {
+ final List srcFiles = Arrays.asList("src/main/resources/zipTest/test1.txt", "src/main/resources/zipTest/test2.txt");
+ final FileOutputStream fos = new FileOutputStream("src/main/resources/multiCompressed.zip");
+ final ZipOutputStream zipOut = new ZipOutputStream(fos);
+ for (final String srcFile : srcFiles) {
+ final File fileToZip = new File(srcFile);
+ final FileInputStream fis = new FileInputStream(fileToZip);
+ final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
+ zipOut.putNextEntry(zipEntry);
+
+ final byte[] bytes = new byte[1024];
+ int length;
+ while ((length = fis.read(bytes)) >= 0) {
+ zipOut.write(bytes, 0, length);
+ }
+ fis.close();
+ }
+ zipOut.close();
+ fos.close();
+ }
+}
\ No newline at end of file
diff --git a/core-java-8/src/main/resources/compressed.zip b/core-java-8/src/main/resources/compressed.zip
new file mode 100644
index 0000000000..03f840ae2b
Binary files /dev/null and b/core-java-8/src/main/resources/compressed.zip differ
diff --git a/core-java-8/src/main/resources/dirCompressed.zip b/core-java-8/src/main/resources/dirCompressed.zip
new file mode 100644
index 0000000000..f42d3aa5c6
Binary files /dev/null and b/core-java-8/src/main/resources/dirCompressed.zip differ
diff --git a/core-java-8/src/main/resources/fileTest.txt b/core-java-8/src/main/resources/fileTest.txt
new file mode 100644
index 0000000000..ce4bea208b
--- /dev/null
+++ b/core-java-8/src/main/resources/fileTest.txt
@@ -0,0 +1 @@
+Hello World from fileTest.txt!!!
\ No newline at end of file
diff --git a/core-java-8/src/main/resources/logback.xml b/core-java-8/src/main/resources/logback.xml
index 62d0ea5037..eefdc7a337 100644
--- a/core-java-8/src/main/resources/logback.xml
+++ b/core-java-8/src/main/resources/logback.xml
@@ -10,7 +10,7 @@
-
+
\ No newline at end of file
diff --git a/core-java-8/src/main/resources/multiCompressed.zip b/core-java-8/src/main/resources/multiCompressed.zip
new file mode 100644
index 0000000000..002e70ef81
Binary files /dev/null and b/core-java-8/src/main/resources/multiCompressed.zip differ
diff --git a/core-java-8/src/main/resources/unzipTest/test1.txt b/core-java-8/src/main/resources/unzipTest/test1.txt
new file mode 100644
index 0000000000..c57eff55eb
--- /dev/null
+++ b/core-java-8/src/main/resources/unzipTest/test1.txt
@@ -0,0 +1 @@
+Hello World!
\ No newline at end of file
diff --git a/core-java-8/src/main/resources/zipTest/test1.txt b/core-java-8/src/main/resources/zipTest/test1.txt
new file mode 100644
index 0000000000..c57eff55eb
--- /dev/null
+++ b/core-java-8/src/main/resources/zipTest/test1.txt
@@ -0,0 +1 @@
+Hello World!
\ No newline at end of file
diff --git a/core-java-8/src/main/resources/zipTest/test2.txt b/core-java-8/src/main/resources/zipTest/test2.txt
new file mode 100644
index 0000000000..f0fb0f14d1
--- /dev/null
+++ b/core-java-8/src/main/resources/zipTest/test2.txt
@@ -0,0 +1 @@
+My Name is John
\ No newline at end of file
diff --git a/core-java-8/src/main/resources/zipTest/testFolder/test3.txt b/core-java-8/src/main/resources/zipTest/testFolder/test3.txt
new file mode 100644
index 0000000000..882edb168e
--- /dev/null
+++ b/core-java-8/src/main/resources/zipTest/testFolder/test3.txt
@@ -0,0 +1 @@
+My Name is Tom
\ No newline at end of file
diff --git a/core-java-8/src/main/resources/zipTest/testFolder/test4.txt b/core-java-8/src/main/resources/zipTest/testFolder/test4.txt
new file mode 100644
index 0000000000..a78c3fadc8
--- /dev/null
+++ b/core-java-8/src/main/resources/zipTest/testFolder/test4.txt
@@ -0,0 +1 @@
+My Name is Jane
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/CharToStringTest.java b/core-java-8/src/test/java/com/baeldung/CharToStringTest.java
new file mode 100644
index 0000000000..d91016d104
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/CharToStringTest.java
@@ -0,0 +1,53 @@
+package com.baeldung;
+
+import org.junit.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class CharToStringTest {
+
+ @Test
+ public void givenChar_whenCallingStringValueOf_shouldConvertToString(){
+ final char givenChar = 'x';
+
+ final String result = String.valueOf(givenChar);
+
+ assertThat(result).isEqualTo("x");
+ }
+
+ @Test
+ public void givenChar_whenCallingToStringOnCharacter_shouldConvertToString(){
+ final char givenChar = 'x';
+
+ final String result = Character.toString(givenChar);
+
+ assertThat(result).isEqualTo("x");
+ }
+
+ @Test
+ public void givenChar_whenCallingCharacterConstructor_shouldConvertToString3(){
+ final char givenChar = 'x';
+
+ final String result = new Character(givenChar).toString();
+
+ assertThat(result).isEqualTo("x");
+ }
+
+ @Test
+ public void givenChar_whenConcatenated_shouldConvertToString4(){
+ final char givenChar = 'x';
+
+ final String result = givenChar + "";
+
+ assertThat(result).isEqualTo("x");
+ }
+
+ @Test
+ public void givenChar_whenFormated_shouldConvertToString5(){
+ final char givenChar = 'x';
+
+ final String result = String.format("%c", givenChar);
+
+ assertThat(result).isEqualTo("x");
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java b/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java
new file mode 100644
index 0000000000..1918c801dc
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/RandomListElementTest.java
@@ -0,0 +1,71 @@
+package com.baeldung;
+
+import com.google.common.collect.Lists;
+import org.junit.Test;
+
+import java.util.*;
+import java.util.concurrent.ThreadLocalRandom;
+
+public class RandomListElementTest {
+
+ @Test
+ public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingRandom() {
+ List givenList = Lists.newArrayList(1, 2, 3);
+ Random rand = new Random();
+
+ givenList.get(rand.nextInt(givenList.size()));
+ }
+
+ @Test
+ public void givenList_whenRandomIndexChosen_shouldReturnARandomElementUsingMathRandom() {
+ List givenList = Lists.newArrayList(1, 2, 3);
+
+ givenList.get((int)(Math.random() * givenList.size()));
+ }
+
+ @Test
+ public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsRepeat() {
+ Random rand = new Random();
+ List givenList = Lists.newArrayList("one", "two", "three", "four");
+
+ int numberOfElements = 2;
+
+ for (int i = 0; i < numberOfElements; i++) {
+ int randomIndex = rand.nextInt(givenList.size());
+ givenList.get(randomIndex);
+ }
+ }
+
+ @Test
+ public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsNoRepeat() {
+ Random rand = new Random();
+ List givenList = Lists.newArrayList("one", "two", "three", "four");
+
+ int numberOfElements = 2;
+
+ for (int i = 0; i < numberOfElements; i++) {
+ int randomIndex = rand.nextInt(givenList.size());
+ givenList.get(randomIndex);
+ givenList.remove(randomIndex);
+ }
+ }
+
+ @Test
+ public void givenList_whenSeriesLengthChosen_shouldReturnRandomSeries() {
+ List givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6);
+ Collections.shuffle(givenList);
+
+ int randomSeriesLength = 3;
+
+ givenList.subList(0, randomSeriesLength - 1);
+ }
+
+ @Test
+ public void givenList_whenRandomIndexChosen_shouldReturnElementThreadSafely() {
+ List givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6);
+ int randomIndex = ThreadLocalRandom.current().nextInt(10) % givenList.size();
+
+ givenList.get(randomIndex);
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java b/core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java
new file mode 100644
index 0000000000..6c1493d89b
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/StringToIntOrIntegerTest.java
@@ -0,0 +1,62 @@
+package com.baeldung;
+
+import com.google.common.primitives.Ints;
+import org.junit.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class StringToIntOrIntegerTest {
+
+ @Test
+ public void givenString_whenParsingInt_shouldConvertToInt() {
+ String givenString = "42";
+
+ int result = Integer.parseInt(givenString);
+
+ assertThat(result).isEqualTo(42);
+ }
+
+
+ @Test
+ public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
+ String givenString = "42";
+
+ Integer result = Integer.valueOf(givenString);
+
+ assertThat(result).isEqualTo(new Integer(42));
+ }
+
+ @Test
+ public void givenString_whenCallingIntegerConstructor_shouldConvertToInt() {
+ String givenString = "42";
+
+ Integer result = new Integer(givenString);
+
+ assertThat(result).isEqualTo(new Integer(42));
+ }
+
+ @Test
+ public void givenString_whenCallingIntegerDecode_shouldConvertToInt() {
+ String givenString = "42";
+
+ int result = Integer.decode(givenString);
+
+ assertThat(result).isEqualTo(42);
+ }
+
+ @Test
+ public void givenString_whenTryParse_shouldConvertToInt() {
+ String givenString = "42";
+
+ Integer result = Ints.tryParse(givenString);
+
+ assertThat(result).isEqualTo(42);
+ }
+
+ @Test(expected = NumberFormatException.class)
+ public void givenInvalidInput_whenParsingInt_shouldThrow() {
+ String givenString = "nan";
+ Integer.parseInt(givenString);
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java b/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java
new file mode 100644
index 0000000000..d94f72b685
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java
@@ -0,0 +1,265 @@
+package com.baeldung.collectors;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Sets;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.DoubleSummaryStatistics;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.BinaryOperator;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collector;
+
+import static com.google.common.collect.Sets.newHashSet;
+import static java.util.stream.Collectors.averagingDouble;
+import static java.util.stream.Collectors.collectingAndThen;
+import static java.util.stream.Collectors.counting;
+import static java.util.stream.Collectors.groupingBy;
+import static java.util.stream.Collectors.joining;
+import static java.util.stream.Collectors.maxBy;
+import static java.util.stream.Collectors.partitioningBy;
+import static java.util.stream.Collectors.summarizingDouble;
+import static java.util.stream.Collectors.summingDouble;
+import static java.util.stream.Collectors.toCollection;
+import static java.util.stream.Collectors.toList;
+import static java.util.stream.Collectors.toMap;
+import static java.util.stream.Collectors.toSet;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+public class Java8CollectorsTest {
+
+ private final List givenList = Arrays.asList("a", "bb", "ccc", "dd");
+
+ @Test
+ public void whenCollectingToList_shouldCollectToList() throws Exception {
+ final List result = givenList.stream()
+ .collect(toList());
+
+ assertThat(result)
+ .containsAll(givenList);
+ }
+
+ @Test
+ public void whenCollectingToList_shouldCollectToSet() throws Exception {
+ final Set result = givenList.stream()
+ .collect(toSet());
+
+ assertThat(result)
+ .containsAll(givenList);
+ }
+
+ @Test
+ public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
+ final List result = givenList.stream()
+ .collect(toCollection(LinkedList::new));
+
+ assertThat(result)
+ .containsAll(givenList)
+ .isInstanceOf(LinkedList.class);
+ }
+
+ @Test
+ public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
+ assertThatThrownBy(() -> {
+ givenList.stream()
+ .collect(toCollection(ImmutableList::of));
+ }).isInstanceOf(UnsupportedOperationException.class);
+
+ }
+
+ @Test
+ public void whenCollectingToMap_shouldCollectToMap() throws Exception {
+ final Map result = givenList.stream()
+ .collect(toMap(Function.identity(), String::length));
+
+ assertThat(result)
+ .containsEntry("a", 1)
+ .containsEntry("bb", 2)
+ .containsEntry("ccc", 3)
+ .containsEntry("dd", 2);
+ }
+
+ @Test
+ public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
+ final Map result = givenList.stream()
+ .collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
+
+ assertThat(result)
+ .containsEntry("a", 1)
+ .containsEntry("bb", 2)
+ .containsEntry("ccc", 3)
+ .containsEntry("dd", 2);
+ }
+
+ @Test
+ public void whenCollectingAndThen_shouldCollect() throws Exception {
+ final List result = givenList.stream()
+ .collect(collectingAndThen(toList(), ImmutableList::copyOf));
+
+ assertThat(result)
+ .containsAll(givenList)
+ .isInstanceOf(ImmutableList.class);
+ }
+
+ @Test
+ public void whenJoining_shouldJoin() throws Exception {
+ final String result = givenList.stream()
+ .collect(joining());
+
+ assertThat(result)
+ .isEqualTo("abbcccdd");
+ }
+
+ @Test
+ public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
+ final String result = givenList.stream()
+ .collect(joining(" "));
+
+ assertThat(result)
+ .isEqualTo("a bb ccc dd");
+ }
+
+ @Test
+ public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
+ final String result = givenList.stream()
+ .collect(joining(" ", "PRE-", "-POST"));
+
+ assertThat(result)
+ .isEqualTo("PRE-a bb ccc dd-POST");
+ }
+
+ @Test
+ public void whenPartitioningBy_shouldPartition() throws Exception {
+ final Map> result = givenList.stream()
+ .collect(partitioningBy(s -> s.length() > 2));
+
+ assertThat(result)
+ .containsKeys(true, false)
+ .satisfies(booleanListMap -> {
+ assertThat(booleanListMap.get(true))
+ .contains("ccc");
+
+ assertThat(booleanListMap.get(false))
+ .contains("a", "bb", "dd");
+ });
+ }
+
+ @Test
+ public void whenCounting_shouldCount() throws Exception {
+ final Long result = givenList.stream()
+ .collect(counting());
+
+ assertThat(result)
+ .isEqualTo(4);
+ }
+
+ @Test
+ public void whenSummarizing_shouldSummarize() throws Exception {
+ final DoubleSummaryStatistics result = givenList.stream()
+ .collect(summarizingDouble(String::length));
+
+ assertThat(result.getAverage())
+ .isEqualTo(2);
+ assertThat(result.getCount())
+ .isEqualTo(4);
+ assertThat(result.getMax())
+ .isEqualTo(3);
+ assertThat(result.getMin())
+ .isEqualTo(1);
+ assertThat(result.getSum())
+ .isEqualTo(8);
+ }
+
+ @Test
+ public void whenAveraging_shouldAverage() throws Exception {
+ final Double result = givenList.stream()
+ .collect(averagingDouble(String::length));
+
+ assertThat(result)
+ .isEqualTo(2);
+ }
+
+ @Test
+ public void whenSumming_shouldSum() throws Exception {
+ final Double result = givenList.stream()
+ .collect(summingDouble(String::length));
+
+ assertThat(result)
+ .isEqualTo(8);
+ }
+
+ @Test
+ public void whenMaxingBy_shouldMaxBy() throws Exception {
+ final Optional result = givenList.stream()
+ .collect(maxBy(Comparator.naturalOrder()));
+
+ assertThat(result)
+ .isPresent()
+ .hasValue("dd");
+ }
+
+ @Test
+ public void whenGroupingBy_shouldGroupBy() throws Exception {
+ final Map> result = givenList.stream()
+ .collect(groupingBy(String::length, toSet()));
+
+ assertThat(result)
+ .containsEntry(1, newHashSet("a"))
+ .containsEntry(2, newHashSet("bb", "dd"))
+ .containsEntry(3, newHashSet("ccc"));
+ }
+
+
+ @Test
+ public void whenCreatingCustomCollector_shouldCollect() throws Exception {
+ final ImmutableSet result = givenList.stream()
+ .collect(toImmutableSet());
+
+ assertThat(result)
+ .isInstanceOf(ImmutableSet.class)
+ .contains("a", "bb", "ccc", "dd");
+
+ }
+
+ private static ImmutableSetCollector toImmutableSet() {
+ return new ImmutableSetCollector<>();
+ }
+
+ private static class ImmutableSetCollector implements Collector, ImmutableSet> {
+
+ @Override
+ public Supplier> supplier() {
+ return ImmutableSet::builder;
+ }
+
+ @Override
+ public BiConsumer, T> accumulator() {
+ return ImmutableSet.Builder::add;
+ }
+
+ @Override
+ public BinaryOperator> combiner() {
+ return (left, right) -> left.addAll(right.build());
+ }
+
+ @Override
+ public Function, ImmutableSet> finisher() {
+ return ImmutableSet.Builder::build;
+ }
+
+ @Override
+ public Set characteristics() {
+ return Sets.immutableEnumSet(Characteristics.UNORDERED);
+ }
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java
new file mode 100644
index 0000000000..5363a73afa
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/completablefuture/CompletableFutureTest.java
@@ -0,0 +1,209 @@
+package com.baeldung.completablefuture;
+
+import java.util.concurrent.*;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class CompletableFutureTest {
+
+ @Test
+ public void whenRunningCompletableFutureAsynchronously_thenGetMethodWaitsForResult() throws InterruptedException, ExecutionException {
+
+ Future completableFuture = calculateAsync();
+
+ String result = completableFuture.get();
+ assertEquals("Hello", result);
+
+ }
+
+ public Future calculateAsync() throws InterruptedException {
+ CompletableFuture completableFuture = new CompletableFuture<>();
+
+ Executors.newCachedThreadPool().submit(() -> {
+ Thread.sleep(500);
+ completableFuture.complete("Hello");
+ return null;
+ });
+
+ return completableFuture;
+ }
+
+ @Test
+ public void whenRunningCompletableFutureWithResult_thenGetMethodReturnsImmediately() throws InterruptedException, ExecutionException {
+
+ Future completableFuture = CompletableFuture.completedFuture("Hello");
+
+ String result = completableFuture.get();
+ assertEquals("Hello", result);
+
+ }
+
+
+ public Future calculateAsyncWithCancellation() throws InterruptedException {
+ CompletableFuture completableFuture = new CompletableFuture<>();
+
+ Executors.newCachedThreadPool().submit(() -> {
+ Thread.sleep(500);
+ completableFuture.cancel(false);
+ return null;
+ });
+
+ return completableFuture;
+ }
+
+
+ @Test(expected = CancellationException.class)
+ public void whenCancelingTheFuture_thenThrowsCancellationException() throws ExecutionException, InterruptedException {
+
+ Future future = calculateAsyncWithCancellation();
+ future.get();
+
+ }
+
+ @Test
+ public void whenCreatingCompletableFutureWithSupplyAsync_thenFutureReturnsValue() throws ExecutionException, InterruptedException {
+
+ CompletableFuture future = CompletableFuture.supplyAsync(() -> "Hello");
+
+ assertEquals("Hello", future.get());
+
+ }
+
+ @Test
+ public void whenAddingThenAcceptToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
+
+ CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
+
+ CompletableFuture future = completableFuture.thenAccept(s -> System.out.println("Computation returned: " + s));
+
+ future.get();
+
+ }
+
+ @Test
+ public void whenAddingThenRunToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
+
+ CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
+
+ CompletableFuture future = completableFuture.thenRun(() -> System.out.println("Computation finished."));
+
+ future.get();
+
+ }
+
+ @Test
+ public void whenAddingThenApplyToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
+
+ CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
+
+ CompletableFuture future = completableFuture.thenApply(s -> s + " World");
+
+ assertEquals("Hello World", future.get());
+
+ }
+
+ @Test
+ public void whenUsingThenCompose_thenFuturesExecuteSequentially() throws ExecutionException, InterruptedException {
+
+ CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
+ .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " World"));
+
+ assertEquals("Hello World", completableFuture.get());
+
+ }
+
+ @Test
+ public void whenUsingThenCombine_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
+
+ CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello")
+ .thenCombine(CompletableFuture.supplyAsync(() -> " World"),
+ (s1, s2) -> s1 + s2);
+
+ assertEquals("Hello World", completableFuture.get());
+
+ }
+
+ @Test
+ public void whenUsingThenAcceptBoth_thenWaitForExecutionOfBothFutures() throws ExecutionException, InterruptedException {
+
+ CompletableFuture.supplyAsync(() -> "Hello")
+ .thenAcceptBoth(CompletableFuture.supplyAsync(() -> " World"),
+ (s1, s2) -> System.out.println(s1 + s2));
+
+ }
+
+ @Test
+ public void whenFutureCombinedWithAllOfCompletes_thenAllFuturesAreDone() throws ExecutionException, InterruptedException {
+
+ CompletableFuture future1 = CompletableFuture.supplyAsync(() -> "Hello");
+ CompletableFuture future2 = CompletableFuture.supplyAsync(() -> "Beautiful");
+ CompletableFuture future3 = CompletableFuture.supplyAsync(() -> "World");
+
+ CompletableFuture combinedFuture = CompletableFuture.allOf(future1, future2, future3);
+
+ // ...
+
+ combinedFuture.get();
+
+ assertTrue(future1.isDone());
+ assertTrue(future2.isDone());
+ assertTrue(future3.isDone());
+
+ String combined = Stream.of(future1, future2, future3)
+ .map(CompletableFuture::join)
+ .collect(Collectors.joining(" "));
+
+ assertEquals("Hello Beautiful World", combined);
+
+ }
+
+ @Test
+ public void whenFutureThrows_thenHandleMethodReceivesException() throws ExecutionException, InterruptedException {
+
+ String name = null;
+
+ // ...
+
+ CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> {
+ if (name == null) {
+ throw new RuntimeException("Computation error!");
+ }
+ return "Hello, " + name;
+ }).handle((s, t) -> s != null ? s : "Hello, Stranger!");
+
+ assertEquals("Hello, Stranger!", completableFuture.get());
+
+ }
+
+ @Test(expected = ExecutionException.class)
+ public void whenCompletingFutureExceptionally_thenGetMethodThrows() throws ExecutionException, InterruptedException {
+
+ CompletableFuture completableFuture = new CompletableFuture<>();
+
+ // ...
+
+ completableFuture.completeExceptionally(new RuntimeException("Calculation failed!"));
+
+ // ...
+
+ completableFuture.get();
+
+ }
+
+ @Test
+ public void whenAddingThenApplyAsyncToFuture_thenFunctionExecutesAfterComputationIsFinished() throws ExecutionException, InterruptedException {
+
+ CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> "Hello");
+
+ CompletableFuture future = completableFuture.thenApplyAsync(s -> s + " World");
+
+ assertEquals("Hello World", future.get());
+
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java b/core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java
new file mode 100644
index 0000000000..a543c80eaf
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java
@@ -0,0 +1,19 @@
+package com.baeldung.dateapi;
+
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+
+public class ConversionExample {
+ public static void main(String[] args) {
+ Instant instantFromCalendar = GregorianCalendar.getInstance().toInstant();
+ ZonedDateTime zonedDateTimeFromCalendar = new GregorianCalendar().toZonedDateTime();
+ Date dateFromInstant = Date.from(Instant.now());
+ GregorianCalendar calendarFromZonedDateTime = GregorianCalendar.from(ZonedDateTime.now());
+ Instant instantFromDate = new Date().toInstant();
+ ZoneId zoneIdFromTimeZone = TimeZone.getTimeZone("PST").toZoneId();
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java b/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java
new file mode 100644
index 0000000000..4bce40c2d9
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java
@@ -0,0 +1,89 @@
+package com.baeldung.dateapi;
+
+import org.junit.Test;
+
+import java.text.ParseException;
+import java.time.Duration;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.Month;
+import java.time.YearMonth;
+import java.time.format.DateTimeFormatter;
+import java.time.temporal.ChronoUnit;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class JavaUtilTimeTest {
+
+ @Test
+ public void currentTime() {
+ final LocalDate now = LocalDate.now();
+
+ System.out.println(now);
+ // there is not much to test here
+ }
+
+ @Test
+ public void specificTime() {
+ LocalDate birthDay = LocalDate.of(1990, Month.DECEMBER, 15);
+
+ System.out.println(birthDay);
+ // there is not much to test here
+ }
+
+ @Test
+ public void extractMonth() {
+ Month month = LocalDate.of(1990, Month.DECEMBER, 15).getMonth();
+
+ assertThat(month).isEqualTo(Month.DECEMBER);
+ }
+
+ @Test
+ public void subtractTime() {
+ LocalDateTime fiveHoursBefore = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).minusHours(5);
+
+ assertThat(fiveHoursBefore.getHour()).isEqualTo(10);
+ }
+
+ @Test
+ public void alterField() {
+ LocalDateTime inJune = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).with(Month.JUNE);
+
+ assertThat(inJune.getMonth()).isEqualTo(Month.JUNE);
+ }
+
+ @Test
+ public void truncate() {
+ LocalTime truncated = LocalTime.of(15, 12, 34).truncatedTo(ChronoUnit.HOURS);
+
+ assertThat(truncated).isEqualTo(LocalTime.of(15, 0, 0));
+ }
+
+ @Test
+ public void getTimeSpan() {
+ LocalDateTime now = LocalDateTime.now();
+ LocalDateTime hourLater = now.plusHours(1);
+ Duration span = Duration.between(now, hourLater);
+
+ assertThat(span).isEqualTo(Duration.ofHours(1));
+ }
+
+ @Test
+ public void formatAndParse() throws ParseException {
+ LocalDate someDate = LocalDate.of(2016, 12, 7);
+ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+ String formattedDate = someDate.format(formatter);
+ LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);
+
+ assertThat(formattedDate).isEqualTo("2016-12-07");
+ assertThat(parsedDate).isEqualTo(someDate);
+ }
+
+ @Test
+ public void daysInMonth() {
+ int daysInMonth = YearMonth.of(1990, 2).lengthOfMonth();
+
+ assertThat(daysInMonth).isEqualTo(28);
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java
new file mode 100644
index 0000000000..8af33393be
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java
@@ -0,0 +1,55 @@
+package com.baeldung.datetime;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.Month;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseLocalDateTest {
+
+ UseLocalDate useLocalDate = new UseLocalDate();
+
+ @Test
+ public void givenValues_whenUsingFactoryOf_thenLocalDate(){
+ Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingFactoryOfMethod(2016,5,10).toString());
+ }
+
+ @Test
+ public void givenString_whenUsingParse_thenLocalDate(){
+ Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
+ }
+
+ @Test
+ public void whenUsingClock_thenLocalDate(){
+ Assert.assertEquals(LocalDate.now(),useLocalDate.getLocalDateFromClock());
+ }
+
+ @Test
+ public void givenDate_whenUsingPlus_thenNextDay(){
+ Assert.assertEquals(LocalDate.now().plusDays(1),useLocalDate.getNextDay(LocalDate.now()));
+ }
+
+ @Test
+ public void givenDate_whenUsingMinus_thenPreviousDay(){
+ Assert.assertEquals(LocalDate.now().minusDays(1),useLocalDate.getPreviousDay(LocalDate.now()));
+ }
+
+ @Test
+ public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek(){
+ Assert.assertEquals(DayOfWeek.SUNDAY,useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
+ }
+
+ @Test
+ public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth(){
+ Assert.assertEquals(1,useLocalDate.getFirstDayOfMonth().getDayOfMonth());
+ }
+
+ @Test
+ public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight(){
+ Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"),useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java
new file mode 100644
index 0000000000..69a289fd02
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDate;
+import java.time.LocalTime;
+import java.time.Month;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseLocalDateTimeTest {
+
+ UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
+
+ @Test
+ public void givenString_whenUsingParse_thenLocalDateTime(){
+ Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
+ Assert.assertEquals(LocalTime.of(6,30),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java
new file mode 100644
index 0000000000..7776fad363
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.datetime;
+
+import java.time.LocalTime;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseLocalTimeTest {
+
+ UseLocalTime useLocalTime = new UseLocalTime();
+
+ @Test
+ public void givenValues_whenUsingFactoryOf_thenLocalTime(){
+ Assert.assertEquals("07:07:07",useLocalTime.getLocalTimeUsingFactoryOfMethod(7,7,7).toString());
+ }
+
+ @Test
+ public void givenString_whenUsingParse_thenLocalTime(){
+ Assert.assertEquals("06:30",useLocalTime.getLocalTimeUsingParseMethod("06:30").toString());
+ }
+
+ @Test
+ public void givenTime_whenAddHour_thenLocalTime(){
+ Assert.assertEquals("07:30",useLocalTime.addAnHour(LocalTime.of(6,30)).toString());
+ }
+
+ @Test
+ public void getHourFromLocalTime(){
+ Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1,1)));
+ }
+
+ @Test
+ public void getLocalTimeWithMinuteSetToValue(){
+ Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10,10), 20));
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java
new file mode 100644
index 0000000000..8a3228aaa5
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java
@@ -0,0 +1,29 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.Period;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UsePeriodTest {
+ UsePeriod usingPeriod=new UsePeriod();
+
+ @Test
+ public void givenPeriodAndLocalDate_thenCalculateModifiedDate(){
+ Period period = Period.ofDays(1);
+ LocalDate localDate = LocalDate.parse("2007-05-10");
+ Assert.assertEquals(localDate.plusDays(1),usingPeriod.modifyDates(localDate, period));
+ }
+
+ @Test
+ public void givenDates_thenGetPeriod(){
+ LocalDate localDate1 = LocalDate.parse("2007-05-10");
+ LocalDate localDate2 = LocalDate.parse("2007-05-15");
+
+ Assert.assertEquals(Period.ofDays(5), usingPeriod.getDifferenceBetweenDates(localDate1, localDate2));
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java
new file mode 100644
index 0000000000..5af01ad678
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseZonedDateTimeTest {
+
+ UseZonedDateTime zonedDateTime=new UseZonedDateTime();
+
+ @Test
+ public void givenZoneId_thenZonedDateTime(){
+ ZoneId zoneId=ZoneId.of("Europe/Paris");
+ ZonedDateTime zonedDatetime=zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId);
+ Assert.assertEquals(zoneId,ZoneId.from(zonedDatetime));
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java b/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java
index 5ae6f02a56..85194f5aa6 100644
--- a/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java
+++ b/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java
@@ -6,7 +6,9 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
-import java.util.*;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
import java.util.function.BiFunction;
import static com.baeldung.doublecolon.ComputerUtils.*;
diff --git a/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java b/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java
new file mode 100644
index 0000000000..deeebaa240
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java
@@ -0,0 +1,80 @@
+package com.baeldung.enums;
+
+
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.List;
+
+import static junit.framework.TestCase.assertTrue;
+
+public class PizzaTest {
+
+ @Test
+ public void givenPizaOrder_whenReady_thenDeliverable() {
+ Pizza testPz = new Pizza();
+ testPz.setStatus(Pizza.PizzaStatusEnum.READY);
+ assertTrue(testPz.isDeliverable());
+ }
+
+ @Test
+ public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
+ List pzList = new ArrayList<>();
+ Pizza pz1 = new Pizza();
+ pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
+
+ Pizza pz2 = new Pizza();
+ pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
+
+ Pizza pz3 = new Pizza();
+ pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
+
+ Pizza pz4 = new Pizza();
+ pz4.setStatus(Pizza.PizzaStatusEnum.READY);
+
+ pzList.add(pz1);
+ pzList.add(pz2);
+ pzList.add(pz3);
+ pzList.add(pz4);
+
+ List undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
+ assertTrue(undeliveredPzs.size() == 3);
+ }
+
+ @Test
+ public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
+
+ List pzList = new ArrayList<>();
+ Pizza pz1 = new Pizza();
+ pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
+
+ Pizza pz2 = new Pizza();
+ pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
+
+ Pizza pz3 = new Pizza();
+ pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
+
+ Pizza pz4 = new Pizza();
+ pz4.setStatus(Pizza.PizzaStatusEnum.READY);
+
+ pzList.add(pz1);
+ pzList.add(pz2);
+ pzList.add(pz3);
+ pzList.add(pz4);
+
+ EnumMap> map = Pizza.groupPizzaByStatus(pzList);
+ assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
+ assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
+ assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
+ }
+
+ @Test
+ public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
+ Pizza pz = new Pizza();
+ pz.setStatus(Pizza.PizzaStatusEnum.READY);
+ pz.deliver();
+ assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java
new file mode 100644
index 0000000000..1dd1be7808
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/file/FileOperationsTest.java
@@ -0,0 +1,132 @@
+package com.baeldung.file;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.net.URLConnection;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+
+import org.apache.commons.io.FileUtils;
+import org.hamcrest.CoreMatchers;
+import org.hamcrest.Matchers;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class FileOperationsTest {
+
+ @Test
+ public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
+ String expectedData = "Hello World from fileTest.txt!!!";
+
+ ClassLoader classLoader = getClass().getClassLoader();
+ File file = new File(classLoader.getResource("fileTest.txt").getFile());
+ InputStream inputStream = new FileInputStream(file);
+ String data = readFromInputStream(inputStream);
+
+ Assert.assertEquals(expectedData, data.trim());
+ }
+
+ @Test
+ public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
+ String expectedData = "Hello World from fileTest.txt!!!";
+
+ Class clazz = FileOperationsTest.class;
+ InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
+ String data = readFromInputStream(inputStream);
+
+ Assert.assertEquals(expectedData, data.trim());
+ }
+
+ @Test
+ public void givenFileName_whenUsingJarFile_thenFileData() throws IOException {
+ String expectedData = "BSD License";
+
+ Class clazz = Matchers.class;
+ InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
+ String data = readFromInputStream(inputStream);
+
+ Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
+ }
+
+ @Test
+ public void givenURLName_whenUsingURL_thenFileData() throws IOException {
+ String expectedData = "Baeldung";
+
+ URL urlObject = new URL("http://www.baeldung.com/");
+
+ URLConnection urlConnection = urlObject.openConnection();
+
+ InputStream inputStream = urlConnection.getInputStream();
+ String data = readFromInputStream(inputStream);
+
+ Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
+ }
+
+ @Test
+ public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
+ String expectedData = "Hello World from fileTest.txt!!!";
+
+ ClassLoader classLoader = getClass().getClassLoader();
+ File file = new File(classLoader.getResource("fileTest.txt").getFile());
+ String data = FileUtils.readFileToString(file);
+
+ Assert.assertEquals(expectedData, data.trim());
+ }
+
+ @Test
+ public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException {
+ String expectedData = "Hello World from fileTest.txt!!!";
+
+ ClassLoader classLoader = getClass().getClassLoader();
+ File file = new File(classLoader.getResource("fileTest.txt").getFile());
+ Path path = Paths.get(file.getAbsolutePath());
+
+ byte[] fileBytes = Files.readAllBytes(path);
+ String data = new String(fileBytes);
+
+ Assert.assertEquals(expectedData, data.trim());
+ }
+
+ @Test
+ public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException {
+ String expectedData = "Hello World from fileTest.txt!!!";
+
+ ClassLoader classLoader = getClass().getClassLoader();
+ File file = new File(classLoader.getResource("fileTest.txt").getFile());
+ Path path = Paths.get(file.getAbsolutePath());
+
+ StringBuilder data = new StringBuilder();
+ Stream lines = Files.lines(path);
+ lines.forEach(new Consumer() {
+ @Override
+ public void accept(String line) {
+ data.append(line).append("\n");
+ }
+ });
+
+ Assert.assertEquals(expectedData, data.toString().trim());
+ }
+
+ private String readFromInputStream(InputStream inputStream) throws IOException {
+ InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
+ BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
+ StringBuilder resultStringBuilder = new StringBuilder();
+ String line;
+ while ((line = bufferedReader.readLine()) != null) {
+ resultStringBuilder.append(line);
+ resultStringBuilder.append("\n");
+ }
+ bufferedReader.close();
+ inputStreamReader.close();
+ inputStream.close();
+ return resultStringBuilder.toString();
+ }
+}
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java b/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java
new file mode 100644
index 0000000000..ce878026d4
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java
@@ -0,0 +1,199 @@
+package com.baeldung.functionalinterface;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import com.google.common.util.concurrent.Uninterruptibles;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+public class FunctionalInterfaceTest {
+
+ @Test
+ public void whenPassingLambdaToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
+
+ Map nameMap = new HashMap<>();
+ Integer value = nameMap.computeIfAbsent("John", s -> s.length());
+
+ assertEquals(new Integer(4), nameMap.get("John"));
+ assertEquals(new Integer(4), value);
+
+ }
+
+ @Test
+ public void whenPassingMethodReferenceToComputeIfAbsent_thenTheValueGetsComputedAndPutIntoMap() {
+
+ Map nameMap = new HashMap<>();
+ Integer value = nameMap.computeIfAbsent("John", String::length);
+
+ assertEquals(new Integer(4), nameMap.get("John"));
+ assertEquals(new Integer(4), value);
+
+ }
+
+ public byte[] transformArray(short[] array, ShortToByteFunction function) {
+ byte[] transformedArray = new byte[array.length];
+ for (int i = 0; i < array.length; i++) {
+ transformedArray[i] = function.applyAsByte(array[i]);
+ }
+ return transformedArray;
+ }
+
+ @Test
+ public void whenUsingCustomFunctionalInterfaceForPrimitives_thenCanUseItAsLambda() {
+
+ short[] array = {(short) 1, (short) 2, (short) 3};
+ byte[] transformedArray = transformArray(array, s -> (byte) (s * 2));
+
+ byte[] expectedArray = {(byte) 2, (byte) 4, (byte) 6};
+ assertArrayEquals(expectedArray, transformedArray);
+
+ }
+
+ @Test
+ public void whenUsingBiFunction_thenCanUseItToReplaceMapValues() {
+
+ Map salaries = new HashMap<>();
+ salaries.put("John", 40000);
+ salaries.put("Freddy", 30000);
+ salaries.put("Samuel", 50000);
+
+ salaries.replaceAll((name, oldValue) -> name.equals("Freddy") ? oldValue : oldValue + 10000);
+
+ assertEquals(new Integer(50000), salaries.get("John"));
+ assertEquals(new Integer(30000), salaries.get("Freddy"));
+ assertEquals(new Integer(60000), salaries.get("Samuel"));
+
+ }
+
+
+ @Test
+ public void whenPassingLambdaToThreadConstructor_thenLambdaInferredToRunnable() {
+
+ Thread thread = new Thread(() -> System.out.println("Hello From Another Thread"));
+ thread.start();
+
+ }
+
+ @Test
+ public void whenUsingSupplierToGenerateNumbers_thenCanUseItInStreamGenerate() {
+
+ int[] fibs = {0, 1};
+ Stream fibonacci = Stream.generate(() -> {
+ int result = fibs[1];
+ int fib3 = fibs[0] + fibs[1];
+ fibs[0] = fibs[1];
+ fibs[1] = fib3;
+ return result;
+ });
+
+ List fibonacci5 = fibonacci.limit(5)
+ .collect(Collectors.toList());
+
+ assertEquals(new Integer(1), fibonacci5.get(0));
+ assertEquals(new Integer(1), fibonacci5.get(1));
+ assertEquals(new Integer(2), fibonacci5.get(2));
+ assertEquals(new Integer(3), fibonacci5.get(3));
+ assertEquals(new Integer(5), fibonacci5.get(4));
+
+ }
+
+ @Test
+ public void whenUsingConsumerInForEach_thenConsumerExecutesForEachListElement() {
+
+ List names = Arrays.asList("John", "Freddy", "Samuel");
+ names.forEach(name -> System.out.println("Hello, " + name));
+
+ }
+
+ @Test
+ public void whenUsingBiConsumerInForEach_thenConsumerExecutesForEachMapElement() {
+
+ Map ages = new HashMap<>();
+ ages.put("John", 25);
+ ages.put("Freddy", 24);
+ ages.put("Samuel", 30);
+
+ ages.forEach((name, age) -> System.out.println(name + " is " + age + " years old"));
+
+ }
+
+ @Test
+ public void whenUsingPredicateInFilter_thenListValuesAreFilteredOut() {
+
+ List names = Arrays.asList("Angela", "Aaron", "Bob", "Claire", "David");
+
+ List namesWithA = names.stream()
+ .filter(name -> name.startsWith("A"))
+ .collect(Collectors.toList());
+
+ assertEquals(2, namesWithA.size());
+ assertTrue(namesWithA.contains("Angela"));
+ assertTrue(namesWithA.contains("Aaron"));
+
+ }
+
+ @Test
+ public void whenUsingUnaryOperatorWithReplaceAll_thenAllValuesInTheListAreReplaced() {
+
+ List names = Arrays.asList("bob", "josh", "megan");
+
+ names.replaceAll(String::toUpperCase);
+
+ assertEquals("BOB", names.get(0));
+ assertEquals("JOSH", names.get(1));
+ assertEquals("MEGAN", names.get(2));
+
+ }
+
+ @Test
+ public void whenUsingBinaryOperatorWithStreamReduce_thenResultIsSumOfValues() {
+
+ List values = Arrays.asList(3, 5, 8, 9, 12);
+
+ int sum = values.stream()
+ .reduce(0, (i1, i2) -> i1 + i2);
+
+ assertEquals(37, sum);
+
+ }
+
+ @Test
+ public void whenComposingTwoFunctions_thenFunctionsExecuteSequentially() {
+
+ Function intToString = Object::toString;
+ Function quote = s -> "'" + s + "'";
+
+ Function quoteIntToString = quote.compose(intToString);
+
+ assertEquals("'5'", quoteIntToString.apply(5));
+
+ }
+
+ public double squareLazy(Supplier lazyValue) {
+ return Math.pow(lazyValue.get(), 2);
+ }
+
+ @Test
+ public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() {
+
+ Supplier lazyValue = () -> {
+ Uninterruptibles.sleepUninterruptibly(1000, TimeUnit.MILLISECONDS);
+ return 9d;
+ };
+
+ double valueSquared = squareLazy(lazyValue);
+
+ assertEquals(81d, valueSquared, 0);
+
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java b/core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java
new file mode 100644
index 0000000000..3231d6244f
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java
@@ -0,0 +1,8 @@
+package com.baeldung.functionalinterface;
+
+@FunctionalInterface
+public interface ShortToByteFunction {
+
+ byte applyAsByte(short s);
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java
index 9c248ad8ce..ef4b80c6e8 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java
@@ -1,14 +1,13 @@
package com.baeldung.java8;
-import static org.hamcrest.Matchers.hasSize;
-import static org.junit.Assert.assertThat;
+import com.google.common.collect.Lists;
+import org.junit.Test;
import java.util.List;
import java.util.stream.Collectors;
-import org.junit.Test;
-
-import com.google.common.collect.Lists;
+import static org.hamcrest.Matchers.hasSize;
+import static org.junit.Assert.assertThat;
public class Java8CollectionCleanupUnitTest {
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java
new file mode 100644
index 0000000000..21a5e34b9b
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java
@@ -0,0 +1,27 @@
+package com.baeldung.java8;
+
+import com.baeldung.java_8_features.Vehicle;
+import com.baeldung.java_8_features.VehicleImpl;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class Java8DefaultStaticIntefaceMethodsTest {
+
+ @Test
+ public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() {
+ Vehicle vehicle = new VehicleImpl();
+ String overview = vehicle.getOverview();
+ long[] startPosition = vehicle.startPosition();
+
+ assertEquals(overview, "ATV made by N&F Vehicles");
+ assertEquals(startPosition[0], 23);
+ assertEquals(startPosition[1], 15);
+ }
+
+ @Test
+ public void callDefaultInterfaceMethods_whenExpectedResults_thenCorrect() {
+ String producer = Vehicle.producer();
+ assertEquals(producer, "N&F Vehicles");
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java
new file mode 100644
index 0000000000..581ccec182
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java
@@ -0,0 +1,156 @@
+package com.baeldung.java8;
+
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.*;
+
+import static org.junit.Assert.*;
+
+
+public class Java8ExecutorServiceTest {
+
+ private Runnable runnableTask;
+ private Callable callableTask;
+ private List> callableTasks;
+
+ @Before
+ public void init() {
+
+ runnableTask = () -> {
+ try {
+ TimeUnit.MILLISECONDS.sleep(300);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ };
+
+ callableTask = () -> {
+ TimeUnit.MILLISECONDS.sleep(300);
+ return "Task's execution";
+ };
+
+ callableTasks = new ArrayList<>();
+ callableTasks.add(callableTask);
+ callableTasks.add(callableTask);
+ callableTasks.add(callableTask);
+ }
+
+ @Test
+ public void creationSubmittingTaskShuttingDown_whenShutDown_thenCorrect() {
+
+ ExecutorService executorService = Executors.newFixedThreadPool(10);
+ executorService.submit(runnableTask);
+ executorService.submit(callableTask);
+ executorService.shutdown();
+
+ assertTrue(executorService.isShutdown());
+ }
+
+ @Test
+ public void creationSubmittingTasksShuttingDownNow_whenShutDownAfterAwating_thenCorrect() {
+
+ ExecutorService threadPoolExecutor =
+ new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
+ new LinkedBlockingQueue<>());
+
+ for (int i = 0; i < 100; i++) {
+ threadPoolExecutor.submit(callableTask);
+ }
+
+ List notExecutedTasks = smartShutdown(threadPoolExecutor);
+
+ assertTrue(threadPoolExecutor.isShutdown());
+ assertFalse(notExecutedTasks.isEmpty());
+ assertTrue(notExecutedTasks.size() > 0 && notExecutedTasks.size() < 98);
+ }
+
+ private List smartShutdown(ExecutorService executorService) {
+
+ List notExecutedTasks = new ArrayList<>();
+ executorService.shutdown();
+ try {
+ if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) {
+ notExecutedTasks = executorService.shutdownNow();
+ }
+ } catch (InterruptedException e) {
+ notExecutedTasks = executorService.shutdownNow();
+ }
+ return notExecutedTasks;
+ }
+
+ @Test
+ public void submittingTasks_whenExecutedOneAndAll_thenCorrect() {
+
+ ExecutorService executorService = Executors.newFixedThreadPool(10);
+
+ String result = null;
+ List> futures = new ArrayList<>();
+ try {
+ result = executorService.invokeAny(callableTasks);
+ futures = executorService.invokeAll(callableTasks);
+ } catch (InterruptedException | ExecutionException e) {
+ e.printStackTrace();
+ }
+
+ assertEquals("Task's execution", result);
+ assertTrue(futures.size() == 3);
+ }
+
+ @Test
+ public void submittingTaskShuttingDown_whenGetExpectedResult_thenCorrect() {
+
+ ExecutorService executorService = Executors.newFixedThreadPool(10);
+
+ Future future = executorService.submit(callableTask);
+ String result = null;
+ try {
+ result = future.get();
+ result = future.get(200, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException | ExecutionException | TimeoutException e) {
+ e.printStackTrace();
+ }
+
+ executorService.shutdown();
+
+ assertEquals("Task's execution", result);
+ }
+
+ @Test
+ public void submittingTask_whenCanceled_thenCorrect() {
+
+ ExecutorService executorService = Executors.newFixedThreadPool(10);
+
+ Future future = executorService.submit(callableTask);
+
+ boolean canceled = future.cancel(true);
+ boolean isCancelled = future.isCancelled();
+
+ executorService.shutdown();
+
+ assertTrue(canceled);
+ assertTrue(isCancelled);
+ }
+
+ @Test
+ public void submittingTaskScheduling_whenExecuted_thenCorrect() {
+
+ ScheduledExecutorService executorService = Executors
+ .newSingleThreadScheduledExecutor();
+
+ Future resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS);
+ String result = null;
+ try {
+ result = resultFuture.get();
+ } catch (InterruptedException | ExecutionException e) {
+ e.printStackTrace();
+ }
+
+ executorService.shutdown();
+
+ assertEquals("Task's execution", result);
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java
new file mode 100644
index 0000000000..273b2d78db
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java
@@ -0,0 +1,100 @@
+package com.baeldung.java8;
+
+
+import com.baeldung.forkjoin.CustomRecursiveAction;
+import com.baeldung.forkjoin.CustomRecursiveTask;
+import com.baeldung.forkjoin.util.PoolUtil;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Random;
+import java.util.concurrent.ForkJoinPool;
+
+import static org.junit.Assert.*;
+
+public class Java8ForkJoinTest {
+
+ private int[] arr;
+ private CustomRecursiveTask customRecursiveTask;
+
+ @Before
+ public void init() {
+ Random random = new Random();
+ arr = new int[50];
+ for (int i = 0; i < arr.length; i++) {
+ arr[i] = random.nextInt(35);
+ }
+ customRecursiveTask = new CustomRecursiveTask(arr);
+ }
+
+
+ @Test
+ public void callPoolUtil_whenExistsAndExpectedType_thenCorrect() {
+
+ ForkJoinPool forkJoinPool = PoolUtil.forkJoinPool;
+ ForkJoinPool forkJoinPoolTwo = PoolUtil.forkJoinPool;
+
+ assertNotNull(forkJoinPool);
+ assertEquals(2, forkJoinPool.getParallelism());
+ assertEquals(forkJoinPool, forkJoinPoolTwo);
+
+ }
+
+ @Test
+ public void callCommonPool_whenExistsAndExpectedType_thenCorrect() {
+
+ ForkJoinPool commonPool = ForkJoinPool.commonPool();
+ ForkJoinPool commonPoolTwo = ForkJoinPool.commonPool();
+
+ assertNotNull(commonPool);
+ assertEquals(commonPool, commonPoolTwo);
+
+ }
+
+ @Test
+ public void executeRecursiveAction_whenExecuted_thenCorrect() {
+
+ CustomRecursiveAction myRecursiveAction = new CustomRecursiveAction("ddddffffgggghhhh");
+ ForkJoinPool.commonPool().invoke(myRecursiveAction);
+
+ assertTrue(myRecursiveAction.isDone());
+
+ }
+
+ @Test
+ public void executeRecursiveTask_whenExecuted_thenCorrect() {
+
+ ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
+
+ forkJoinPool.execute(customRecursiveTask);
+ int result = customRecursiveTask.join();
+ assertTrue(customRecursiveTask.isDone());
+
+ forkJoinPool.submit(customRecursiveTask);
+ int resultTwo = customRecursiveTask.join();
+ assertTrue(customRecursiveTask.isDone());
+
+ }
+
+ @Test
+ public void executeRecursiveTaskWithFJ_whenExecuted_thenCorrect() {
+
+ CustomRecursiveTask customRecursiveTaskFirst = new CustomRecursiveTask(arr);
+ CustomRecursiveTask customRecursiveTaskSecond = new CustomRecursiveTask(arr);
+ CustomRecursiveTask customRecursiveTaskLast = new CustomRecursiveTask(arr);
+
+ customRecursiveTaskFirst.fork();
+ customRecursiveTaskSecond.fork();
+ customRecursiveTaskLast.fork();
+ int result = 0;
+ result += customRecursiveTaskLast.join();
+ result += customRecursiveTaskSecond.join();
+ result += customRecursiveTaskFirst.join();
+
+ assertTrue(customRecursiveTaskFirst.isDone());
+ assertTrue(customRecursiveTaskSecond.isDone());
+ assertTrue(customRecursiveTaskLast.isDone());
+ assertTrue(result != 0);
+
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java
index 94448fcc83..faaf3ae407 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java
@@ -1,16 +1,15 @@
package com.baeldung.java8;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-
-import java.util.function.Function;
-
-import org.junit.Before;
-import org.junit.Test;
-
import com.baeldung.Foo;
import com.baeldung.FooExtended;
import com.baeldung.UseFoo;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.function.Function;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
public class Java8FunctionalInteracesLambdasTest {
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java
new file mode 100644
index 0000000000..d9d88c5052
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java
@@ -0,0 +1,67 @@
+package com.baeldung.java8;
+
+import com.baeldung.java_8_features.User;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class Java8MethodReferenceTest {
+
+ private List list;
+
+ @Before
+ public void init() {
+ list = new ArrayList<>();
+ list.add("One");
+ list.add("OneAndOnly");
+ list.add("Derek");
+ list.add("Change");
+ list.add("factory");
+ list.add("justBefore");
+ list.add("Italy");
+ list.add("Italy");
+ list.add("Thursday");
+ list.add("");
+ list.add("");
+ }
+
+ @Test
+ public void checkStaticMethodReferences_whenWork_thenCorrect() {
+
+ List users = new ArrayList<>();
+ users.add(new User());
+ users.add(new User());
+ boolean isReal = users.stream().anyMatch(u -> User.isRealUser(u));
+ boolean isRealRef = users.stream().anyMatch(User::isRealUser);
+ assertTrue(isReal);
+ assertTrue(isRealRef);
+ }
+
+ @Test
+ public void checkInstanceMethodReferences_whenWork_thenCorrect() {
+ User user = new User();
+ boolean isLegalName = list.stream().anyMatch(user::isLegalName);
+ assertTrue(isLegalName);
+ }
+
+ @Test
+ public void checkParticularTypeReferences_whenWork_thenCorrect() {
+ long count = list.stream().filter(String::isEmpty).count();
+ assertEquals(count, 2);
+ }
+
+ @Test
+ public void checkConstructorReferences_whenWork_thenCorrect() {
+ Stream stream = list.stream().map(User::new);
+ List userList = stream.collect(Collectors.toList());
+ assertEquals(userList.size(), list.size());
+ assertTrue(userList.get(0) instanceof User);
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java
new file mode 100644
index 0000000000..26de39bc0e
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java
@@ -0,0 +1,118 @@
+package com.baeldung.java8;
+
+import com.baeldung.java_8_features.*;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+import static org.junit.Assert.*;
+
+public class Java8OptionalTest {
+
+ private List list;
+
+ @Before
+ public void init() {
+ list = new ArrayList<>();
+ list.add("One");
+ list.add("OneAndOnly");
+ list.add("Derek");
+ list.add("Change");
+ list.add("factory");
+ list.add("justBefore");
+ list.add("Italy");
+ list.add("Italy");
+ list.add("Thursday");
+ list.add("");
+ list.add("");
+ }
+
+ @Test
+ public void checkOptional_whenAsExpected_thenCorrect() {
+
+ Optional optionalEmpty = Optional.empty();
+ assertFalse(optionalEmpty.isPresent());
+
+ String str = "value";
+ Optional optional = Optional.of(str);
+ assertEquals(optional.get(), "value");
+
+ Optional optionalNullable = Optional.ofNullable(str);
+ Optional optionalNull = Optional.ofNullable(null);
+ assertEquals(optionalNullable.get(), "value");
+ assertFalse(optionalNull.isPresent());
+
+ List listOpt = Optional.of(list).orElse(new ArrayList<>());
+ List listNull = null;
+ List listOptNull = Optional.ofNullable(listNull).orElse(new ArrayList<>());
+ assertTrue(listOpt == list);
+ assertTrue(listOptNull.isEmpty());
+
+ Optional user = Optional.ofNullable(getUser());
+ String result = user.map(User::getAddress)
+ .map(Address::getStreet)
+ .orElse("not specified");
+ assertEquals(result, "1st Avenue");
+
+ Optional optionalUser = Optional.ofNullable(getOptionalUser());
+ String resultOpt = optionalUser.flatMap(OptionalUser::getAddress)
+ .flatMap(OptionalAddress::getStreet)
+ .orElse("not specified");
+ assertEquals(resultOpt, "1st Avenue");
+
+ Optional userNull = Optional.ofNullable(getUserNull());
+ String resultNull = userNull.map(User::getAddress)
+ .map(Address::getStreet)
+ .orElse("not specified");
+ assertEquals(resultNull, "not specified");
+
+ Optional optionalUserNull = Optional.ofNullable(getOptionalUserNull());
+ String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress)
+ .flatMap(OptionalAddress::getStreet)
+ .orElse("not specified");
+ assertEquals(resultOptNull, "not specified");
+
+ }
+
+ @Test(expected = CustomException.class)
+ public void callMethod_whenCustomException_thenCorrect() {
+ User user = new User();
+ String result = user.getOrThrow();
+ }
+
+ private User getUser() {
+ User user = new User();
+ Address address = new Address();
+ address.setStreet("1st Avenue");
+ user.setAddress(address);
+ return user;
+ }
+
+ private OptionalUser getOptionalUser() {
+ OptionalUser user = new OptionalUser();
+ OptionalAddress address = new OptionalAddress();
+ address.setStreet("1st Avenue");
+ user.setAddress(address);
+ return user;
+ }
+
+ private OptionalUser getOptionalUserNull() {
+ OptionalUser user = new OptionalUser();
+ OptionalAddress address = new OptionalAddress();
+ address.setStreet(null);
+ user.setAddress(address);
+ return user;
+ }
+
+ private User getUserNull() {
+ User user = new User();
+ Address address = new Address();
+ address.setStreet(null);
+ user.setAddress(address);
+ return user;
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
index 2ba9e417d6..f371c0d7da 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
@@ -1,17 +1,16 @@
package com.baeldung.java8;
-import static org.hamcrest.Matchers.equalTo;
+import com.baeldung.java8.entity.Human;
+import com.google.common.collect.Lists;
+import com.google.common.primitives.Ints;
+import org.junit.Assert;
+import org.junit.Test;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
-import org.junit.Assert;
-import org.junit.Test;
-
-import com.baeldung.java8.entity.Human;
-import com.google.common.collect.Lists;
-import com.google.common.primitives.Ints;
+import static org.hamcrest.Matchers.equalTo;
public class Java8SortUnitTest {
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java
new file mode 100644
index 0000000000..37326c6d26
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java
@@ -0,0 +1,263 @@
+package com.baeldung.java8;
+
+import com.baeldung.streamApi.Product;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.*;
+import java.util.regex.Pattern;
+import java.util.stream.*;
+
+import static org.junit.Assert.*;
+
+public class Java8StreamApiTest {
+
+ private long counter;
+
+ private static Logger log = LoggerFactory.getLogger(Java8StreamApiTest.class);
+
+ private List productList;
+
+ @Before
+ public void init() {
+ productList = Arrays.asList(
+ new Product(23, "potatoes"), new Product(14, "orange"),
+ new Product(13, "lemon"), new Product(23, "bread"),
+ new Product(13, "sugar"));
+ }
+
+ @Test
+ public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
+
+ List list = Arrays.asList("abc1", "abc2", "abc3");
+ long size = list.stream().skip(1)
+ .map(element -> element.substring(0, 3)).count();
+ assertEquals(list.size() - 1, size);
+ }
+
+ @Test
+ public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
+
+ List list = Arrays.asList("abc1", "abc2", "abc3");
+
+ counter = 0;
+ long sizeFirst = list.stream()
+ .skip(2).map(element -> {
+ wasCalled();
+ return element.substring(0, 3);
+ }).count();
+ assertEquals(1, counter);
+
+ counter = 0;
+ long sizeSecond = list.stream().map(element -> {
+ wasCalled();
+ return element.substring(0, 3);
+ }).skip(2).count();
+ assertEquals(3, counter);
+ }
+
+ @Test
+ public void createEmptyStream_whenEmpty_thenCorrect() {
+
+ Stream streamEmpty = Stream.empty();
+ assertEquals(0, streamEmpty.count());
+
+ List names = Collections.emptyList();
+ Stream streamOf = Product.streamOf(names);
+ assertTrue(streamOf.count() == 0);
+ }
+
+ @Test
+ public void createStream_whenCreated_thenCorrect() {
+
+ Collection collection = Arrays.asList("a", "b", "c");
+ Stream streamOfCollection = collection.stream();
+ assertEquals(3, streamOfCollection.count());
+
+ Stream streamOfArray = Stream.of("a", "b", "c");
+ assertEquals(3, streamOfArray.count());
+
+ String[] arr = new String[]{"a", "b", "c"};
+ Stream streamOfArrayPart = Arrays.stream(arr, 1, 3);
+ assertEquals(2, streamOfArrayPart.count());
+
+ IntStream intStream = IntStream.range(1, 3);
+ LongStream longStream = LongStream.rangeClosed(1, 3);
+ Random random = new Random();
+ DoubleStream doubleStream = random.doubles(3);
+ assertEquals(2, intStream.count());
+ assertEquals(3, longStream.count());
+ assertEquals(3, doubleStream.count());
+
+ IntStream streamOfChars = "abc".chars();
+ IntStream str = "".chars();
+ assertEquals(3, streamOfChars.count());
+
+ Stream streamOfString = Pattern.compile(", ").splitAsStream("a, b, c");
+ assertEquals("a", streamOfString.findFirst().get());
+
+ Path path = getPath();
+ Stream streamOfStrings = null;
+ try {
+ streamOfStrings = Files.lines(path, Charset.forName("UTF-8"));
+ } catch (IOException e) {
+ log.error("Error creating streams from paths {}", path, e.getMessage(), e);
+ }
+ assertEquals("a", streamOfStrings.findFirst().get());
+
+ Stream streamBuilder = Stream.builder().add("a").add("b").add("c").build();
+ assertEquals(3, streamBuilder.count());
+
+ Stream streamGenerated = Stream.generate(() -> "element").limit(10);
+ assertEquals(10, streamGenerated.count());
+
+ Stream streamIterated = Stream.iterate(40, n -> n + 2).limit(20);
+ assertTrue(40 <= streamIterated.findAny().get());
+ }
+
+ @Test
+ public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
+
+ List list = Arrays.asList("abc1", "abc2", "abc3");
+ Optional stream = list.stream()
+ .filter(element -> {
+ log.info("filter() was called");
+ return element.contains("2");
+ }).map(element -> {
+ log.info("map() was called");
+ return element.toUpperCase();
+ }).findFirst();
+ }
+
+ @Test
+ public void reduce_whenExpected_thenCorrect() {
+
+ OptionalInt reduced = IntStream.range(1, 4).reduce((a, b) -> a + b);
+ assertEquals(6, reduced.getAsInt());
+
+ int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
+ assertEquals(16, reducedTwoParams);
+
+ int reducedThreeParams = Stream.of(1, 2, 3)
+ .reduce(10, (a, b) -> a + b, (a, b) -> {
+ log.info("combiner was called");
+ return a + b;
+ });
+ assertEquals(16, reducedThreeParams);
+
+ int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream()
+ .reduce(10, (a, b) -> a + b, (a, b) -> {
+ log.info("combiner was called");
+ return a + b;
+ });
+ assertEquals(36, reducedThreeParamsParallel);
+ }
+
+ @Test
+ public void collecting_whenAsExpected_thenCorrect() {
+
+ List collectorCollection = productList.stream()
+ .map(Product::getName).collect(Collectors.toList());
+
+ assertTrue(collectorCollection instanceof List);
+ assertEquals(5, collectorCollection.size());
+
+ String listToString = productList.stream().map(Product::getName)
+ .collect(Collectors.joining(", ", "[", "]"));
+
+ assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
+
+ double averagePrice = productList.stream().collect(Collectors.averagingInt(Product::getPrice));
+ assertTrue(17.2 == averagePrice);
+
+ int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
+ assertEquals(86, summingPrice);
+
+ IntSummaryStatistics statistics = productList.stream()
+ .collect(Collectors.summarizingInt(Product::getPrice));
+ assertEquals(23, statistics.getMax());
+
+ Map> collectorMapOfLists = productList.stream()
+ .collect(Collectors.groupingBy(Product::getPrice));
+ assertEquals(3, collectorMapOfLists.keySet().size());
+
+ Map> mapPartioned = productList.stream()
+ .collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
+ assertEquals(2, mapPartioned.keySet().size());
+
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void collect_whenThrows_thenCorrect() {
+ Set unmodifiableSet = productList.stream()
+ .collect(Collectors.collectingAndThen(Collectors.toSet(),
+ Collections::unmodifiableSet));
+ unmodifiableSet.add(new Product(4, "tea"));
+ }
+
+ @Test
+ public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
+ Collector> toLinkedList =
+ Collector.of(LinkedList::new, LinkedList::add,
+ (first, second) -> {
+ first.addAll(second);
+ return first;
+ });
+
+ LinkedList linkedListOfPersons = productList.stream().collect(toLinkedList);
+ assertTrue(linkedListOfPersons.containsAll(productList));
+ }
+
+ @Test
+ public void parallelStream_whenWorks_thenCorrect() {
+ Stream streamOfCollection = productList.parallelStream();
+ boolean isParallel = streamOfCollection.isParallel();
+ boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12)
+ .anyMatch(price -> price > 200);
+ assertTrue(isParallel && haveBigPrice);
+ }
+
+ @Test
+ public void parallel_whenIsParallel_thenCorrect() {
+ IntStream intStreamParallel =
+ IntStream.range(1, 150).parallel().map(element -> element * 34);
+ boolean isParallel = intStreamParallel.isParallel();
+ assertTrue(isParallel);
+ }
+
+ @Test
+ public void parallel_whenIsSequential_thenCorrect() {
+ IntStream intStreamParallel =
+ IntStream.range(1, 150).parallel().map(element -> element * 34);
+ IntStream intStreamSequential = intStreamParallel.sequential();
+ boolean isParallel = intStreamParallel.isParallel();
+ assertFalse(isParallel);
+ }
+
+ private Path getPath() {
+ Path path = null;
+ try {
+ path = Files.createTempFile(null, ".txt");
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+
+ try (BufferedWriter writer = Files.newBufferedWriter(path)) {
+ writer.write("a\nb\nc");
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+ return path;
+ }
+
+ private void wasCalled() {
+ counter++;
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java
new file mode 100644
index 0000000000..1f1dda49ce
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java
@@ -0,0 +1,113 @@
+package com.baeldung.java8;
+
+import com.baeldung.java_8_features.Detail;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.*;
+
+public class Java8StreamsTest {
+
+ private List list;
+
+ @Before
+ public void init() {
+ list = new ArrayList<>();
+ list.add("One");
+ list.add("OneAndOnly");
+ list.add("Derek");
+ list.add("Change");
+ list.add("factory");
+ list.add("justBefore");
+ list.add("Italy");
+ list.add("Italy");
+ list.add("Thursday");
+ list.add("");
+ list.add("");
+ }
+
+ @Test
+ public void checkStreamCount_whenCreating_givenDifferentSources() {
+ String[] arr = new String[]{"a", "b", "c"};
+ Stream streamArr = Arrays.stream(arr);
+ assertEquals(streamArr.count(), 3);
+
+ Stream streamOf = Stream.of("a", "b", "c");
+ assertEquals(streamOf.count(), 3);
+
+ long count = list.stream().distinct().count();
+ assertEquals(count, 9);
+ }
+
+
+ @Test
+ public void checkStreamCount_whenOperationFilter_thanCorrect() {
+ Stream streamFilter = list.stream().filter(element -> element.isEmpty());
+ assertEquals(streamFilter.count(), 2);
+ }
+
+
+ @Test
+ public void checkStreamCount_whenOperationMap_thanCorrect() {
+ List uris = new ArrayList<>();
+ uris.add("C:\\My.txt");
+ Stream streamMap = uris.stream().map(uri -> Paths.get(uri));
+ assertEquals(streamMap.count(), 1);
+
+ List details = new ArrayList<>();
+ details.add(new Detail());
+ details.add(new Detail());
+ Stream streamFlatMap = details.stream()
+ .flatMap(detail -> detail.getParts().stream());
+ assertEquals(streamFlatMap.count(), 4);
+ }
+
+
+ @Test
+ public void checkStreamCount_whenOperationMatch_thenCorrect() {
+ boolean isValid = list.stream().anyMatch(element -> element.contains("h"));
+ boolean isValidOne = list.stream().allMatch(element -> element.contains("h"));
+ boolean isValidTwo = list.stream().noneMatch(element -> element.contains("h"));
+ assertTrue(isValid);
+ assertFalse(isValidOne);
+ assertFalse(isValidTwo);
+ }
+
+
+ @Test
+ public void checkStreamReducedValue_whenOperationReduce_thenCorrect() {
+ List integers = new ArrayList<>();
+ integers.add(1);
+ integers.add(1);
+ integers.add(1);
+ Integer reduced = integers.stream().reduce(23, (a, b) -> a + b);
+ assertTrue(reduced == 26);
+ }
+
+ @Test
+ public void checkStreamContains_whenOperationCollect_thenCorrect() {
+ List resultList = list.stream()
+ .map(element -> element.toUpperCase())
+ .collect(Collectors.toList());
+ assertEquals(resultList.size(), list.size());
+ assertTrue(resultList.contains(""));
+ }
+
+
+ @Test
+ public void checkParallelStream_whenDoWork() {
+ list.parallelStream().forEach(element -> doWork(element));
+ }
+
+ private void doWork(String string) {
+ assertTrue(true); //just imitate an amount of work
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java
index 2ac16b5d1d..f2e7452137 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java
@@ -1,22 +1,18 @@
package com.baeldung.java8;
-import static org.junit.Assert.assertEquals;
+import org.apache.commons.io.FileUtils;
+import org.junit.Before;
+import org.junit.Test;
import java.io.File;
import java.io.IOException;
-import java.nio.file.FileVisitResult;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.SimpleFileVisitor;
+import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.DecimalFormat;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.StreamSupport;
-import org.apache.commons.io.FileUtils;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
public class JavaFolderSizeTest {
@@ -25,7 +21,7 @@ public class JavaFolderSizeTest {
@Before
public void init() {
final String separator = File.separator;
- path = "src" + separator + "test" + separator + "resources";
+ path = String.format("src%stest%sresources", separator, separator);
}
@Test
@@ -83,7 +79,9 @@ public class JavaFolderSizeTest {
final File folder = new File(path);
final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
- final long size = StreamSupport.stream(files.spliterator(), false).filter(f -> f.isFile()).mapToLong(File::length).sum();
+ final long size = StreamSupport.stream(files.spliterator(), false)
+ .filter(File::isFile)
+ .mapToLong(File::length).sum();
assertEquals(expectedSize, size);
}
@@ -93,7 +91,7 @@ public class JavaFolderSizeTest {
final File folder = new File(path);
final long size = getFolderSize(folder);
- final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
+ final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
final int unitIndex = (int) (Math.log10(size) / 3);
final double unitValue = 1 << (unitIndex * 10);
@@ -105,13 +103,11 @@ public class JavaFolderSizeTest {
long length = 0;
final File[] files = folder.listFiles();
- final int count = files.length;
-
- for (int i = 0; i < count; i++) {
- if (files[i].isFile()) {
- length += files[i].length();
+ for (File file : files) {
+ if (file.isFile()) {
+ length += file.length();
} else {
- length += getFolderSize(files[i]);
+ length += getFolderSize(file);
}
}
return length;
diff --git a/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java
index 18110b181d..224c4e9d6a 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java
@@ -1,13 +1,13 @@
package com.baeldung.java8;
+import org.junit.Assert;
+import org.junit.Test;
+
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.Scanner;
-import org.junit.Assert;
-import org.junit.Test;
-
public class JavaTryWithResourcesTest {
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java b/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java
index 07380cdd01..164a571817 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java
@@ -1,14 +1,12 @@
package com.baeldung.java8.base64;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.io.UnsupportedEncodingException;
-
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
+import java.io.UnsupportedEncodingException;
+
+import static org.junit.Assert.*;
+
public class ApacheCommonsEncodeDecodeTest {
// tests
diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java b/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java
index 3c504edbf3..18dccf71ba 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java
@@ -1,14 +1,12 @@
package com.baeldung.java8.base64;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.UUID;
-import org.junit.Test;
+import static org.junit.Assert.*;
public class Java8EncodeDecodeTest {
diff --git a/core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java b/core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java
new file mode 100644
index 0000000000..df336f4a93
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/threadpool/CoreThreadPoolTest.java
@@ -0,0 +1,146 @@
+package com.baeldung.threadpool;
+
+import java.util.concurrent.*;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class CoreThreadPoolTest {
+
+ @Test(timeout = 1000)
+ public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException {
+
+ CountDownLatch lock = new CountDownLatch(1);
+
+ Executor executor = Executors.newSingleThreadExecutor();
+ executor.execute(() -> {
+ System.out.println("Hello World");
+ lock.countDown();
+ });
+
+ lock.await(1000, TimeUnit.MILLISECONDS);
+ }
+
+ @Test
+ public void whenUsingExecutorServiceAndFuture_thenCanWaitOnFutureResult() throws InterruptedException, ExecutionException {
+
+ ExecutorService executorService = Executors.newFixedThreadPool(10);
+ Future future = executorService.submit(() -> "Hello World");
+ String result = future.get();
+
+ assertEquals("Hello World", result);
+
+ }
+
+ @Test
+ public void whenUsingFixedThreadPool_thenCoreAndMaximumThreadSizeAreTheSame() {
+
+ ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
+ executor.submit(() -> {
+ Thread.sleep(1000);
+ return null;
+ });
+ executor.submit(() -> {
+ Thread.sleep(1000);
+ return null;
+ });
+ executor.submit(() -> {
+ Thread.sleep(1000);
+ return null;
+ });
+
+ assertEquals(2, executor.getPoolSize());
+ assertEquals(1, executor.getQueue().size());
+
+ }
+
+ @Test
+ public void whenUsingCachedThreadPool_thenPoolSizeGrowsUnbounded() {
+ ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
+ executor.submit(() -> {
+ Thread.sleep(1000);
+ return null;
+ });
+ executor.submit(() -> {
+ Thread.sleep(1000);
+ return null;
+ });
+ executor.submit(() -> {
+ Thread.sleep(1000);
+ return null;
+ });
+
+ assertEquals(3, executor.getPoolSize());
+ assertEquals(0, executor.getQueue().size());
+
+ }
+
+ @Test(timeout = 1000)
+ public void whenUsingSingleThreadPool_thenTasksExecuteSequentially() throws InterruptedException {
+
+ CountDownLatch lock = new CountDownLatch(2);
+ AtomicInteger counter = new AtomicInteger();
+
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ executor.submit(() -> {
+ counter.set(1);
+ lock.countDown();
+ });
+ executor.submit(() -> {
+ counter.compareAndSet(1, 2);
+ lock.countDown();
+ });
+
+ lock.await(1000, TimeUnit.MILLISECONDS);
+ assertEquals(2, counter.get());
+
+ }
+
+ @Test(timeout = 1000)
+ public void whenSchedulingTask_thenTaskExecutesWithinGivenPeriod() throws InterruptedException {
+
+ CountDownLatch lock = new CountDownLatch(1);
+
+ ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
+ executor.schedule(() -> {
+ System.out.println("Hello World");
+ lock.countDown();
+ }, 500, TimeUnit.MILLISECONDS);
+
+ lock.await(1000, TimeUnit.MILLISECONDS);
+
+ }
+
+ @Test(timeout = 1000)
+ public void whenSchedulingTaskWithFixedPeriod_thenTaskExecutesMultipleTimes() throws InterruptedException {
+
+ CountDownLatch lock = new CountDownLatch(3);
+
+ ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
+ ScheduledFuture> future = executor.scheduleAtFixedRate(() -> {
+ System.out.println("Hello World");
+ lock.countDown();
+ }, 500, 100, TimeUnit.MILLISECONDS);
+
+ lock.await();
+ future.cancel(true);
+
+ }
+
+ @Test
+ public void whenUsingForkJoinPool_thenSumOfTreeElementsIsCalculatedCorrectly() {
+
+ TreeNode tree = new TreeNode(5,
+ new TreeNode(3), new TreeNode(2,
+ new TreeNode(2), new TreeNode(8)));
+
+ ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
+ int sum = forkJoinPool.invoke(new CountingTask(tree));
+
+ assertEquals(20, sum);
+ }
+
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java b/core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java
new file mode 100644
index 0000000000..92e0f9a8cb
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/threadpool/GuavaThreadPoolTest.java
@@ -0,0 +1,56 @@
+package com.baeldung.threadpool;
+
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class GuavaThreadPoolTest {
+
+ @Test
+ public void whenExecutingTaskWithDirectExecutor_thenTheTaskIsExecutedInTheCurrentThread() {
+
+ Executor executor = MoreExecutors.directExecutor();
+
+ AtomicBoolean executed = new AtomicBoolean();
+
+ executor.execute(() -> {
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ executed.set(true);
+ });
+
+ assertTrue(executed.get());
+ }
+
+ @Test
+ public void whenJoiningFuturesWithAllAsList_thenCombinedFutureCompletesAfterAllFuturesComplete() throws ExecutionException, InterruptedException {
+
+ ExecutorService executorService = Executors.newCachedThreadPool();
+ ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService);
+
+ ListenableFuture future1 = listeningExecutorService.submit(() -> "Hello");
+ ListenableFuture future2 = listeningExecutorService.submit(() -> "World");
+
+ String greeting = Futures.allAsList(future1, future2).get()
+ .stream()
+ .collect(Collectors.joining(" "));
+ assertEquals("Hello World", greeting);
+
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java
new file mode 100644
index 0000000000..06d9394a5e
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeTest.java
@@ -0,0 +1,47 @@
+package com.baeldung.util;
+
+import static org.junit.Assert.assertEquals;
+
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalTime;
+import java.time.temporal.ChronoField;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+
+import org.junit.Test;
+
+public class CurrentDateTimeTest {
+
+ @Test
+ public void shouldReturnCurrentDate() {
+
+ final LocalDate now = LocalDate.now();
+ final Calendar calendar = GregorianCalendar.getInstance();
+
+ assertEquals("10-10-2010".length(), now.toString().length());
+ assertEquals(calendar.get(Calendar.DATE), now.get(ChronoField.DAY_OF_MONTH));
+ assertEquals(calendar.get(Calendar.MONTH), now.get(ChronoField.MONTH_OF_YEAR) - 1);
+ assertEquals(calendar.get(Calendar.YEAR), now.get(ChronoField.YEAR));
+ }
+
+ @Test
+ public void shouldReturnCurrentTime() {
+
+ final LocalTime now = LocalTime.now();
+ final Calendar calendar = GregorianCalendar.getInstance();
+
+ assertEquals(calendar.get(Calendar.HOUR_OF_DAY), now.get(ChronoField.HOUR_OF_DAY));
+ assertEquals(calendar.get(Calendar.MINUTE), now.get(ChronoField.MINUTE_OF_HOUR));
+ assertEquals(calendar.get(Calendar.SECOND), now.get(ChronoField.SECOND_OF_MINUTE));
+ }
+
+ @Test
+ public void shouldReturnCurrentTimestamp() {
+
+ final Instant now = Instant.now();
+ final Calendar calendar = GregorianCalendar.getInstance();
+
+ assertEquals(calendar.getTimeInMillis() / 1000, now.getEpochSecond());
+ }
+}
diff --git a/core-java-8/src/test/resources/test.txt b/core-java-8/src/test/resources/test.txt
new file mode 100644
index 0000000000..652d70630f
--- /dev/null
+++ b/core-java-8/src/test/resources/test.txt
@@ -0,0 +1 @@
+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse facilisis neque sed turpis venenatis, non dignissim risus volutpat.
\ No newline at end of file
diff --git a/core-java-8/src/test/resources/.gitignore b/core-java-9/.gitignore
similarity index 100%
rename from core-java-8/src/test/resources/.gitignore
rename to core-java-9/.gitignore
diff --git a/core-java-9/README.md b/core-java-9/README.md
new file mode 100644
index 0000000000..b5d4dbef95
--- /dev/null
+++ b/core-java-9/README.md
@@ -0,0 +1,5 @@
+=========
+
+## Core Java 9 Examples
+
+http://inprogress.baeldung.com/java-9-new-features/
\ No newline at end of file
diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml
new file mode 100644
index 0000000000..844ad6a782
--- /dev/null
+++ b/core-java-9/pom.xml
@@ -0,0 +1,93 @@
+
+ 4.0.0
+ com.baeldung
+ core-java9
+ 0.2-SNAPSHOT
+
+ core-java9
+
+
+
+ apache.snapshots
+ http://repository.apache.org/snapshots/
+
+
+
+
+
+
+ org.slf4j
+ slf4j-api
+ ${org.slf4j.version}
+
+
+
+
+
+ org.hamcrest
+ hamcrest-library
+ ${org.hamcrest.version}
+ test
+
+
+
+ junit
+ junit
+ ${junit.version}
+ test
+
+
+
+ org.mockito
+ mockito-core
+ ${mockito.version}
+ test
+
+
+
+
+
+ core-java-9
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ 1.9
+ 1.9
+ true
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+
+
+
+
+
+
+ 1.7.13
+ 1.0.13
+
+
+
+ 3.6-jigsaw-SNAPSHOT
+ 2.19.1
+
+
+ 1.3
+ 4.12
+ 1.10.19
+
+
+
diff --git a/mockito-mocks-spring-beans/.gitignore b/core-java-9/src/main/java/.gitignore
similarity index 100%
rename from mockito-mocks-spring-beans/.gitignore
rename to core-java-9/src/main/java/.gitignore
diff --git a/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java b/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java
new file mode 100644
index 0000000000..fd6a496b18
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/language/PrivateInterface.java
@@ -0,0 +1,23 @@
+package com.baeldung.java9.language;
+
+public interface PrivateInterface {
+
+ private static String staticPrivate() {
+ return "static private";
+ }
+
+ private String instancePrivate() {
+ return "instance private";
+ }
+
+ public default void check(){
+ String result = staticPrivate();
+ if (!result.equals("static private"))
+ throw new AssertionError("Incorrect result for static private interface method");
+ PrivateInterface pvt = new PrivateInterface() {
+ };
+ result = pvt.instancePrivate();
+ if (!result.equals("instance private"))
+ throw new AssertionError("Incorrect result for instance private interface method");
+ }
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java
new file mode 100644
index 0000000000..d6682bd0c8
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUtils.java
@@ -0,0 +1,44 @@
+package com.baeldung.java9.process;
+
+import java.io.File;
+import java.io.IOException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.stream.Stream;
+
+
+public class ProcessUtils {
+
+ public static String getClassPath(){
+ String cp = System.getProperty("java.class.path");
+ System.out.println("ClassPath is "+cp);
+ return cp;
+ }
+
+ public static File getJavaCmd() throws IOException{
+ String javaHome = System.getProperty("java.home");
+ File javaCmd;
+ if(System.getProperty("os.name").startsWith("Win")){
+ javaCmd = new File(javaHome, "bin/java.exe");
+ }else{
+ javaCmd = new File(javaHome, "bin/java");
+ }
+ if(javaCmd.canExecute()){
+ return javaCmd;
+ }else{
+ throw new UnsupportedOperationException(javaCmd.getCanonicalPath() + " is not executable");
+ }
+ }
+
+ public static String getMainClass(){
+ return System.getProperty("sun.java.command");
+ }
+
+ public static String getSystemProperties(){
+ StringBuilder sb = new StringBuilder();
+ System.getProperties().forEach((s1, s2) -> sb.append(s1 +" - "+ s2) );
+ return sb.toString();
+ }
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java
new file mode 100644
index 0000000000..458f746496
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/process/ServiceMain.java
@@ -0,0 +1,22 @@
+package com.baeldung.java9.process;
+
+import java.util.Optional;
+
+public class ServiceMain {
+
+ public static void main(String[] args) throws InterruptedException {
+ ProcessHandle thisProcess = ProcessHandle.current();
+ long pid = thisProcess.getPid();
+
+
+ Optional opArgs = Optional.ofNullable(args);
+ String procName = opArgs.map(str -> str.length > 0 ? str[0] : null).orElse(System.getProperty("sun.java.command"));
+
+ for (int i = 0; i < 10000; i++) {
+ System.out.println("Process " + procName + " with ID " + pid + " is running!");
+ Thread.sleep(10000);
+ }
+
+ }
+
+}
diff --git a/core-java-9/src/main/resources/logback.xml b/core-java-9/src/main/resources/logback.xml
new file mode 100644
index 0000000000..eefdc7a337
--- /dev/null
+++ b/core-java-9/src/main/resources/logback.xml
@@ -0,0 +1,16 @@
+
+
+
+
+ web - %date [%thread] %-5level %logger{36} - %message%n
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java
new file mode 100644
index 0000000000..b0684a94f8
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/Java9OptionalsStreamTest.java
@@ -0,0 +1,71 @@
+package com.baeldung.java8;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class Java9OptionalsStreamTest {
+
+ private static List> listOfOptionals = Arrays.asList(Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));
+
+ @Test
+ public void filterOutPresentOptionalsWithFilter() {
+ assertEquals(4, listOfOptionals.size());
+
+ List filteredList = listOfOptionals.stream()
+ .filter(Optional::isPresent)
+ .map(Optional::get)
+ .collect(Collectors.toList());
+
+ assertEquals(2, filteredList.size());
+ assertEquals("foo", filteredList.get(0));
+ assertEquals("bar", filteredList.get(1));
+ }
+
+ @Test
+ public void filterOutPresentOptionalsWithFlatMap() {
+ assertEquals(4, listOfOptionals.size());
+
+ List filteredList = listOfOptionals.stream()
+ .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
+ .collect(Collectors.toList());
+ assertEquals(2, filteredList.size());
+
+ assertEquals("foo", filteredList.get(0));
+ assertEquals("bar", filteredList.get(1));
+ }
+
+ @Test
+ public void filterOutPresentOptionalsWithFlatMap2() {
+ assertEquals(4, listOfOptionals.size());
+
+ List filteredList = listOfOptionals.stream()
+ .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
+ .collect(Collectors.toList());
+ assertEquals(2, filteredList.size());
+
+ assertEquals("foo", filteredList.get(0));
+ assertEquals("bar", filteredList.get(1));
+ }
+
+ @Test
+ public void filterOutPresentOptionalsWithJava9() {
+ assertEquals(4, listOfOptionals.size());
+
+ List filteredList = listOfOptionals.stream()
+ .flatMap(Optional::stream)
+ .collect(Collectors.toList());
+
+ assertEquals(2, filteredList.size());
+ assertEquals("foo", filteredList.get(0));
+ assertEquals("bar", filteredList.get(1));
+ }
+
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java
new file mode 100644
index 0000000000..a00646e4db
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/MultiResultionImageTest.java
@@ -0,0 +1,47 @@
+package com.baeldung.java9;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+
+import java.awt.Image;
+import java.awt.image.BaseMultiResolutionImage;
+import java.awt.image.BufferedImage;
+import java.awt.image.MultiResolutionImage;
+import java.util.List;
+
+import org.junit.Test;
+
+public class MultiResultionImageTest {
+
+
+ @Test
+ public void baseMultiResImageTest() {
+ int baseIndex = 1;
+ int length = 4;
+ BufferedImage[] resolutionVariants = new BufferedImage[length];
+ for (int i = 0; i < length; i++) {
+ resolutionVariants[i] = createImage(i);
+ }
+ MultiResolutionImage bmrImage = new BaseMultiResolutionImage(baseIndex, resolutionVariants);
+ List rvImageList = bmrImage.getResolutionVariants();
+ assertEquals("MultiResoltion Image shoudl contain the same number of resolution variants!", rvImageList.size(), length);
+
+ for (int i = 0; i < length; i++) {
+ int imageSize = getSize(i);
+ Image testRVImage = bmrImage.getResolutionVariant(imageSize, imageSize);
+ assertSame("Images should be the same", testRVImage, resolutionVariants[i]);
+ }
+
+ }
+
+ private static int getSize(int i) {
+ return 8 * (i + 1);
+ }
+
+
+ private static BufferedImage createImage(int i) {
+ return new BufferedImage(getSize(i), getSize(i),
+ BufferedImage.TYPE_INT_RGB);
+ }
+
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java b/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java
new file mode 100644
index 0000000000..56b4bb7b8c
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/OptionalToStreamTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.java9;
+
+import java.util.Optional;
+import java.util.stream.Stream;
+
+import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+
+public class OptionalToStreamTest {
+
+ @Test
+ public void testOptionalToStream() {
+ Optional op = Optional.ofNullable("String value");
+ Stream strOptionalStream = op.stream();
+ Stream filteredStream = strOptionalStream.filter((str) -> {
+ return str != null && str.startsWith("String");
+ });
+ assertEquals(1, filteredStream.count());
+
+ }
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/README.MD b/core-java-9/src/test/java/com/baeldung/java9/README.MD
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/README.MD
@@ -0,0 +1 @@
+
diff --git a/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java
new file mode 100644
index 0000000000..0f8db83d9c
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/SetExamplesTest.java
@@ -0,0 +1,26 @@
+package com.baeldung.java9;
+
+import java.util.Set;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class SetExamplesTest {
+
+ @Test
+ public void testUnmutableSet() {
+ Set strKeySet = Set.of("key1", "key2", "key3");
+ try {
+ strKeySet.add("newKey");
+ } catch (UnsupportedOperationException uoe) {
+ }
+ assertEquals(strKeySet.size(), 3);
+ }
+
+ @Test
+ public void testArrayToSet() {
+ Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
+ Set intSet = Set.of(intArray);
+ assertEquals(intSet.size(), intArray.length);
+ }
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java
new file mode 100644
index 0000000000..ab28b0a805
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/httpclient/SimpleHttpRequestsTest.java
@@ -0,0 +1,126 @@
+package com.baeldung.java9.httpclient;
+
+
+
+import static java.net.HttpURLConnection.HTTP_OK;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.net.CookieManager;
+import java.net.CookiePolicy;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpHeaders;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.security.NoSuchAlgorithmException;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLParameters;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class SimpleHttpRequestsTest {
+
+ private URI httpURI;
+
+ @Before
+ public void init() throws URISyntaxException {
+ httpURI = new URI("http://www.baeldung.com/");
+ }
+
+ @Test
+ public void quickGet() throws IOException, InterruptedException, URISyntaxException {
+ HttpRequest request = HttpRequest.create( httpURI ).GET();
+ HttpResponse response = request.response();
+ int responseStatusCode = response.statusCode();
+ String responseBody = response.body(HttpResponse.asString());
+ assertTrue("Get response status code is bigger then 400", responseStatusCode < 400);
+ }
+
+ @Test
+ public void asynchronousGet() throws URISyntaxException, IOException, InterruptedException, ExecutionException{
+ HttpRequest request = HttpRequest.create(httpURI).GET();
+ long before = System.currentTimeMillis();
+ CompletableFuture futureResponse = request.responseAsync();
+ futureResponse.thenAccept( response -> {
+ String responseBody = response.body(HttpResponse.asString());
+ });
+ HttpResponse resp = futureResponse.get();
+ HttpHeaders hs = resp.headers();
+ assertTrue("There should be more then 1 header.", hs.map().size() >1);
+ }
+
+ @Test
+ public void postMehtod() throws URISyntaxException, IOException, InterruptedException {
+ HttpRequest.Builder requestBuilder = HttpRequest.create(httpURI);
+ requestBuilder.body(HttpRequest.fromString("param1=foo,param2=bar")).followRedirects(HttpClient.Redirect.SECURE);
+ HttpRequest request = requestBuilder.POST();
+ HttpResponse response = request.response();
+ int statusCode = response.statusCode();
+ assertTrue("HTTP return code", statusCode == HTTP_OK);
+ }
+
+ @Test
+ public void configureHttpClient() throws NoSuchAlgorithmException, URISyntaxException, IOException, InterruptedException{
+ CookieManager cManager = new CookieManager();
+ cManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
+
+ SSLParameters sslParam = new SSLParameters (new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256" }, new String[] { "TLSv1.2" });
+
+ HttpClient.Builder hcBuilder = HttpClient.create();
+ hcBuilder.cookieManager(cManager).sslContext(SSLContext.getDefault()).sslParameters(sslParam);
+ HttpClient httpClient = hcBuilder.build();
+ HttpRequest.Builder reqBuilder = httpClient.request(new URI("https://www.facebook.com"));
+
+ HttpRequest request = reqBuilder.followRedirects(HttpClient.Redirect.ALWAYS).GET();
+ HttpResponse response = request.response();
+ int statusCode = response.statusCode();
+ assertTrue("HTTP return code", statusCode == HTTP_OK);
+ }
+
+ SSLParameters getDefaultSSLParameters() throws NoSuchAlgorithmException{
+ SSLParameters sslP1 = SSLContext.getDefault().getSupportedSSLParameters();
+ String [] proto = sslP1.getApplicationProtocols();
+ String [] cifers = sslP1.getCipherSuites();
+ System.out.println(printStringArr(proto));
+ System.out.println(printStringArr(cifers));
+ return sslP1;
+ }
+
+ String printStringArr(String ... args ){
+ if(args == null){
+ return null;
+ }
+ StringBuilder sb = new StringBuilder();
+ for (String s : args){
+ sb.append(s);
+ sb.append("\n");
+ }
+ return sb.toString();
+ }
+
+ String printHeaders(HttpHeaders h){
+ if(h == null){
+ return null;
+ }
+
+ StringBuilder sb = new StringBuilder();
+ Map> hMap = h.map();
+ for(String k : hMap.keySet()){
+ sb.append(k).append(":");
+ List l = hMap.get(k);
+ if( l != null ){
+ l.forEach( s -> { sb.append(s).append(","); } );
+ }
+ sb.append("\n");
+ }
+ return sb.toString();
+ }
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/DiamondTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/DiamondTest.java
new file mode 100644
index 0000000000..33da6486f4
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/language/DiamondTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.java9.language;
+
+import org.junit.Test;
+
+public class DiamondTest {
+
+ static class FooClass {
+ FooClass(X x) {
+ }
+
+ FooClass(X x, Z z) {
+ }
+ }
+
+ @Test
+ public void diamondTest() {
+ FooClass fc = new FooClass<>(1) {
+ };
+ FooClass extends Integer> fc0 = new FooClass<>(1) {
+ };
+ FooClass> fc1 = new FooClass<>(1) {
+ };
+ FooClass super Integer> fc2 = new FooClass<>(1) {
+ };
+
+ FooClass fc3 = new FooClass<>(1, "") {
+ };
+ FooClass extends Integer> fc4 = new FooClass<>(1, "") {
+ };
+ FooClass> fc5 = new FooClass<>(1, "") {
+ };
+ FooClass super Integer> fc6 = new FooClass<>(1, "") {
+ };
+
+ }
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java
new file mode 100644
index 0000000000..29ef3930f8
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/language/PrivateInterfaceTest.java
@@ -0,0 +1,15 @@
+package com.baeldung.java9.language;
+
+import com.baeldung.java9.language.PrivateInterface;
+import org.junit.Test;
+
+public class PrivateInterfaceTest {
+
+ @Test
+ public void test() {
+ PrivateInterface piClass = new PrivateInterface() {
+ };
+ piClass.check();
+ }
+
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java
new file mode 100644
index 0000000000..687dfbc390
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/language/TryWithResourcesTest.java
@@ -0,0 +1,70 @@
+package com.baeldung.java9.language;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Test;
+
+public class TryWithResourcesTest {
+
+ static int closeCount = 0;
+
+ static class MyAutoCloseable implements AutoCloseable{
+ final FinalWrapper finalWrapper = new FinalWrapper();
+
+ public void close() {
+ closeCount++;
+ }
+
+ static class FinalWrapper {
+ public final AutoCloseable finalCloseable = new AutoCloseable() {
+ @Override
+ public void close() throws Exception {
+ closeCount++;
+ }
+ };
+ }
+ }
+
+ @Test
+ public void tryWithResourcesTest() {
+ MyAutoCloseable mac = new MyAutoCloseable();
+
+ try (mac) {
+ assertEquals("Expected and Actual does not match", 0, closeCount);
+ }
+
+ try (mac.finalWrapper.finalCloseable) {
+ assertEquals("Expected and Actual does not match", 1, closeCount);
+ } catch (Exception ex) {
+ }
+
+ try (new MyAutoCloseable() { }.finalWrapper.finalCloseable) {
+ assertEquals("Expected and Actual does not match", 2, closeCount);
+ } catch (Exception ex) {
+ }
+
+ try ((closeCount > 0 ? mac : new MyAutoCloseable()).finalWrapper.finalCloseable) {
+ assertEquals("Expected and Actual does not match", 3, closeCount);
+ } catch (Exception ex) {
+ }
+
+ try {
+ throw new CloseableException();
+ } catch (CloseableException ex) {
+ try (ex) {
+ assertEquals("Expected and Actual does not match", 4, closeCount);
+ }
+ }
+ assertEquals("Expected and Actual does not match", 5, closeCount);
+ }
+
+
+ static class CloseableException extends Exception implements AutoCloseable {
+ @Override
+ public void close() {
+ closeCount++;
+ }
+ }
+
+}
+
+
diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java
new file mode 100644
index 0000000000..419516cb64
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessApi.java
@@ -0,0 +1,112 @@
+package com.baeldung.java9.process;
+
+import java.io.IOException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.CompletableFuture;
+import java.util.stream.Stream;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import junit.framework.Assert;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class ProcessApi {
+
+
+ @Before
+ public void init() {
+
+ }
+
+ @Test
+ public void processInfoExample()throws NoSuchAlgorithmException{
+ ProcessHandle self = ProcessHandle.current();
+ long PID = self.getPid();
+ ProcessHandle.Info procInfo = self.info();
+ Optional args = procInfo.arguments();
+ Optional cmd = procInfo.commandLine();
+ Optional startTime = procInfo.startInstant();
+ Optional cpuUsage = procInfo.totalCpuDuration();
+
+ waistCPU();
+ System.out.println("Args "+ args);
+ System.out.println("Command " +cmd.orElse("EmptyCmd"));
+ System.out.println("Start time: "+ startTime.get().toString());
+ System.out.println(cpuUsage.get().toMillis());
+
+ Stream allProc = ProcessHandle.current().children();
+ allProc.forEach(p -> {
+ System.out.println("Proc "+ p.getPid());
+ });
+
+ }
+
+ @Test
+ public void createAndDestroyProcess() throws IOException, InterruptedException{
+ int numberOfChildProcesses = 5;
+ for(int i=0; i < numberOfChildProcesses; i++){
+ createNewJVM(ServiceMain.class, i).getPid();
+ }
+
+ Stream childProc = ProcessHandle.current().children();
+ assertEquals( childProc.count(), numberOfChildProcesses);
+
+ childProc = ProcessHandle.current().children();
+ childProc.forEach(processHandle -> {
+ assertTrue("Process "+ processHandle.getPid() +" should be alive!", processHandle.isAlive());
+ CompletableFuture onProcExit = processHandle.onExit();
+ onProcExit.thenAccept(procHandle -> {
+ System.out.println("Process with PID "+ procHandle.getPid() + " has stopped");
+ });
+ });
+
+ Thread.sleep(10000);
+
+ childProc = ProcessHandle.current().children();
+ childProc.forEach(procHandle -> {
+ assertTrue("Could not kill process "+procHandle.getPid(), procHandle.destroy());
+ });
+
+ Thread.sleep(5000);
+
+ childProc = ProcessHandle.current().children();
+ childProc.forEach(procHandle -> {
+ assertFalse("Process "+ procHandle.getPid() +" should not be alive!", procHandle.isAlive());
+ });
+
+ }
+
+ private Process createNewJVM(Class mainClass, int number) throws IOException{
+ ArrayList cmdParams = new ArrayList(5);
+ cmdParams.add(ProcessUtils.getJavaCmd().getAbsolutePath());
+ cmdParams.add("-cp");
+ cmdParams.add(ProcessUtils.getClassPath());
+ cmdParams.add(mainClass.getName());
+ cmdParams.add("Service "+ number);
+ ProcessBuilder myService = new ProcessBuilder(cmdParams);
+ myService.inheritIO();
+ return myService.start();
+ }
+
+ private void waistCPU() throws NoSuchAlgorithmException{
+ ArrayList randArr = new ArrayList(4096);
+ SecureRandom sr = SecureRandom.getInstanceStrong();
+ Duration somecpu = Duration.ofMillis(4200L);
+ Instant end = Instant.now().plus(somecpu);
+ while (Instant.now().isBefore(end)) {
+ //System.out.println(sr.nextInt());
+ randArr.add( sr.nextInt() );
+ }
+ }
+
+}
diff --git a/mockito/src/test/resources/.gitignore b/core-java-9/src/test/resources/.gitignore
similarity index 100%
rename from mockito/src/test/resources/.gitignore
rename to core-java-9/src/test/resources/.gitignore
diff --git a/core-java/.classpath b/core-java/.classpath
deleted file mode 100644
index f9b079e8c9..0000000000
--- a/core-java/.classpath
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/core-java/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/core-java/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch
deleted file mode 100644
index 627021fb96..0000000000
--- a/core-java/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch
+++ /dev/null
@@ -1,7 +0,0 @@
-
-
-
-
-
-
-
diff --git a/core-java/.project b/core-java/.project
deleted file mode 100644
index 12bfa7d869..0000000000
--- a/core-java/.project
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
- core-java
-
-
-
-
-
- org.eclipse.jdt.core.javabuilder
-
-
-
-
- org.eclipse.wst.common.project.facet.core.builder
-
-
-
-
- org.eclipse.wst.validation.validationbuilder
-
-
-
-
- org.eclipse.m2e.core.maven2Builder
-
-
-
-
-
- org.eclipse.jem.workbench.JavaEMFNature
- org.eclipse.wst.common.modulecore.ModuleCoreNature
- org.eclipse.jdt.core.javanature
- org.eclipse.m2e.core.maven2Nature
- org.eclipse.wst.common.project.facet.core.nature
-
-
diff --git a/core-java/.settings/.jsdtscope b/core-java/.settings/.jsdtscope
deleted file mode 100644
index 7b3f0c8b9f..0000000000
--- a/core-java/.settings/.jsdtscope
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/core-java/.settings/org.eclipse.jdt.core.prefs b/core-java/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index 046168cf24..0000000000
--- a/core-java/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,95 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
-org.eclipse.jdt.core.compiler.compliance=1.7
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=error
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=error
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.7
diff --git a/core-java/.settings/org.eclipse.jdt.ui.prefs b/core-java/.settings/org.eclipse.jdt.ui.prefs
deleted file mode 100644
index 471e9b0d81..0000000000
--- a/core-java/.settings/org.eclipse.jdt.ui.prefs
+++ /dev/null
@@ -1,55 +0,0 @@
-#Sat Jan 21 23:04:06 EET 2012
-eclipse.preferences.version=1
-editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
-sp_cleanup.add_default_serial_version_id=true
-sp_cleanup.add_generated_serial_version_id=false
-sp_cleanup.add_missing_annotations=true
-sp_cleanup.add_missing_deprecated_annotations=true
-sp_cleanup.add_missing_methods=false
-sp_cleanup.add_missing_nls_tags=false
-sp_cleanup.add_missing_override_annotations=true
-sp_cleanup.add_missing_override_annotations_interface_methods=true
-sp_cleanup.add_serial_version_id=false
-sp_cleanup.always_use_blocks=true
-sp_cleanup.always_use_parentheses_in_expressions=true
-sp_cleanup.always_use_this_for_non_static_field_access=false
-sp_cleanup.always_use_this_for_non_static_method_access=false
-sp_cleanup.convert_to_enhanced_for_loop=true
-sp_cleanup.correct_indentation=true
-sp_cleanup.format_source_code=true
-sp_cleanup.format_source_code_changes_only=true
-sp_cleanup.make_local_variable_final=true
-sp_cleanup.make_parameters_final=true
-sp_cleanup.make_private_fields_final=false
-sp_cleanup.make_type_abstract_if_missing_method=false
-sp_cleanup.make_variable_declarations_final=true
-sp_cleanup.never_use_blocks=false
-sp_cleanup.never_use_parentheses_in_expressions=false
-sp_cleanup.on_save_use_additional_actions=true
-sp_cleanup.organize_imports=true
-sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
-sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
-sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
-sp_cleanup.qualify_static_member_accesses_with_declaring_class=true
-sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
-sp_cleanup.remove_private_constructors=true
-sp_cleanup.remove_trailing_whitespaces=true
-sp_cleanup.remove_trailing_whitespaces_all=true
-sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
-sp_cleanup.remove_unnecessary_casts=true
-sp_cleanup.remove_unnecessary_nls_tags=false
-sp_cleanup.remove_unused_imports=true
-sp_cleanup.remove_unused_local_variables=false
-sp_cleanup.remove_unused_private_fields=true
-sp_cleanup.remove_unused_private_members=false
-sp_cleanup.remove_unused_private_methods=true
-sp_cleanup.remove_unused_private_types=true
-sp_cleanup.sort_members=false
-sp_cleanup.sort_members_all=false
-sp_cleanup.use_blocks=false
-sp_cleanup.use_blocks_only_for_return_and_throw=false
-sp_cleanup.use_parentheses_in_expressions=false
-sp_cleanup.use_this_for_non_static_field_access=true
-sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
-sp_cleanup.use_this_for_non_static_method_access=true
-sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
diff --git a/core-java/.settings/org.eclipse.m2e.core.prefs b/core-java/.settings/org.eclipse.m2e.core.prefs
deleted file mode 100644
index f897a7f1cb..0000000000
--- a/core-java/.settings/org.eclipse.m2e.core.prefs
+++ /dev/null
@@ -1,4 +0,0 @@
-activeProfiles=
-eclipse.preferences.version=1
-resolveWorkspaceProjects=true
-version=1
diff --git a/core-java/.settings/org.eclipse.m2e.wtp.prefs b/core-java/.settings/org.eclipse.m2e.wtp.prefs
deleted file mode 100644
index ef86089622..0000000000
--- a/core-java/.settings/org.eclipse.m2e.wtp.prefs
+++ /dev/null
@@ -1,2 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false
diff --git a/core-java/.settings/org.eclipse.wst.common.component b/core-java/.settings/org.eclipse.wst.common.component
deleted file mode 100644
index e98377cb0f..0000000000
--- a/core-java/.settings/org.eclipse.wst.common.component
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
-
-
-
-
-
-
diff --git a/core-java/.settings/org.eclipse.wst.common.project.facet.core.xml b/core-java/.settings/org.eclipse.wst.common.project.facet.core.xml
deleted file mode 100644
index bc0009a455..0000000000
--- a/core-java/.settings/org.eclipse.wst.common.project.facet.core.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
diff --git a/core-java/.settings/org.eclipse.wst.jsdt.ui.superType.container b/core-java/.settings/org.eclipse.wst.jsdt.ui.superType.container
deleted file mode 100644
index 3bd5d0a480..0000000000
--- a/core-java/.settings/org.eclipse.wst.jsdt.ui.superType.container
+++ /dev/null
@@ -1 +0,0 @@
-org.eclipse.wst.jsdt.launching.baseBrowserLibrary
\ No newline at end of file
diff --git a/core-java/.settings/org.eclipse.wst.jsdt.ui.superType.name b/core-java/.settings/org.eclipse.wst.jsdt.ui.superType.name
deleted file mode 100644
index 05bd71b6ec..0000000000
--- a/core-java/.settings/org.eclipse.wst.jsdt.ui.superType.name
+++ /dev/null
@@ -1 +0,0 @@
-Window
\ No newline at end of file
diff --git a/core-java/.settings/org.eclipse.wst.validation.prefs b/core-java/.settings/org.eclipse.wst.validation.prefs
deleted file mode 100644
index cacf5451ae..0000000000
--- a/core-java/.settings/org.eclipse.wst.validation.prefs
+++ /dev/null
@@ -1,14 +0,0 @@
-DELEGATES_PREFERENCE=delegateValidatorList
-USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
-USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
-USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.303.v201202090300
-eclipse.preferences.version=1
-override=true
-suspend=false
-vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01
-vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01
-vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01
-vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01
-vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01
-vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02
-vf.version=3
diff --git a/core-java/.settings/org.eclipse.wst.ws.service.policy.prefs b/core-java/.settings/org.eclipse.wst.ws.service.policy.prefs
deleted file mode 100644
index 9cfcabe16f..0000000000
--- a/core-java/.settings/org.eclipse.wst.ws.service.policy.prefs
+++ /dev/null
@@ -1,2 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.wst.ws.service.policy.projectEnabled=false
diff --git a/core-java/.springBeans b/core-java/.springBeans
deleted file mode 100644
index a79097f40d..0000000000
--- a/core-java/.springBeans
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
- 1
-
-
-
-
-
-
- src/main/webapp/WEB-INF/api-servlet.xml
-
-
-
-
diff --git a/core-java/README.md b/core-java/README.md
index 772681ad57..23fe12465f 100644
--- a/core-java/README.md
+++ b/core-java/README.md
@@ -6,4 +6,10 @@
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
- [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file)
- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string)
-
+- [Converting between an Array and a List in Java](http://www.baeldung.com/convert-array-to-list-and-list-to-array)
+- [Converting between an Array and a Set in Java](http://www.baeldung.com/convert-array-to-set-and-set-to-array)
+- [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list)
+- [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set)
+- [Java – Write to File](http://www.baeldung.com/java-write-to-file)
+- [Java Scanner](http://www.baeldung.com/java-scanner)
+- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
diff --git a/core-java/pom.xml b/core-java/pom.xml
index b439b41f22..bce97d1148 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -1,15 +1,19 @@
4.0.0
- org.baeldung
+ com.baeldung
core-java
- 0.1-SNAPSHOT
+ 0.1.0-SNAPSHOT
core-java
-
+
+ net.sourceforge.collections
+ collections-generic
+ 4.01
+
com.google.guava
guava
@@ -97,12 +101,34 @@
test
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+
+ org.testng
+ testng
+ ${testng.version}
+ test
+
+
+
+
org.mockito
mockito-core
${mockito.version}
test
+
+
+ commons-codec
+ commons-codec
+ 1.10
+
@@ -122,8 +148,8 @@
maven-compiler-plugin
${maven-compiler-plugin.version}
- 1.7
- 1.7
+ 1.8
+ 1.8
@@ -143,16 +169,12 @@
-
- 4.1.5.RELEASE
- 3.2.5.RELEASE
-
- 4.3.10.Final
- 5.1.35
+ 4.3.11.Final
+ 5.1.38
- 2.5.5
+ 2.7.2
1.7.13
@@ -169,18 +191,20 @@
1.3
4.12
1.10.19
+ 6.8
+ 3.5.1
4.4.1
4.5
- 2.4.1
+ 2.9.0
- 3.3
+ 3.5.1
2.6
- 2.18.1
+ 2.19.1
2.7
- 1.4.14
+ 1.4.18
diff --git a/core-java/src/main/java/com/baeldung/enums/Pizza.java b/core-java/src/main/java/com/baeldung/enums/Pizza.java
new file mode 100644
index 0000000000..7742781081
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/enums/Pizza.java
@@ -0,0 +1,110 @@
+package com.baeldung.enums;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.collections15.Predicate;
+
+import java.io.IOException;
+import java.util.EnumMap;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class Pizza {
+
+ private static EnumSet undeliveredPizzaStatuses =
+ EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY);
+
+ private PizzaStatus status;
+
+ @JsonFormat(shape = JsonFormat.Shape.OBJECT)
+ public enum PizzaStatus {
+ ORDERED(5) {
+ @Override
+ public boolean isOrdered() {
+ return true;
+ }
+ },
+ READY(2) {
+ @Override
+ public boolean isReady() {
+ return true;
+ }
+ },
+ DELIVERED(0) {
+ @Override
+ public boolean isDelivered() {
+ return true;
+ }
+ };
+
+ private int timeToDelivery;
+
+ public boolean isOrdered() {
+ return false;
+ }
+
+ public boolean isReady() {
+ return false;
+ }
+
+ public boolean isDelivered() {
+ return false;
+ }
+
+ @JsonProperty("timeToDelivery")
+ public int getTimeToDelivery() {
+ return timeToDelivery;
+ }
+
+ PizzaStatus(int timeToDelivery) {
+ this.timeToDelivery = timeToDelivery;
+ }
+ }
+
+ public PizzaStatus getStatus() {
+ return status;
+ }
+
+ public void setStatus(PizzaStatus status) {
+ this.status = status;
+ }
+
+ public boolean isDeliverable() {
+ return this.status.isReady();
+ }
+
+ public void printTimeToDeliver() {
+ System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
+ }
+
+ public static List getAllUndeliveredPizzas(List input) {
+ return input.stream().filter(
+ (s) -> undeliveredPizzaStatuses.contains(s.getStatus()))
+ .collect(Collectors.toList());
+ }
+
+ public static EnumMap>
+ groupPizzaByStatus(List pzList) {
+ return pzList.stream().collect(
+ Collectors.groupingBy(Pizza::getStatus,
+ () -> new EnumMap<>(PizzaStatus.class), Collectors.toList()));
+ }
+
+ public void deliver() {
+ if (isDeliverable()) {
+ PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
+ this.setStatus(PizzaStatus.DELIVERED);
+ }
+ }
+
+ public static String getJsonString(Pizza pz) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pz);
+ }
+
+ private static Predicate thatAreNotDelivered() {
+ return entry -> undeliveredPizzaStatuses.contains(entry.getStatus());
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java b/core-java/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java
new file mode 100644
index 0000000000..ed65919387
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java
@@ -0,0 +1,18 @@
+package com.baeldung.enums;
+
+public enum PizzaDeliveryStrategy {
+ EXPRESS {
+ @Override
+ public void deliver(Pizza pz) {
+ System.out.println("Pizza will be delivered in express mode");
+ }
+ },
+ NORMAL {
+ @Override
+ public void deliver(Pizza pz) {
+ System.out.println("Pizza will be delivered in normal mode");
+ }
+ };
+
+ public abstract void deliver(Pizza pz);
+}
diff --git a/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java b/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java
new file mode 100644
index 0000000000..a276b3c000
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java
@@ -0,0 +1,21 @@
+package com.baeldung.enums;
+
+public enum PizzaDeliverySystemConfiguration {
+ INSTANCE;
+
+ PizzaDeliverySystemConfiguration() {
+ // Do the configuration initialization which
+ // involves overriding defaults like delivery strategy
+ }
+
+ private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
+
+ public static PizzaDeliverySystemConfiguration getInstance() {
+ return INSTANCE;
+ }
+
+ public PizzaDeliveryStrategy getDeliveryStrategy() {
+ return deliveryStrategy;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Animal.java b/core-java/src/main/java/com/baeldung/java/reflection/Animal.java
new file mode 100644
index 0000000000..3f36243c29
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/reflection/Animal.java
@@ -0,0 +1,23 @@
+package com.baeldung.java.reflection;
+
+public abstract class Animal implements Eating {
+
+ public static final String CATEGORY = "domestic";
+
+ private String name;
+
+ public Animal(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ protected abstract String getSound();
+
+}
diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Bird.java b/core-java/src/main/java/com/baeldung/java/reflection/Bird.java
new file mode 100644
index 0000000000..bd6f13094c
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/reflection/Bird.java
@@ -0,0 +1,36 @@
+package com.baeldung.java.reflection;
+
+public class Bird extends Animal {
+ private boolean walks;
+
+ public Bird() {
+ super("bird");
+ }
+
+ public Bird(String name, boolean walks) {
+ super(name);
+ setWalks(walks);
+ }
+
+ public Bird(String name) {
+ super(name);
+ }
+
+ @Override
+ public String eats() {
+ return "grains";
+ }
+
+ @Override
+ protected String getSound() {
+ return "chaps";
+ }
+
+ public boolean walks() {
+ return walks;
+ }
+
+ public void setWalks(boolean walks) {
+ this.walks = walks;
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Eating.java b/core-java/src/main/java/com/baeldung/java/reflection/Eating.java
new file mode 100644
index 0000000000..479425cad4
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/reflection/Eating.java
@@ -0,0 +1,5 @@
+package com.baeldung.java.reflection;
+
+public interface Eating {
+ String eats();
+}
diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Goat.java b/core-java/src/main/java/com/baeldung/java/reflection/Goat.java
new file mode 100644
index 0000000000..503717ae5e
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/reflection/Goat.java
@@ -0,0 +1,24 @@
+package com.baeldung.java.reflection;
+
+public class Goat extends Animal implements Locomotion {
+
+ public Goat(String name) {
+ super(name);
+ }
+
+ @Override
+ protected String getSound() {
+ return "bleat";
+ }
+
+ @Override
+ public String getLocomotion() {
+ return "walks";
+ }
+
+ @Override
+ public String eats() {
+ return "grass";
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Locomotion.java b/core-java/src/main/java/com/baeldung/java/reflection/Locomotion.java
new file mode 100644
index 0000000000..047c00cb13
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/reflection/Locomotion.java
@@ -0,0 +1,5 @@
+package com.baeldung.java.reflection;
+
+public interface Locomotion {
+ String getLocomotion();
+}
diff --git a/core-java/src/main/java/com/baeldung/java/reflection/Person.java b/core-java/src/main/java/com/baeldung/java/reflection/Person.java
new file mode 100644
index 0000000000..f3d7f9f001
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/reflection/Person.java
@@ -0,0 +1,6 @@
+package com.baeldung.java.reflection;
+
+public class Person {
+ private String name;
+ private int age;
+}
diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java
new file mode 100644
index 0000000000..d4a6a0f42e
--- /dev/null
+++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/ComplexClass.java
@@ -0,0 +1,65 @@
+package org.baeldung.equalshashcode.entities;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+public class ComplexClass {
+
+ private List> genericList;
+ private Set integerSet;
+
+ public ComplexClass(ArrayList> genericArrayList, HashSet integerHashSet) {
+ super();
+ this.genericList = genericArrayList;
+ this.integerSet = integerHashSet;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((genericList == null) ? 0 : genericList.hashCode());
+ result = prime * result + ((integerSet == null) ? 0 : integerSet.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (!(obj instanceof ComplexClass))
+ return false;
+ ComplexClass other = (ComplexClass) obj;
+ if (genericList == null) {
+ if (other.genericList != null)
+ return false;
+ } else if (!genericList.equals(other.genericList))
+ return false;
+ if (integerSet == null) {
+ if (other.integerSet != null)
+ return false;
+ } else if (!integerSet.equals(other.integerSet))
+ return false;
+ return true;
+ }
+
+ protected List> getGenericList() {
+ return genericList;
+ }
+
+ protected void setGenericArrayList(List> genericList) {
+ this.genericList = genericList;
+ }
+
+ protected Set getIntegerSet() {
+ return integerSet;
+ }
+
+ protected void setIntegerSet(Set integerSet) {
+ this.integerSet = integerSet;
+ }
+}
diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java
new file mode 100644
index 0000000000..ebe005688c
--- /dev/null
+++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/PrimitiveClass.java
@@ -0,0 +1,54 @@
+package org.baeldung.equalshashcode.entities;
+
+public class PrimitiveClass {
+
+ private boolean primitiveBoolean;
+ private int primitiveInt;
+
+ public PrimitiveClass(boolean primitiveBoolean, int primitiveInt) {
+ super();
+ this.primitiveBoolean = primitiveBoolean;
+ this.primitiveInt = primitiveInt;
+ }
+
+ protected boolean isPrimitiveBoolean() {
+ return primitiveBoolean;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + (primitiveBoolean ? 1231 : 1237);
+ result = prime * result + primitiveInt;
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ PrimitiveClass other = (PrimitiveClass) obj;
+ if (primitiveBoolean != other.primitiveBoolean)
+ return false;
+ if (primitiveInt != other.primitiveInt)
+ return false;
+ return true;
+ }
+
+ protected void setPrimitiveBoolean(boolean primitiveBoolean) {
+ this.primitiveBoolean = primitiveBoolean;
+ }
+
+ protected int getPrimitiveInt() {
+ return primitiveInt;
+ }
+
+ protected void setPrimitiveInt(int primitiveInt) {
+ this.primitiveInt = primitiveInt;
+ }
+}
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
new file mode 100644
index 0000000000..1e1423f0b3
--- /dev/null
+++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Rectangle.java
@@ -0,0 +1,58 @@
+package org.baeldung.equalshashcode.entities;
+
+public class Rectangle extends Shape {
+ private double width;
+ private double length;
+
+ public Rectangle(double width, double length) {
+ this.width = width;
+ this.length = length;
+ }
+
+ @Override
+ public double area() {
+ return width * length;
+ }
+
+ @Override
+ public double perimeter() {
+ return 2 * (width + length);
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ long temp;
+ temp = Double.doubleToLongBits(length);
+ result = prime * result + (int) (temp ^ (temp >>> 32));
+ temp = Double.doubleToLongBits(width);
+ result = prime * result + (int) (temp ^ (temp >>> 32));
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Rectangle other = (Rectangle) obj;
+ if (Double.doubleToLongBits(length) != Double.doubleToLongBits(other.length))
+ return false;
+ if (Double.doubleToLongBits(width) != Double.doubleToLongBits(other.width))
+ return false;
+ return true;
+ }
+
+ protected double getWidth() {
+ return width;
+ }
+
+ protected double getLength() {
+ return length;
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java
new file mode 100644
index 0000000000..3bfc81da8f
--- /dev/null
+++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Shape.java
@@ -0,0 +1,7 @@
+package org.baeldung.equalshashcode.entities;
+
+public abstract class Shape {
+ public abstract double area();
+
+ public abstract double perimeter();
+}
diff --git a/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java
new file mode 100644
index 0000000000..f11e34f0ba
--- /dev/null
+++ b/core-java/src/main/java/org/baeldung/equalshashcode/entities/Square.java
@@ -0,0 +1,58 @@
+package org.baeldung.equalshashcode.entities;
+
+import java.awt.Color;
+
+public class Square extends Rectangle {
+
+ Color color;
+
+ public Square(double width, Color color) {
+ super(width, width);
+ this.color = color;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = super.hashCode();
+ result = prime * result + ((color == null) ? 0 : color.hashCode());
+ return result;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (!super.equals(obj)) {
+ return false;
+ }
+ if (!(obj instanceof Square)) {
+ return false;
+ }
+ Square other = (Square) obj;
+ if (color == null) {
+ if (other.color != null) {
+ return false;
+ }
+ } else if (!color.equals(other.color)) {
+ return false;
+ }
+ return true;
+ }
+
+ protected Color getColor() {
+ return color;
+ }
+
+ protected void setColor(Color color) {
+ this.color = color;
+ }
+
+}
diff --git a/core-java/src/main/resources/targetFile.tmp b/core-java/src/main/resources/targetFile.tmp
deleted file mode 100644
index 20f137b416..0000000000
--- a/core-java/src/main/resources/targetFile.tmp
+++ /dev/null
@@ -1,2 +0,0 @@
-line 1
-a second line
\ No newline at end of file
diff --git a/core-java/src/main/webapp/WEB-INF/api-servlet.xml b/core-java/src/main/webapp/WEB-INF/api-servlet.xml
deleted file mode 100644
index 4c74be8912..0000000000
--- a/core-java/src/main/webapp/WEB-INF/api-servlet.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/core-java/src/main/webapp/WEB-INF/web.xml b/core-java/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 935beae648..0000000000
--- a/core-java/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-
-
-
- Spring MVC Application
-
-
-
- contextClass
-
- org.springframework.web.context.support.AnnotationConfigWebApplicationContext
-
-
-
- contextConfigLocation
- org.baeldung.config
-
-
-
- org.springframework.web.context.ContextLoaderListener
-
-
-
-
- api
- org.springframework.web.servlet.DispatcherServlet
- 1
-
-
- api
- /
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java
new file mode 100644
index 0000000000..a12a2f205f
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionTest.java
@@ -0,0 +1,326 @@
+package com.baeldung.java.reflection;
+
+import org.junit.Test;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.Arrays;
+import java.util.List;
+import java.util.ArrayList;
+import static org.junit.Assert.*;
+
+public class ReflectionTest {
+
+ @Test
+ public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() {
+ Object person = new Person();
+ Field[] fields = person.getClass().getDeclaredFields();
+
+ List actualFieldNames = getFieldNames(fields);
+
+ assertTrue(Arrays.asList("name", "age")
+ .containsAll(actualFieldNames));
+ }
+
+ @Test
+ public void givenObject_whenGetsClassName_thenCorrect() {
+ Object goat = new Goat("goat");
+ Class> clazz = goat.getClass();
+
+ assertEquals("Goat", clazz.getSimpleName());
+ assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
+ assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
+ }
+
+ @Test
+ public void givenClassName_whenCreatesObject_thenCorrect()
+ throws ClassNotFoundException {
+ Class> clazz = Class.forName("com.baeldung.java.reflection.Goat");
+
+ assertEquals("Goat", clazz.getSimpleName());
+ assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
+ assertEquals("com.baeldung.java.reflection.Goat", clazz.getCanonicalName());
+ }
+
+ @Test
+ public void givenClass_whenRecognisesModifiers_thenCorrect()
+ throws ClassNotFoundException {
+ Class> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
+ Class> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
+ int goatMods = goatClass.getModifiers();
+ int animalMods = animalClass.getModifiers();
+
+ assertTrue(Modifier.isPublic(goatMods));
+ assertTrue(Modifier.isAbstract(animalMods));
+ assertTrue(Modifier.isPublic(animalMods));
+ }
+
+ @Test
+ public void givenClass_whenGetsPackageInfo_thenCorrect() {
+ Goat goat = new Goat("goat");
+ Class> goatClass = goat.getClass();
+ Package pkg = goatClass.getPackage();
+
+ assertEquals("com.baeldung.java.reflection", pkg.getName());
+ }
+
+ @Test
+ public void givenClass_whenGetsSuperClass_thenCorrect() {
+ Goat goat = new Goat("goat");
+ String str = "any string";
+
+ Class> goatClass = goat.getClass();
+ Class> goatSuperClass = goatClass.getSuperclass();
+
+ assertEquals("Animal", goatSuperClass.getSimpleName());
+ assertEquals("Object", str.getClass().getSuperclass().getSimpleName());
+
+ }
+
+ @Test
+ public void givenClass_whenGetsImplementedInterfaces_thenCorrect()
+ throws ClassNotFoundException {
+ Class> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
+ Class> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
+ Class>[] goatInterfaces = goatClass.getInterfaces();
+ Class>[] animalInterfaces = animalClass.getInterfaces();
+
+ assertEquals(1, goatInterfaces.length);
+ assertEquals(1, animalInterfaces.length);
+ assertEquals("Locomotion", goatInterfaces[0].getSimpleName());
+ assertEquals("Eating", animalInterfaces[0].getSimpleName());
+ }
+
+ @Test
+ public void givenClass_whenGetsConstructor_thenCorrect()
+ throws ClassNotFoundException {
+ Class> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
+ Constructor>[] constructors = goatClass.getConstructors();
+
+ assertEquals(1, constructors.length);
+ assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName());
+ }
+
+ @Test
+ public void givenClass_whenGetsFields_thenCorrect()
+ throws ClassNotFoundException {
+ Class> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
+ Field[] fields = animalClass.getDeclaredFields();
+
+ List actualFields = getFieldNames(fields);
+
+ assertEquals(2, actualFields.size());
+ assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY")));
+ }
+
+ @Test
+ public void givenClass_whenGetsMethods_thenCorrect()
+ throws ClassNotFoundException {
+ Class> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
+ Method[] methods = animalClass.getDeclaredMethods();
+ List actualMethods = getMethodNames(methods);
+
+ assertEquals(4, actualMethods.size());
+ assertTrue(actualMethods.containsAll(Arrays.asList("getName",
+ "setName", "getSound")));
+ }
+
+ @Test
+ public void givenClass_whenGetsAllConstructors_thenCorrect()
+ throws ClassNotFoundException {
+ Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ Constructor>[] constructors = birdClass.getConstructors();
+
+ assertEquals(3, constructors.length);
+ }
+
+ @Test
+ public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect()
+ throws Exception {
+ Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ Constructor> cons1 = birdClass.getConstructor();
+ Constructor> cons2 = birdClass.getConstructor(String.class);
+ Constructor> cons3 = birdClass.getConstructor(String.class,
+ boolean.class);
+ }
+
+ @Test
+ public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect()
+ throws Exception {
+ Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+
+ Constructor> cons1 = birdClass.getConstructor();
+ Constructor> cons2 = birdClass.getConstructor(String.class);
+ Constructor> cons3 = birdClass.getConstructor(String.class,
+ boolean.class);
+
+ Bird bird1 = (Bird) cons1.newInstance();
+ Bird bird2 = (Bird) cons2.newInstance("Weaver bird");
+ Bird bird3 = (Bird) cons3.newInstance("dove", true);
+
+ assertEquals("bird", bird1.getName());
+ assertEquals("Weaver bird", bird2.getName());
+ assertEquals("dove", bird3.getName());
+ assertFalse(bird1.walks());
+ assertTrue(bird3.walks());
+ }
+
+ @Test
+ public void givenClass_whenGetsPublicFields_thenCorrect()
+ throws ClassNotFoundException {
+ Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ Field[] fields = birdClass.getFields();
+ assertEquals(1, fields.length);
+ assertEquals("CATEGORY", fields[0].getName());
+
+ }
+
+ @Test
+ public void givenClass_whenGetsPublicFieldByName_thenCorrect()
+ throws Exception {
+ Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ Field field = birdClass.getField("CATEGORY");
+ assertEquals("CATEGORY", field.getName());
+
+ }
+
+ @Test
+ public void givenClass_whenGetsDeclaredFields_thenCorrect()
+ throws ClassNotFoundException {
+ Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ Field[] fields = birdClass.getDeclaredFields();
+ assertEquals(1, fields.length);
+ assertEquals("walks", fields[0].getName());
+ }
+
+ @Test
+ public void givenClass_whenGetsFieldsByName_thenCorrect()
+ throws Exception {
+ Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ Field field = birdClass.getDeclaredField("walks");
+ assertEquals("walks", field.getName());
+
+ }
+
+ @Test
+ public void givenClassField_whenGetsType_thenCorrect()
+ throws Exception {
+ Field field = Class.forName("com.baeldung.java.reflection.Bird")
+ .getDeclaredField("walks");
+ Class> fieldClass = field.getType();
+ assertEquals("boolean", fieldClass.getSimpleName());
+ }
+
+ @Test
+ public void givenClassField_whenSetsAndGetsValue_thenCorrect()
+ throws Exception {
+ Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ Bird bird = (Bird) birdClass.newInstance();
+ Field field = birdClass.getDeclaredField("walks");
+ field.setAccessible(true);
+
+ assertFalse(field.getBoolean(bird));
+ assertFalse(bird.walks());
+
+ field.set(bird, true);
+
+ assertTrue(field.getBoolean(bird));
+ assertTrue(bird.walks());
+
+ }
+
+ @Test
+ public void givenClassField_whenGetsAndSetsWithNull_thenCorrect()
+ throws Exception {
+ Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ Field field = birdClass.getField("CATEGORY");
+ field.setAccessible(true);
+
+ assertEquals("domestic", field.get(null));
+ }
+
+ @Test
+ public void givenClass_whenGetsAllPublicMethods_thenCorrect()
+ throws ClassNotFoundException {
+ Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ Method[] methods = birdClass.getMethods();
+ List methodNames = getMethodNames(methods);
+
+ assertTrue(methodNames.containsAll(Arrays
+ .asList("equals", "notifyAll", "hashCode",
+ "walks", "eats", "toString")));
+
+ }
+
+ @Test
+ public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect()
+ throws ClassNotFoundException {
+ Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ List actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
+
+ List expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats");
+
+ assertEquals(expectedMethodNames.size(), actualMethodNames.size());
+ assertTrue(expectedMethodNames.containsAll(actualMethodNames));
+ assertTrue(actualMethodNames.containsAll(expectedMethodNames));
+
+ }
+
+ @Test
+ public void givenMethodName_whenGetsMethod_thenCorrect()
+ throws Exception {
+ Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ Method walksMethod = birdClass.getDeclaredMethod("walks");
+ Method setWalksMethod = birdClass.getDeclaredMethod("setWalks",
+ boolean.class);
+
+ assertFalse(walksMethod.isAccessible());
+ assertFalse(setWalksMethod.isAccessible());
+
+ walksMethod.setAccessible(true);
+ setWalksMethod.setAccessible(true);
+
+ assertTrue(walksMethod.isAccessible());
+ assertTrue(setWalksMethod.isAccessible());
+
+ }
+
+ @Test
+ public void givenMethod_whenInvokes_thenCorrect()
+ throws Exception {
+ Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ Bird bird = (Bird) birdClass.newInstance();
+ Method setWalksMethod = birdClass.getDeclaredMethod("setWalks",
+ boolean.class);
+ Method walksMethod = birdClass.getDeclaredMethod("walks");
+ boolean walks = (boolean) walksMethod.invoke(bird);
+
+ assertFalse(walks);
+ assertFalse(bird.walks());
+
+ setWalksMethod.invoke(bird, true);
+ boolean walks2 = (boolean) walksMethod.invoke(bird);
+
+ assertTrue(walks2);
+ assertTrue(bird.walks());
+
+ }
+
+ private static List getFieldNames(Field[] fields) {
+ List fieldNames = new ArrayList<>();
+ for (Field field : fields)
+ fieldNames.add(field.getName());
+ return fieldNames;
+
+ }
+
+ private static List