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/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
+
+
+
+
+
+
+
+
\ 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
+
+
+
+
+
+
+
+
\ 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..2b052803e6
--- /dev/null
+++ b/annotations/readme.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Java Annotation Processing and Creating a Builder](http://www.baeldung.com/java-annotation-processing-builder)
diff --git a/apache-cxf/cxf-introduction/README.md b/apache-cxf/cxf-introduction/README.md
new file mode 100644
index 0000000000..9a076524b7
--- /dev/null
+++ b/apache-cxf/cxf-introduction/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf)
diff --git a/apache-cxf/cxf-introduction/pom.xml b/apache-cxf/cxf-introduction/pom.xml
index 232a4f0089..0902bd690e 100644
--- a/apache-cxf/cxf-introduction/pom.xml
+++ b/apache-cxf/cxf-introduction/pom.xml
@@ -11,6 +11,7 @@
3.1.6
+ 2.19.1
@@ -26,7 +27,7 @@
2.19.1
- **/StudentTest.java
+ **/*LiveTest.java
@@ -44,4 +45,5 @@
${cxf.version}
+
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/StudentLiveTest.java
similarity index 65%
rename from apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentTest.java
rename to apache-cxf/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java
index e1e5b60ec3..60fc0a10e7 100644
--- 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/StudentLiveTest.java
@@ -2,20 +2,16 @@ 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;
+import org.junit.Before;
+import org.junit.Test;
-public class StudentTest {
+public class StudentLiveTest {
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");
@@ -25,7 +21,7 @@ public class StudentTest {
{
service = Service.create(SERVICE_NAME);
- String endpointAddress = "http://localhost:8080/baeldung";
+ final String endpointAddress = "http://localhost:8080/baeldung";
service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);
}
@@ -37,28 +33,28 @@ public class StudentTest {
@Test
public void whenUsingHelloMethod_thenCorrect() {
- String endpointResponse = baeldungProxy.hello("Baeldung");
- String localResponse = baeldungImpl.hello("Baeldung");
+ final String endpointResponse = baeldungProxy.hello("Baeldung");
+ final 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);
+ final Student student = new StudentImpl("John Doe");
+ final String endpointResponse = baeldungProxy.helloStudent(student);
+ final String localResponse = baeldungImpl.helloStudent(student);
assertEquals(localResponse, endpointResponse);
}
@Test
public void usingGetStudentsMethod_thenCorrect() {
- Student student1 = new StudentImpl("Adam");
+ final Student student1 = new StudentImpl("Adam");
baeldungProxy.helloStudent(student1);
- Student student2 = new StudentImpl("Eve");
+ final Student student2 = new StudentImpl("Eve");
baeldungProxy.helloStudent(student2);
-
- Map students = baeldungProxy.getStudents();
+
+ final Map students = baeldungProxy.getStudents();
assertEquals("Adam", students.get(1).getName());
assertEquals("Eve", students.get(2).getName());
}
diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml
new file mode 100644
index 0000000000..b3a81aef82
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml
@@ -0,0 +1,55 @@
+
+
+
+ 4.0.0
+ cxf-jaxrs-implementation
+
+ com.baeldung
+ apache-cxf
+ 0.0.1-SNAPSHOT
+
+
+ UTF-8
+ 3.1.7
+ 4.5.2
+ 2.19.1
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+
+ com.baeldung.cxf.jaxrs.implementation.RestfulServer
+
+
+
+ maven-surefire-plugin
+ 2.19.1
+
+
+ **/*LiveTest.java
+
+
+
+
+
+
+
+ org.apache.cxf
+ cxf-rt-frontend-jaxrs
+ ${cxf.version}
+
+
+ org.apache.cxf
+ cxf-rt-transports-http-jetty
+ ${cxf.version}
+
+
+ org.apache.httpcomponents
+ httpclient
+ ${httpclient.version}
+
+
+
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java
new file mode 100644
index 0000000000..dba9b9c661
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java
@@ -0,0 +1,86 @@
+package com.baeldung.cxf.jaxrs.implementation;
+
+import javax.ws.rs.*;
+import javax.ws.rs.core.Response;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@XmlRootElement(name = "Course")
+public class Course {
+ private int id;
+ private String name;
+ private List students = new ArrayList<>();
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public List getStudents() {
+ return students;
+ }
+
+ public void setStudents(List students) {
+ this.students = students;
+ }
+
+ @GET
+ @Path("{studentId}")
+ public Student getStudent(@PathParam("studentId") int studentId) {
+ return findById(studentId);
+ }
+
+ @POST
+ public Response createStudent(Student student) {
+ for (Student element : students) {
+ if (element.getId() == student.getId()) {
+ return Response.status(Response.Status.CONFLICT).build();
+ }
+ }
+ students.add(student);
+ return Response.ok(student).build();
+ }
+
+ @DELETE
+ @Path("{studentId}")
+ public Response deleteStudent(@PathParam("studentId") int studentId) {
+ Student student = findById(studentId);
+ if (student == null) {
+ return Response.status(Response.Status.NOT_FOUND).build();
+ }
+ students.remove(student);
+ return Response.ok().build();
+ }
+
+ private Student findById(int id) {
+ for (Student student : students) {
+ if (student.getId() == id) {
+ return student;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public int hashCode() {
+ return id + name.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return (obj instanceof Course) && (id == ((Course) obj).getId()) && (name.equals(((Course) obj).getName()));
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java
new file mode 100644
index 0000000000..a2fd6be435
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java
@@ -0,0 +1,72 @@
+package com.baeldung.cxf.jaxrs.implementation;
+
+import javax.ws.rs.*;
+import javax.ws.rs.core.Response;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Path("baeldung")
+@Produces("text/xml")
+public class CourseRepository {
+ private Map courses = new HashMap<>();
+
+ {
+ Student student1 = new Student();
+ Student student2 = new Student();
+ student1.setId(1);
+ student1.setName("Student A");
+ student2.setId(2);
+ student2.setName("Student B");
+
+ List course1Students = new ArrayList<>();
+ course1Students.add(student1);
+ course1Students.add(student2);
+
+ Course course1 = new Course();
+ Course course2 = new Course();
+ course1.setId(1);
+ course1.setName("REST with Spring");
+ course1.setStudents(course1Students);
+ course2.setId(2);
+ course2.setName("Learn Spring Security");
+
+ courses.put(1, course1);
+ courses.put(2, course2);
+ }
+
+ @GET
+ @Path("courses/{courseId}")
+ public Course getCourse(@PathParam("courseId") int courseId) {
+ return findById(courseId);
+ }
+
+ @PUT
+ @Path("courses/{courseId}")
+ public Response updateCourse(@PathParam("courseId") int courseId, Course course) {
+ Course existingCourse = findById(courseId);
+ if (existingCourse == null) {
+ return Response.status(Response.Status.NOT_FOUND).build();
+ }
+ if (existingCourse.equals(course)) {
+ return Response.notModified().build();
+ }
+ courses.put(courseId, course);
+ return Response.ok().build();
+ }
+
+ @Path("courses/{courseId}/students")
+ public Course pathToStudent(@PathParam("courseId") int courseId) {
+ return findById(courseId);
+ }
+
+ private Course findById(int id) {
+ for (Map.Entry course : courses.entrySet()) {
+ if (course.getKey() == id) {
+ return course.getValue();
+ }
+ }
+ return null;
+ }
+}
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java
new file mode 100644
index 0000000000..d3ed2eb70e
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/RestfulServer.java
@@ -0,0 +1,21 @@
+package com.baeldung.cxf.jaxrs.implementation;
+
+import org.apache.cxf.endpoint.Server;
+import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
+import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
+
+public class RestfulServer {
+ public static void main(String args[]) throws Exception {
+ JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
+ factoryBean.setResourceClasses(CourseRepository.class);
+ factoryBean.setResourceProvider(new SingletonResourceProvider(new CourseRepository()));
+ factoryBean.setAddress("http://localhost:8080/");
+ Server server = factoryBean.create();
+
+ System.out.println("Server ready...");
+ Thread.sleep(60 * 1000);
+ System.out.println("Server exiting");
+ server.destroy();
+ System.exit(0);
+ }
+}
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java
new file mode 100644
index 0000000000..bd3dad0f5e
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java
@@ -0,0 +1,35 @@
+package com.baeldung.cxf.jaxrs.implementation;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "Student")
+public class Student {
+ private int id;
+ private String name;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public int hashCode() {
+ return id + name.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ return (obj instanceof Student) && (id == ((Student) obj).getId()) && (name.equals(((Student) obj).getName()));
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/changed_course.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/changed_course.xml
new file mode 100644
index 0000000000..097cf2ce58
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/changed_course.xml
@@ -0,0 +1,4 @@
+
+ 2
+ Apache CXF Support for RESTful
+
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml
new file mode 100644
index 0000000000..7d083dbdc9
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/conflict_student.xml
@@ -0,0 +1,4 @@
+
+ 2
+ Student B
+
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/created_student.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/created_student.xml
new file mode 100644
index 0000000000..068c9dae4b
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/created_student.xml
@@ -0,0 +1,4 @@
+
+ 3
+ Student C
+
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/non_existent_course.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/non_existent_course.xml
new file mode 100644
index 0000000000..465c337745
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/non_existent_course.xml
@@ -0,0 +1,4 @@
+
+ 3
+ Apache CXF Support for RESTful
+
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/unchanged_course.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/unchanged_course.xml
new file mode 100644
index 0000000000..5936fdc094
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/unchanged_course.xml
@@ -0,0 +1,4 @@
+
+ 1
+ REST with Spring
+
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java
new file mode 100644
index 0000000000..29c34ae16b
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java
@@ -0,0 +1,130 @@
+package com.baeldung.cxf.jaxrs.implementation;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+
+import javax.xml.bind.JAXB;
+
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpDelete;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.entity.InputStreamEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class ServiceLiveTest {
+ private static final String BASE_URL = "http://localhost:8080/baeldung/courses/";
+ private static CloseableHttpClient client;
+
+ @BeforeClass
+ public static void createClient() {
+ client = HttpClients.createDefault();
+ }
+
+ @AfterClass
+ public static void closeClient() throws IOException {
+ client.close();
+ }
+
+ @Test
+ public void whenUpdateNonExistentCourse_thenReceiveNotFoundResponse() throws IOException {
+ final HttpPut httpPut = new HttpPut(BASE_URL + "3");
+ final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("non_existent_course.xml");
+ httpPut.setEntity(new InputStreamEntity(resourceStream));
+ httpPut.setHeader("Content-Type", "text/xml");
+
+ final HttpResponse response = client.execute(httpPut);
+ assertEquals(404, response.getStatusLine().getStatusCode());
+ }
+
+ @Test
+ public void whenUpdateUnchangedCourse_thenReceiveNotModifiedResponse() throws IOException {
+ final HttpPut httpPut = new HttpPut(BASE_URL + "1");
+ final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("unchanged_course.xml");
+ httpPut.setEntity(new InputStreamEntity(resourceStream));
+ httpPut.setHeader("Content-Type", "text/xml");
+
+ final HttpResponse response = client.execute(httpPut);
+ assertEquals(304, response.getStatusLine().getStatusCode());
+ }
+
+ @Test
+ public void whenUpdateValidCourse_thenReceiveOKResponse() throws IOException {
+ final HttpPut httpPut = new HttpPut(BASE_URL + "2");
+ final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("changed_course.xml");
+ httpPut.setEntity(new InputStreamEntity(resourceStream));
+ httpPut.setHeader("Content-Type", "text/xml");
+
+ final HttpResponse response = client.execute(httpPut);
+ assertEquals(200, response.getStatusLine().getStatusCode());
+
+ final Course course = getCourse(2);
+ assertEquals(2, course.getId());
+ assertEquals("Apache CXF Support for RESTful", course.getName());
+ }
+
+ @Test
+ public void whenCreateConflictStudent_thenReceiveConflictResponse() throws IOException {
+ final HttpPost httpPost = new HttpPost(BASE_URL + "1/students");
+ final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("conflict_student.xml");
+ httpPost.setEntity(new InputStreamEntity(resourceStream));
+ httpPost.setHeader("Content-Type", "text/xml");
+
+ final HttpResponse response = client.execute(httpPost);
+ assertEquals(409, response.getStatusLine().getStatusCode());
+ }
+
+ @Test
+ public void whenCreateValidStudent_thenReceiveOKResponse() throws IOException {
+ final HttpPost httpPost = new HttpPost(BASE_URL + "2/students");
+ final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("created_student.xml");
+ httpPost.setEntity(new InputStreamEntity(resourceStream));
+ httpPost.setHeader("Content-Type", "text/xml");
+
+ final HttpResponse response = client.execute(httpPost);
+ assertEquals(200, response.getStatusLine().getStatusCode());
+
+ final Student student = getStudent(2, 3);
+ assertEquals(3, student.getId());
+ assertEquals("Student C", student.getName());
+ }
+
+ @Test
+ public void whenDeleteInvalidStudent_thenReceiveNotFoundResponse() throws IOException {
+ final HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/3");
+ final HttpResponse response = client.execute(httpDelete);
+ assertEquals(404, response.getStatusLine().getStatusCode());
+ }
+
+ @Test
+ public void whenDeleteValidStudent_thenReceiveOKResponse() throws IOException {
+ final HttpDelete httpDelete = new HttpDelete(BASE_URL + "1/students/1");
+ final HttpResponse response = client.execute(httpDelete);
+ assertEquals(200, response.getStatusLine().getStatusCode());
+
+ final Course course = getCourse(1);
+ assertEquals(1, course.getStudents().size());
+ assertEquals(2, course.getStudents().get(0).getId());
+ assertEquals("Student B", course.getStudents().get(0).getName());
+ }
+
+ private Course getCourse(int courseOrder) throws IOException {
+ final URL url = new URL(BASE_URL + courseOrder);
+ final InputStream input = url.openStream();
+ return JAXB.unmarshal(new InputStreamReader(input), Course.class);
+ }
+
+ private Student getStudent(int courseOrder, int studentOrder) throws IOException {
+ final URL url = new URL(BASE_URL + courseOrder + "/students/" + studentOrder);
+ final InputStream input = url.openStream();
+ return JAXB.unmarshal(new InputStreamReader(input), Student.class);
+ }
+}
\ No newline at end of file
diff --git a/apache-cxf/cxf-spring/pom.xml b/apache-cxf/cxf-spring/pom.xml
index 85e68300f0..8f1dee965a 100644
--- a/apache-cxf/cxf-spring/pom.xml
+++ b/apache-cxf/cxf-spring/pom.xml
@@ -51,7 +51,7 @@
${surefire.version}
- StudentTest.java
+ **/*LiveTest.java
@@ -60,7 +60,7 @@
- integration
+ live
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/StudentLiveTest.java
similarity index 97%
rename from apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentTest.java
rename to apache-cxf/cxf-spring/src/test/java/com/baeldung/cxf/spring/StudentLiveTest.java
index 7466944e04..80a8f6c3b8 100644
--- 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/StudentLiveTest.java
@@ -6,7 +6,7 @@ import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
-public class StudentTest {
+public class StudentLiveTest {
private ApplicationContext context = new AnnotationConfigApplicationContext(ClientConfiguration.class);
private Baeldung baeldungProxy = (Baeldung) context.getBean("client");
diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml
index 022fc59f9b..af7949bb6c 100644
--- a/apache-cxf/pom.xml
+++ b/apache-cxf/pom.xml
@@ -8,6 +8,7 @@
cxf-introduction
cxf-spring
+ cxf-jaxrs-implementation
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/pom.xml b/apache-fop/pom.xml
index 658d567a90..949843a47e 100644
--- a/apache-fop/pom.xml
+++ b/apache-fop/pom.xml
@@ -97,6 +97,14 @@
8.0.2
+
+ org.dbdoclet
+ herold
+ 6.1.0
+ system
+ ${basedir}/src/test/resources/jars/herold.jar
+
+
net.sf.jtidy
jtidy
@@ -132,7 +140,8 @@
${maven-surefire-plugin.version}
- **/*IntegrationTest.java
+ **/*IntegrationTest.java
+ **/*LiveTest.java
@@ -141,6 +150,42 @@
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*ManualTest.java
+
+
+ **/*IntegrationTest.java
+ **/*LiveTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
+
4.3.11.Final
diff --git a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLTest.java b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java
similarity index 98%
rename from apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLTest.java
rename to apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java
index bde6868b39..99487c8fdf 100644
--- a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLTest.java
+++ b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPConvertHTMLIntegrationTest.java
@@ -25,7 +25,7 @@ import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.tidy.Tidy;
-public class ApacheFOPConvertHTMLTest {
+public class ApacheFOPConvertHTMLIntegrationTest {
private String inputFile = "src/test/resources/input.html";
private String style = "src/test/resources/xhtml2fo.xsl";
private String style1 = "src/test/resources/docbook-xsl/fo/docbook.xsl";
diff --git a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldTest.java b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java
similarity index 99%
rename from apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldTest.java
rename to apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java
index 5e3c2c472b..9e71cd9c16 100644
--- a/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldTest.java
+++ b/apache-fop/src/test/java/org/baeldung/java/ApacheFOPHeroldLiveTest.java
@@ -30,7 +30,7 @@ import org.dbdoclet.trafo.script.Script;
import org.junit.Test;
import org.w3c.dom.Document;
-public class ApacheFOPHeroldTest {
+public class ApacheFOPHeroldLiveTest {
private String[] inputUrls = {// @formatter:off
"http://www.baeldung.com/2011/10/20/bootstraping-a-web-application-with-spring-3-1-and-java-based-configuration-part-1/",
"http://www.baeldung.com/2011/10/25/building-a-restful-web-service-with-spring-3-1-and-java-based-configuration-part-2/",
diff --git a/assertj/README.md b/assertj/README.md
new file mode 100644
index 0000000000..86eff05057
--- /dev/null
+++ b/assertj/README.md
@@ -0,0 +1,3 @@
+### Relevant Articles:
+- [AssertJ’s Java 8 Features](http://www.baeldung.com/assertJ-java-8-features)
+- [AssertJ for Guava](http://www.baeldung.com/assertJ-for-guava)
diff --git a/assertj/pom.xml b/assertj/pom.xml
index 421afd40a5..df55ebba4b 100644
--- a/assertj/pom.xml
+++ b/assertj/pom.xml
@@ -1,7 +1,6 @@
-
+
4.0.0
com.baeldung
@@ -9,11 +8,18 @@
1.0.0-SNAPSHOT
+
com.google.guava
guava
- 19.0
+ ${guava.version}
+
+ org.assertj
+ assertj-guava
+ 3.0.0
+
+
junit
junit
@@ -26,11 +32,7 @@
3.5.1
test
-
- org.assertj
- assertj-guava
- 3.0.0
-
+
@@ -46,4 +48,9 @@
+
+
+ 19.0
+
+
\ No newline at end of file
diff --git a/autovalue-tutorial/pom.xml b/autovalue-tutorial/pom.xml
deleted file mode 100644
index 37d595dce1..0000000000
--- a/autovalue-tutorial/pom.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-
- 4.0.0
- com.baeldung
- autovalue-tutorial
- 1.0
- AutoValue
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- 3.3
-
-
- 7
-
-
-
-
-
-
- com.google.auto.value
- auto-value
- 1.2
-
-
-
- junit
- junit
- 4.3
- test
-
-
-
-
diff --git a/autovalue/README.md b/autovalue/README.md
new file mode 100644
index 0000000000..2385e82847
--- /dev/null
+++ b/autovalue/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Introduction to AutoValue](http://www.baeldung.com/introduction-to-autovalue)
diff --git a/autovalue/pom.xml b/autovalue/pom.xml
new file mode 100644
index 0000000000..d1f8e825fc
--- /dev/null
+++ b/autovalue/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
+ 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/src/main/java/com/baeldung/autovalue/AutoValueMoney.java
similarity index 100%
rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoney.java
rename to autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoney.java
diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java b/autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java
similarity index 100%
rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java
rename to autovalue/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java
diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/Foo.java b/autovalue/src/main/java/com/baeldung/autovalue/Foo.java
similarity index 100%
rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/Foo.java
rename to autovalue/src/main/java/com/baeldung/autovalue/Foo.java
diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/ImmutableMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java
similarity index 100%
rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/ImmutableMoney.java
rename to autovalue/src/main/java/com/baeldung/autovalue/ImmutableMoney.java
diff --git a/autovalue-tutorial/src/main/java/com/baeldung/autovalue/MutableMoney.java b/autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java
similarity index 100%
rename from autovalue-tutorial/src/main/java/com/baeldung/autovalue/MutableMoney.java
rename to autovalue/src/main/java/com/baeldung/autovalue/MutableMoney.java
diff --git a/autovalue-tutorial/src/test/java/com/baeldung/autovalue/MoneyTest.java b/autovalue/src/test/java/com/baeldung/autovalue/MoneyTest.java
similarity index 100%
rename from autovalue-tutorial/src/test/java/com/baeldung/autovalue/MoneyTest.java
rename to autovalue/src/test/java/com/baeldung/autovalue/MoneyTest.java
diff --git a/cdi/README.md b/cdi/README.md
new file mode 100644
index 0000000000..a27c35772a
--- /dev/null
+++ b/cdi/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [CDI Interceptor vs Spring AspectJ](http://www.baeldung.com/cdi-interceptor-vs-spring-aspectj)
diff --git a/cdi/pom.xml b/cdi/pom.xml
new file mode 100644
index 0000000000..30dd167fa8
--- /dev/null
+++ b/cdi/pom.xml
@@ -0,0 +1,104 @@
+
+
+ 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
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+ **/*IntegrationTest.java
+ **/*LiveTest.java
+
+
+
+
+
+
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*LiveTest.java
+
+
+ **/*IntegrationTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
+
+ 4.3.1.RELEASE
+ 2.19.1
+
+
+
\ 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/InterceptorIntegrationTest.java b/cdi/src/test/java/com/baeldung/test/InterceptorIntegrationTest.java
new file mode 100644
index 0000000000..cca8cb7495
--- /dev/null
+++ b/cdi/src/test/java/com/baeldung/test/InterceptorIntegrationTest.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 InterceptorIntegrationTest {
+ 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/SpringInterceptorIntegrationTest.java b/cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java
new file mode 100644
index 0000000000..f711b0c8ce
--- /dev/null
+++ b/cdi/src/test/java/com/baeldung/test/SpringInterceptorIntegrationTest.java
@@ -0,0 +1,38 @@
+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 SpringInterceptorIntegrationTest {
+ @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/README.md b/core-java-8/README.md
deleted file mode 100644
index e6bac2a4c9..0000000000
--- a/core-java-8/README.md
+++ /dev/null
@@ -1,14 +0,0 @@
-=========
-
-## Core Java 8 Cookbooks and Examples
-
-### Relevant Articles:
-- [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)
\ No newline at end of file
diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml
deleted file mode 100644
index 63df0e1b95..0000000000
--- a/core-java-8/pom.xml
+++ /dev/null
@@ -1,138 +0,0 @@
-
- 4.0.0
- com.baeldung
- core-java8
- 0.1-SNAPSHOT
-
- core-java8
-
-
-
-
-
-
- commons-io
- commons-io
- 2.4
-
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
-
- org.apache.commons
- commons-collections4
- 4.0
-
-
-
- commons-codec
- commons-codec
- 1.10
-
-
-
- org.apache.commons
- commons-lang3
- 3.3.2
-
-
-
- org.slf4j
- slf4j-api
- ${org.slf4j.version}
-
-
-
-
-
- org.hamcrest
- hamcrest-library
- ${org.hamcrest.version}
- test
-
-
-
- junit
- junit
- ${junit.version}
- test
-
-
-
- org.assertj
- assertj-core
- 3.5.1
- test
-
-
-
- org.mockito
- mockito-core
- ${mockito.version}
- test
-
-
-
-
-
- core-java-8
-
-
- src/main/resources
- true
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
-
- 1.8
-
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
-
-
-
-
-
-
- 1.7.13
- 1.0.13
-
-
- 5.1.3.Final
-
-
- 19.0
- 3.4
-
-
- 1.3
- 4.12
- 1.10.19
-
-
- 3.5.1
- 2.6
- 2.19.1
- 2.7
-
-
-
-
\ No newline at end of file
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
deleted file mode 100644
index 5bc2d9a9eb..0000000000
--- a/core-java-8/src/main/java/com/baeldung/enums/Pizza.java
+++ /dev/null
@@ -1,91 +0,0 @@
-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
deleted file mode 100644
index ed65919387..0000000000
--- a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java
+++ /dev/null
@@ -1,18 +0,0 @@
-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
deleted file mode 100644
index 5ccff5e959..0000000000
--- a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java
+++ /dev/null
@@ -1,22 +0,0 @@
-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/resources/compressed.zip b/core-java-8/src/main/resources/compressed.zip
deleted file mode 100644
index 03f840ae2b..0000000000
Binary files a/core-java-8/src/main/resources/compressed.zip and /dev/null differ
diff --git a/core-java-8/src/main/resources/unzipTest/test1.txt b/core-java-8/src/main/resources/unzipTest/test1.txt
deleted file mode 100644
index c57eff55eb..0000000000
--- a/core-java-8/src/main/resources/unzipTest/test1.txt
+++ /dev/null
@@ -1 +0,0 @@
-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
deleted file mode 100644
index c57eff55eb..0000000000
--- a/core-java-8/src/main/resources/zipTest/test1.txt
+++ /dev/null
@@ -1 +0,0 @@
-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
deleted file mode 100644
index f0fb0f14d1..0000000000
--- a/core-java-8/src/main/resources/zipTest/test2.txt
+++ /dev/null
@@ -1 +0,0 @@
-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
deleted file mode 100644
index 882edb168e..0000000000
--- a/core-java-8/src/main/resources/zipTest/testFolder/test3.txt
+++ /dev/null
@@ -1 +0,0 @@
-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
deleted file mode 100644
index a78c3fadc8..0000000000
--- a/core-java-8/src/main/resources/zipTest/testFolder/test4.txt
+++ /dev/null
@@ -1 +0,0 @@
-My Name is Jane
\ No newline at end of file
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
deleted file mode 100644
index 8af33393be..0000000000
--- a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java
+++ /dev/null
@@ -1,55 +0,0 @@
-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
deleted file mode 100644
index 69a289fd02..0000000000
--- a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java
+++ /dev/null
@@ -1,19 +0,0 @@
-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
deleted file mode 100644
index 7776fad363..0000000000
--- a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java
+++ /dev/null
@@ -1,36 +0,0 @@
-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/UseZonedDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java
deleted file mode 100644
index 5af01ad678..0000000000
--- a/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java
+++ /dev/null
@@ -1,20 +0,0 @@
-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/.gitignore b/core-java-9/.gitignore
similarity index 100%
rename from core-java-8/.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..fbe5f908aa
--- /dev/null
+++ b/core-java-9/README.md
@@ -0,0 +1,5 @@
+=========
+
+## Core Java 9 Examples
+
+[Java 9 New Features](http://www.baeldung.com/new-java-9)
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
+ 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/core-java-8/src/main/java/.gitignore b/core-java-9/src/main/java/.gitignore
similarity index 100%
rename from core-java-8/src/main/java/.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-8/src/main/resources/logback.xml b/core-java-9/src/main/resources/logback.xml
similarity index 100%
rename from core-java-8/src/main/resources/logback.xml
rename to core-java-9/src/main/resources/logback.xml
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..2f44a2336b
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/README.MD
@@ -0,0 +1,2 @@
+### Relevant Artiles:
+- [Filtering a Stream of Optionals in Java](http://www.baeldung.com/java-filter-stream-of-optional)
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/language/stream/StreamFeaturesTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java
new file mode 100644
index 0000000000..a260e84164
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/StreamFeaturesTest.java
@@ -0,0 +1,119 @@
+package com.baeldung.java9.language.stream;
+
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static java.lang.Integer.*;
+import static org.junit.Assert.assertEquals;
+
+public class StreamFeaturesTest {
+
+ public static class TakeAndDropWhileTest {
+
+ public Stream getStreamAfterTakeWhileOperation() {
+ return Stream
+ .iterate("", s -> s + "s")
+ .takeWhile(s -> s.length() < 10);
+ }
+
+ public Stream getStreamAfterDropWhileOperation() {
+ return Stream
+ .iterate("", s -> s + "s")
+ .takeWhile(s -> s.length() < 10)
+ .dropWhile(s -> !s.contains("sssss"));
+ }
+
+ @Test
+ public void testTakeWhileOperation() {
+ List list = getStreamAfterTakeWhileOperation().collect(Collectors.toList());
+
+ assertEquals(10, list.size());
+
+ assertEquals("", list.get(0));
+ assertEquals("ss", list.get(2));
+ assertEquals("sssssssss", list.get(list.size() - 1));
+ }
+
+ @Test
+ public void testDropWhileOperation() {
+ List list = getStreamAfterDropWhileOperation().collect(Collectors.toList());
+
+ assertEquals(5, list.size());
+
+ assertEquals("sssss", list.get(0));
+ assertEquals("sssssss", list.get(2));
+ assertEquals("sssssssss", list.get(list.size() - 1));
+ }
+
+ }
+
+ public static class IterateTest {
+
+ private Stream getStream() {
+ return Stream.iterate(0, i -> i < 10, i -> i + 1);
+ }
+
+ @Test
+ public void testIterateOperation() {
+ List list = getStream().collect(Collectors.toList());
+
+ assertEquals(10, list.size());
+
+ assertEquals(valueOf(0), list.get(0));
+ assertEquals(valueOf(5), list.get(5));
+ assertEquals(valueOf(9), list.get(list.size() - 1));
+ }
+
+ }
+
+ public static class OfNullableTest {
+
+ private List collection = Arrays.asList("A", "B", "C");
+ private Map map = new HashMap<>() {{
+ put("A", 10);
+ put("C", 30);
+ }};
+
+ private Stream getStreamWithOfNullable() {
+ return collection.stream()
+ .flatMap(s -> Stream.ofNullable(map.get(s)));
+ }
+
+ private Stream getStream() {
+ return collection.stream()
+ .flatMap(s -> {
+ Integer temp = map.get(s);
+ return temp != null ? Stream.of(temp) : Stream.empty();
+ });
+ }
+
+ private List testOfNullableFrom(Stream stream) {
+ List list = stream.collect(Collectors.toList());
+
+ assertEquals(2, list.size());
+
+ assertEquals(valueOf(10), list.get(0));
+ assertEquals(valueOf(30), list.get(list.size() - 1));
+
+ return list;
+ }
+
+ @Test
+ public void testOfNullable() {
+
+ assertEquals(
+ testOfNullableFrom(getStream()),
+ testOfNullableFrom(getStreamWithOfNullable())
+ );
+
+ }
+
+ }
+
+}
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/core-java-8/src/test/resources/.gitignore b/core-java-9/src/test/resources/.gitignore
similarity index 100%
rename from core-java-8/src/test/resources/.gitignore
rename to core-java-9/src/test/resources/.gitignore
diff --git a/couchbase-sdk-spring-service/src/main/resources/application.properties b/core-java/0.12457740242410742
similarity index 100%
rename from couchbase-sdk-spring-service/src/main/resources/application.properties
rename to core-java/0.12457740242410742
diff --git a/core-java/README.md b/core-java/README.md
index 23fe12465f..49317bf369 100644
--- a/core-java/README.md
+++ b/core-java/README.md
@@ -13,3 +13,27 @@
- [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)
+- [Java – Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer)
+- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
+- [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
+- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
+- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
+- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
+- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
+- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture)
+- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces)
+- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
+- [Random List Element](http://www.baeldung.com/java-random-list-element)
+- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
+- [Java 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)
+- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
+- [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)
+- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
diff --git a/core-java/pom.xml b/core-java/pom.xml
index bc533607e7..8b93e238eb 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -1,205 +1,358 @@
-
- 4.0.0
- com.baeldung
- core-java
- 0.1.0-SNAPSHOT
+
+ 4.0.0
+ com.baeldung
+ core-java
+ 0.1.0-SNAPSHOT
+ jar
- core-java
+ core-java
-
+
-
-
- net.sourceforge.collections
- collections-generic
- 4.01
-
-
- com.google.guava
- guava
- ${guava.version}
-
+
+
+ net.sourceforge.collections
+ collections-generic
+ 4.01
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
-
- org.apache.commons
- commons-collections4
- 4.0
-
+
+ org.apache.commons
+ commons-collections4
+ 4.0
+
-
- commons-io
- commons-io
- 2.4
-
+
+ commons-io
+ commons-io
+ 2.4
+
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
-
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
-
- org.apache.commons
- commons-math3
- 3.3
-
+
+ org.apache.commons
+ commons-math3
+ 3.3
+
-
+
-
+
-
- com.fasterxml.jackson.core
- jackson-databind
- ${jackson.version}
-
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson.version}
+
-
+
-
- org.slf4j
- slf4j-api
- ${org.slf4j.version}
-
-
- ch.qos.logback
- logback-classic
- ${logback.version}
-
-
-
- org.slf4j
- jcl-over-slf4j
- ${org.slf4j.version}
-
-
-
- org.slf4j
- log4j-over-slf4j
- ${org.slf4j.version}
-
+
+ org.slf4j
+ slf4j-api
+ ${org.slf4j.version}
+
+
+ ch.qos.logback
+ logback-classic
+ ${logback.version}
+
+
+
+ org.slf4j
+ jcl-over-slf4j
+ ${org.slf4j.version}
+
+
+
+ org.slf4j
+ log4j-over-slf4j
+ ${org.slf4j.version}
+
-
+
-
- junit
- junit
- ${junit.version}
- test
-
+
+ junit
+ junit
+ ${junit.version}
+ test
+
-
- org.hamcrest
- hamcrest-core
- ${org.hamcrest.version}
- test
-
-
- org.hamcrest
- hamcrest-library
- ${org.hamcrest.version}
- test
-
+
+ org.hamcrest
+ hamcrest-core
+ ${org.hamcrest.version}
+ test
+
+
+ org.hamcrest
+ hamcrest-library
+ ${org.hamcrest.version}
+ test
+
-
- org.assertj
- assertj-core
- ${assertj.version}
- test
-
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
-
- org.testng
- testng
- ${testng.version}
- test
-
+
+ org.testng
+ testng
+ ${testng.version}
+ test
+
-
- org.mockito
- mockito-core
- ${mockito.version}
- test
-
+
+ org.mockito
+ mockito-core
+ ${mockito.version}
+ test
+
-
+
+ commons-codec
+ commons-codec
+ 1.10
+
-
- core-java
-
-
- src/main/resources
- true
-
-
+
-
+
+ core-java
+
+
+ src/main/resources
+ true
+
+
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
-
- 1.8
-
-
+
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
- **/*IntegrationTest.java
-
-
-
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ 1.8
+
+
-
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+ **/*IntegrationTest.java
+ **/*LongRunningUnitTest.java
+ **/*ManualTest.java
+
+
+
-
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+
+
+ copy-dependencies
+ prepare-package
+
+ copy-dependencies
+
+
+ ${project.build.directory}/libs
+
+
+
+
-
-
- 4.3.11.Final
- 5.1.38
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+
+
+
+ true
+ libs/
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+
-
- 2.7.2
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+
+
+ package
+
+ single
+
+
+
+
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+ jar-with-dependencies
+
+
+
+
+
-
- 1.7.13
- 1.1.3
+
+ org.apache.maven.plugins
+ maven-shade-plugin
+
+
+
+ shade
+
+
+ true
+
+
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+
+
+
-
- 5.1.3.Final
+
+ com.jolira
+ onejar-maven-plugin
+
+
+
+ org.baeldung.executable.ExecutableMavenJar
+ true
+ ${project.build.finalName}-onejar.${project.packaging}
+
+
+ one-jar
+
+
+
+
-
- 19.0
- 3.4
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+ repackage
+
+
+ spring-boot
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+
+
+
-
- 1.3
- 4.12
- 1.10.19
- 6.8
- 3.5.1
+
+
+
+
+ integration
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ integration-test
+
+ test
+
+
+
+ **/*ManualTest.java
+
+
+ **/*IntegrationTest.java
+
+
+
+
+
+
+ json
+
+
+
+
+
+
+
- 4.4.1
- 4.5
+
+
+ 4.3.11.Final
+ 5.1.38
- 2.9.0
+
+ 2.7.8
-
- 3.5.1
- 2.6
- 2.19.1
- 2.7
- 1.4.18
+
+ 1.7.13
+ 1.1.3
-
+
+ 5.1.3.Final
+
+
+ 19.0
+ 3.4
+
+
+ 1.3
+ 4.12
+ 1.10.19
+ 6.8
+ 3.5.1
+
+ 4.4.1
+ 4.5
+
+ 2.9.0
+
+
+ 3.5.1
+ 2.6
+ 2.19.1
+ 2.7
+ 1.4.18
+
+
\ No newline at end of file
diff --git a/spring-security-rest-custom/.gitignore b/core-java/src/main/java/com/baeldung/.gitignore
similarity index 100%
rename from spring-security-rest-custom/.gitignore
rename to core-java/src/main/java/com/baeldung/.gitignore
diff --git a/core-java-8/src/main/java/com/baeldung/Adder.java b/core-java/src/main/java/com/baeldung/Adder.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/Adder.java
rename to core-java/src/main/java/com/baeldung/Adder.java
diff --git a/core-java-8/src/main/java/com/baeldung/AdderImpl.java b/core-java/src/main/java/com/baeldung/AdderImpl.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/AdderImpl.java
rename to core-java/src/main/java/com/baeldung/AdderImpl.java
diff --git a/core-java-8/src/main/java/com/baeldung/Bar.java b/core-java/src/main/java/com/baeldung/Bar.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/Bar.java
rename to core-java/src/main/java/com/baeldung/Bar.java
diff --git a/core-java-8/src/main/java/com/baeldung/Baz.java b/core-java/src/main/java/com/baeldung/Baz.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/Baz.java
rename to core-java/src/main/java/com/baeldung/Baz.java
diff --git a/core-java-8/src/main/java/com/baeldung/Foo.java b/core-java/src/main/java/com/baeldung/Foo.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/Foo.java
rename to core-java/src/main/java/com/baeldung/Foo.java
diff --git a/core-java-8/src/main/java/com/baeldung/FooExtended.java b/core-java/src/main/java/com/baeldung/FooExtended.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/FooExtended.java
rename to core-java/src/main/java/com/baeldung/FooExtended.java
diff --git a/core-java-8/src/main/java/com/baeldung/UseFoo.java b/core-java/src/main/java/com/baeldung/UseFoo.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/UseFoo.java
rename to core-java/src/main/java/com/baeldung/UseFoo.java
diff --git a/core-java/src/main/java/com/baeldung/datetime/README.md b/core-java/src/main/java/com/baeldung/datetime/README.md
new file mode 100644
index 0000000000..1e4adbb612
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/datetime/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java b/core-java/src/main/java/com/baeldung/datetime/UseDuration.java
similarity index 74%
rename from core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java
rename to core-java/src/main/java/com/baeldung/datetime/UseDuration.java
index 125b6fbe38..31b45aab84 100644
--- a/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java
+++ b/core-java/src/main/java/com/baeldung/datetime/UseDuration.java
@@ -5,12 +5,12 @@ import java.time.LocalTime;
import java.time.Period;
public class UseDuration {
-
- public LocalTime modifyDates(LocalTime localTime,Duration duration){
+
+ public LocalTime modifyDates(LocalTime localTime, Duration duration) {
return localTime.plus(duration);
}
-
- public Duration getDifferenceBetweenDates(LocalTime localTime1,LocalTime localTime2){
+
+ 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/src/main/java/com/baeldung/datetime/UseLocalDate.java
similarity index 67%
rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java
rename to core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java
index 47b1b3f67d..82f5745b3c 100644
--- a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java
+++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalDate.java
@@ -7,39 +7,39 @@ import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
public class UseLocalDate {
-
- public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth){
+
+ public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth) {
return LocalDate.of(year, month, dayOfMonth);
}
-
- public LocalDate getLocalDateUsingParseMethod(String representation){
+
+ public LocalDate getLocalDateUsingParseMethod(String representation) {
return LocalDate.parse(representation);
}
-
- public LocalDate getLocalDateFromClock(){
+
+ public LocalDate getLocalDateFromClock() {
LocalDate localDate = LocalDate.now();
return localDate;
}
-
- public LocalDate getNextDay(LocalDate localDate){
+
+ public LocalDate getNextDay(LocalDate localDate) {
return localDate.plusDays(1);
}
-
- public LocalDate getPreviousDay(LocalDate localDate){
+
+ public LocalDate getPreviousDay(LocalDate localDate) {
return localDate.minus(1, ChronoUnit.DAYS);
}
-
- public DayOfWeek getDayOfWeek(LocalDate localDate){
+
+ public DayOfWeek getDayOfWeek(LocalDate localDate) {
DayOfWeek day = localDate.getDayOfWeek();
return day;
}
-
- public LocalDate getFirstDayOfMonth(){
+
+ public LocalDate getFirstDayOfMonth() {
LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
return firstDayOfMonth;
}
-
- public LocalDateTime getStartOfDay(LocalDate localDate){
+
+ 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/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
similarity index 87%
rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
rename to core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
index 7aa1eaa276..7f39ac2f91 100644
--- a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
+++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
@@ -3,8 +3,8 @@ package com.baeldung.datetime;
import java.time.LocalDateTime;
public class UseLocalDateTime {
-
- public LocalDateTime getLocalDateTimeUsingParseMethod(String representation){
+
+ 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/src/main/java/com/baeldung/datetime/UseLocalTime.java
similarity index 67%
rename from core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java
rename to core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java
index e13fd10d6f..9bd8f9706c 100644
--- a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java
+++ b/core-java/src/main/java/com/baeldung/datetime/UseLocalTime.java
@@ -4,32 +4,32 @@ import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
public class UseLocalTime {
-
- public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds){
+
+ public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds) {
LocalTime localTime = LocalTime.of(hour, min, seconds);
return localTime;
}
-
- public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation){
+
+ public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation) {
LocalTime localTime = LocalTime.parse(timeRepresentation);
return localTime;
}
-
- public LocalTime getLocalTimeFromClock(){
+
+ public LocalTime getLocalTimeFromClock() {
LocalTime localTime = LocalTime.now();
return localTime;
}
-
- public LocalTime addAnHour(LocalTime localTime){
- LocalTime newTime = localTime.plus(1,ChronoUnit.HOURS);
+
+ public LocalTime addAnHour(LocalTime localTime) {
+ LocalTime newTime = localTime.plus(1, ChronoUnit.HOURS);
return newTime;
}
-
- public int getHourFromLocalTime(LocalTime localTime){
+
+ public int getHourFromLocalTime(LocalTime localTime) {
return localTime.getHour();
}
-
- public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute){
+
+ 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/src/main/java/com/baeldung/datetime/UsePeriod.java
similarity index 73%
rename from core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java
rename to core-java/src/main/java/com/baeldung/datetime/UsePeriod.java
index 326cfad650..5a42ef83b4 100644
--- a/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java
+++ b/core-java/src/main/java/com/baeldung/datetime/UsePeriod.java
@@ -4,12 +4,12 @@ import java.time.LocalDate;
import java.time.Period;
public class UsePeriod {
-
- public LocalDate modifyDates(LocalDate localDate,Period period){
+
+ public LocalDate modifyDates(LocalDate localDate, Period period) {
return localDate.plus(period);
}
-
- public Period getDifferenceBetweenDates(LocalDate localDate1,LocalDate localDate2){
+
+ 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/src/main/java/com/baeldung/datetime/UseToInstant.java
similarity index 87%
rename from core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java
rename to core-java/src/main/java/com/baeldung/datetime/UseToInstant.java
index 1ddb096cf6..94154ce5c0 100644
--- a/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java
+++ b/core-java/src/main/java/com/baeldung/datetime/UseToInstant.java
@@ -6,13 +6,13 @@ import java.util.Calendar;
import java.util.Date;
public class UseToInstant {
-
- public LocalDateTime convertDateToLocalDate(Date date){
+
+ public LocalDateTime convertDateToLocalDate(Date date) {
LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
return localDateTime;
}
-
- public LocalDateTime convertDateToLocalDate(Calendar calendar){
+
+ 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/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
similarity index 90%
rename from core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
rename to core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
index 0369de9835..2d1b17484b 100644
--- a/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
+++ b/core-java/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
@@ -5,8 +5,8 @@ import java.time.ZoneId;
import java.time.ZonedDateTime;
public class UseZonedDateTime {
-
- public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime,ZoneId zoneId){
+
+ 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/doublecolon/Computer.java b/core-java/src/main/java/com/baeldung/doublecolon/Computer.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/doublecolon/Computer.java
rename to core-java/src/main/java/com/baeldung/doublecolon/Computer.java
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/ComputerUtils.java b/core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/doublecolon/ComputerUtils.java
rename to core-java/src/main/java/com/baeldung/doublecolon/ComputerUtils.java
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/MacbookPro.java b/core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/doublecolon/MacbookPro.java
rename to core-java/src/main/java/com/baeldung/doublecolon/MacbookPro.java
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java b/core-java/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java
rename to core-java/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/function/TriFunction.java b/core-java/src/main/java/com/baeldung/doublecolon/function/TriFunction.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/doublecolon/function/TriFunction.java
rename to core-java/src/main/java/com/baeldung/doublecolon/function/TriFunction.java
diff --git a/core-java/src/main/java/com/baeldung/enums/Pizza.java b/core-java/src/main/java/com/baeldung/enums/Pizza.java
index 7742781081..bad134bf00 100644
--- a/core-java/src/main/java/com/baeldung/enums/Pizza.java
+++ b/core-java/src/main/java/com/baeldung/enums/Pizza.java
@@ -1,11 +1,5 @@
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;
@@ -13,13 +7,11 @@ import java.util.stream.Collectors;
public class Pizza {
- private static EnumSet undeliveredPizzaStatuses =
- EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY);
+ private static EnumSet deliveredPizzaStatuses = EnumSet.of(PizzaStatusEnum.DELIVERED);
- private PizzaStatus status;
+ private PizzaStatusEnum status;
- @JsonFormat(shape = JsonFormat.Shape.OBJECT)
- public enum PizzaStatus {
+ public enum PizzaStatusEnum {
ORDERED(5) {
@Override
public boolean isOrdered() {
@@ -53,21 +45,20 @@ public class Pizza {
return false;
}
- @JsonProperty("timeToDelivery")
public int getTimeToDelivery() {
return timeToDelivery;
}
- PizzaStatus(int timeToDelivery) {
+ PizzaStatusEnum(int timeToDelivery) {
this.timeToDelivery = timeToDelivery;
}
}
- public PizzaStatus getStatus() {
+ public PizzaStatusEnum getStatus() {
return status;
}
- public void setStatus(PizzaStatus status) {
+ public void setStatus(PizzaStatusEnum status) {
this.status = status;
}
@@ -80,31 +71,18 @@ public class Pizza {
}
public static List getAllUndeliveredPizzas(List input) {
- return input.stream().filter(
- (s) -> undeliveredPizzaStatuses.contains(s.getStatus()))
- .collect(Collectors.toList());
+ 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<>(PizzaStatus.class), 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(PizzaStatus.DELIVERED);
+ this.setStatus(PizzaStatusEnum.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/README.md b/core-java/src/main/java/com/baeldung/enums/README.md
new file mode 100644
index 0000000000..6ccfa725f5
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/enums/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
diff --git a/core-java/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java
new file mode 100644
index 0000000000..5a13f505c2
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/ComplexClass.java
@@ -0,0 +1,63 @@
+package com.baeldung.equalshashcode.entities;
+
+import java.util.List;
+import java.util.Set;
+
+public class ComplexClass {
+
+ private List> genericList;
+ private Set integerSet;
+
+ public ComplexClass(List> genericArrayList, Set 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/com/baeldung/equalshashcode/entities/PrimitiveClass.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java
new file mode 100644
index 0000000000..29b280865e
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/PrimitiveClass.java
@@ -0,0 +1,54 @@
+package com.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/com/baeldung/equalshashcode/entities/Rectangle.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java
new file mode 100644
index 0000000000..168e3af0c6
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Rectangle.java
@@ -0,0 +1,58 @@
+package com.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/com/baeldung/equalshashcode/entities/Shape.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Shape.java
new file mode 100644
index 0000000000..628359becf
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Shape.java
@@ -0,0 +1,7 @@
+package com.baeldung.equalshashcode.entities;
+
+public abstract class Shape {
+ public abstract double area();
+
+ public abstract double perimeter();
+}
diff --git a/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java
new file mode 100644
index 0000000000..b9125c3e2f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/equalshashcode/entities/Square.java
@@ -0,0 +1,58 @@
+package com.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/java/com/baeldung/executable/ExecutableMavenJar.java b/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java
new file mode 100644
index 0000000000..6c79e89717
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java
@@ -0,0 +1,11 @@
+package com.baeldung.executable;
+
+import javax.swing.JOptionPane;
+
+public class ExecutableMavenJar {
+
+ public static void main(String[] args) {
+ JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java
similarity index 94%
rename from core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java
rename to core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java
index f1ab2d8d09..ae79787570 100644
--- a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java
+++ b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java
@@ -30,8 +30,7 @@ public class CustomRecursiveAction extends RecursiveAction {
private Collection createSubtasks() {
- List subtasks =
- new ArrayList<>();
+ List subtasks = new ArrayList<>();
String partOne = workLoad.substring(0, workLoad.length() / 2);
String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length());
diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java
similarity index 60%
rename from core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java
rename to core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java
index 5d4d97b805..af9805c33f 100644
--- a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java
+++ b/core-java/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java
@@ -1,6 +1,5 @@
package com.baeldung.forkjoin;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -23,10 +22,7 @@ public class CustomRecursiveTask extends RecursiveTask {
if (arr.length > THRESHOLD) {
- return ForkJoinTask.invokeAll(createSubtasks())
- .stream()
- .mapToInt(ForkJoinTask::join)
- .sum();
+ return ForkJoinTask.invokeAll(createSubtasks()).stream().mapToInt(ForkJoinTask::join).sum();
} else {
return processing(arr);
@@ -35,17 +31,12 @@ public class CustomRecursiveTask extends RecursiveTask {
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)));
+ 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();
+ 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/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java
similarity index 99%
rename from core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java
rename to core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java
index 521616600f..fd24a6fc66 100644
--- a/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java
+++ b/core-java/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java
@@ -1,6 +1,5 @@
package com.baeldung.forkjoin.util;
-
import java.util.concurrent.ForkJoinPool;
public class PoolUtil {
diff --git a/core-java/src/main/java/com/baeldung/java/conversion/StringConversion.java b/core-java/src/main/java/com/baeldung/java/conversion/StringConversion.java
new file mode 100644
index 0000000000..0a0f79566e
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/conversion/StringConversion.java
@@ -0,0 +1,60 @@
+package com.baeldung.java.conversion;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.time.LocalDateTime;
+import java.util.Date;
+
+import com.baeldung.datetime.UseLocalDateTime;
+
+public class StringConversion {
+
+ public static int getInt(String str) {
+ return Integer.parseInt(str);
+ }
+
+ public static int getInteger(String str) {
+ return Integer.valueOf(str);
+ }
+
+ public static long getLongPrimitive(String str) {
+ return Long.parseLong(str);
+ }
+
+ public static Long getLong(String str) {
+ return Long.valueOf(str);
+ }
+
+ public static double getDouble(String str) {
+ return Double.parseDouble(str);
+ }
+
+ public static double getDoublePrimitive(String str) {
+ return Double.valueOf(str);
+ }
+
+ public static byte[] getByteArray(String str) {
+ return str.getBytes();
+ }
+
+ public static char[] getCharArray(String str) {
+ return str.toCharArray();
+ }
+
+ public static boolean getBooleanPrimitive(String str) {
+ return Boolean.parseBoolean(str);
+ }
+
+ public static boolean getBoolean(String str) {
+ return Boolean.valueOf(str);
+ }
+
+ public static Date getJava6Date(String str, String format) throws ParseException {
+ SimpleDateFormat formatter = new SimpleDateFormat(format);
+ return formatter.parse(str);
+ }
+
+ public static LocalDateTime getJava8Date(String str) throws ParseException {
+ return new UseLocalDateTime().getLocalDateTimeUsingParseMethod(str);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java b/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java
new file mode 100644
index 0000000000..0d66406ac2
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/networking/cookies/PersistentCookieStore.java
@@ -0,0 +1,56 @@
+package com.baeldung.java.networking.cookies;
+
+import java.net.*;
+import java.util.List;
+
+public class PersistentCookieStore implements CookieStore, Runnable {
+ CookieStore store;
+
+ public PersistentCookieStore() {
+ store = new CookieManager().getCookieStore();
+ // deserialize cookies into store
+ Runtime.getRuntime().addShutdownHook(new Thread(this));
+ }
+
+ @Override
+ public void run() {
+ // serialize cookies to persistent storage
+ }
+
+ @Override
+ public void add(URI uri, HttpCookie cookie) {
+ store.add(uri, cookie);
+
+ }
+
+ @Override
+ public List get(URI uri) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public List getCookies() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public List getURIs() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+ @Override
+ public boolean remove(URI uri, HttpCookie cookie) {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ public boolean removeAll() {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java b/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java
new file mode 100644
index 0000000000..6d6371bfe0
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/networking/cookies/ProxyAcceptCookiePolicy.java
@@ -0,0 +1,26 @@
+package com.baeldung.java.networking.cookies;
+
+import java.net.*;
+
+public class ProxyAcceptCookiePolicy implements CookiePolicy {
+ String acceptedProxy;
+
+ public ProxyAcceptCookiePolicy(String acceptedProxy) {
+ this.acceptedProxy = acceptedProxy;
+ }
+
+ public boolean shouldAccept(URI uri, HttpCookie cookie) {
+ String host;
+ try {
+ host = InetAddress.getByName(uri.getHost()).getCanonicalHostName();
+ } catch (UnknownHostException e) {
+ host = uri.getHost();
+ }
+
+ if (!HttpCookie.domainMatches(acceptedProxy, host)) {
+ return false;
+ }
+
+ return CookiePolicy.ACCEPT_ORIGINAL_SERVER.shouldAccept(uri, cookie);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java
new file mode 100644
index 0000000000..916442533b
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoClient.java
@@ -0,0 +1,42 @@
+package com.baeldung.java.networking.udp;
+
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+
+public class EchoClient {
+ private DatagramSocket socket;
+ private InetAddress address;
+
+ private byte[] buf;
+
+ public EchoClient() {
+ try {
+ socket = new DatagramSocket();
+ address = InetAddress.getByName("localhost");
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ public String sendEcho(String msg) {
+ DatagramPacket packet = null;
+ try {
+ buf = msg.getBytes();
+ packet = new DatagramPacket(buf, buf.length, address, 4445);
+ socket.send(packet);
+ packet = new DatagramPacket(buf, buf.length);
+ socket.receive(packet);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ String received = new String(packet.getData(), 0, packet.getLength());
+ return received;
+ }
+
+ public void close() {
+ socket.close();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java
new file mode 100644
index 0000000000..900d330786
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/networking/udp/EchoServer.java
@@ -0,0 +1,42 @@
+package com.baeldung.java.networking.udp;
+
+import java.io.IOException;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
+
+public class EchoServer extends Thread {
+
+ protected DatagramSocket socket = null;
+ protected boolean running;
+ protected byte[] buf = new byte[256];
+
+ public EchoServer() throws IOException {
+ socket = new DatagramSocket(4445);
+ }
+
+ public void run() {
+ running = true;
+
+ while (running) {
+ try {
+
+ DatagramPacket packet = new DatagramPacket(buf, buf.length);
+ socket.receive(packet);
+ InetAddress address = packet.getAddress();
+ int port = packet.getPort();
+ packet = new DatagramPacket(buf, buf.length, address, port);
+ String received = new String(packet.getData(), 0, packet.getLength());
+ if (received.equals("end")) {
+ running = false;
+ continue;
+ }
+ socket.send(packet);
+ } catch (IOException e) {
+ e.printStackTrace();
+ running = false;
+ }
+ }
+ socket.close();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java
new file mode 100644
index 0000000000..61f339db58
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoClient.java
@@ -0,0 +1,50 @@
+package com.baeldung.java.nio.selector;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.SocketChannel;
+
+public class EchoClient {
+ private static SocketChannel client;
+ private static ByteBuffer buffer;
+ private static EchoClient instance;
+
+ public static EchoClient start() {
+ if (instance == null)
+ instance = new EchoClient();
+
+ return instance;
+ }
+
+ public static void stop() throws IOException {
+ client.close();
+ buffer = null;
+ }
+
+ private EchoClient() {
+ try {
+ client = SocketChannel.open(new InetSocketAddress("localhost", 5454));
+ buffer = ByteBuffer.allocate(256);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public String sendMessage(String msg) {
+ buffer = ByteBuffer.wrap(msg.getBytes());
+ String response = null;
+ try {
+ client.write(buffer);
+ buffer.clear();
+ client.read(buffer);
+ response = new String(buffer.array()).trim();
+ System.out.println("response=" + response);
+ buffer.clear();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return response;
+
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java
new file mode 100644
index 0000000000..2ed9a27c4c
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/java/nio/selector/EchoServer.java
@@ -0,0 +1,60 @@
+package com.baeldung.java.nio.selector;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.util.Iterator;
+import java.util.Set;
+
+public class EchoServer {
+
+ public static void main(String[] args) throws IOException {
+ Selector selector = Selector.open();
+ ServerSocketChannel serverSocket = ServerSocketChannel.open();
+ serverSocket.bind(new InetSocketAddress("localhost", 5454));
+ serverSocket.configureBlocking(false);
+ serverSocket.register(selector, SelectionKey.OP_ACCEPT);
+ ByteBuffer buffer = ByteBuffer.allocate(256);
+
+ while (true) {
+ selector.select();
+ Set selectedKeys = selector.selectedKeys();
+ Iterator iter = selectedKeys.iterator();
+ while (iter.hasNext()) {
+
+ SelectionKey key = iter.next();
+
+ if (key.isAcceptable()) {
+ SocketChannel client = serverSocket.accept();
+ client.configureBlocking(false);
+ client.register(selector, SelectionKey.OP_READ);
+ }
+
+ if (key.isReadable()) {
+ SocketChannel client = (SocketChannel) key.channel();
+ client.read(buffer);
+ buffer.flip();
+ client.write(buffer);
+ buffer.clear();
+ }
+ iter.remove();
+ }
+ }
+ }
+
+ public static Process start() throws IOException, InterruptedException {
+ String javaHome = System.getProperty("java.home");
+ String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
+ String classpath = System.getProperty("java.class.path");
+ String className = EchoServer.class.getCanonicalName();
+
+ ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className);
+
+ return builder.start();
+ }
+}
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-8/src/main/java/com/baeldung/java_8_features/Address.java b/core-java/src/main/java/com/baeldung/java_8_features/Address.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/Address.java
rename to core-java/src/main/java/com/baeldung/java_8_features/Address.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java b/core-java/src/main/java/com/baeldung/java_8_features/CustomException.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java
rename to core-java/src/main/java/com/baeldung/java_8_features/CustomException.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java b/core-java/src/main/java/com/baeldung/java_8_features/Detail.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java
rename to core-java/src/main/java/com/baeldung/java_8_features/Detail.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java b/core-java/src/main/java/com/baeldung/java_8_features/OptionalAddress.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java
rename to core-java/src/main/java/com/baeldung/java_8_features/OptionalAddress.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java b/core-java/src/main/java/com/baeldung/java_8_features/OptionalUser.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java
rename to core-java/src/main/java/com/baeldung/java_8_features/OptionalUser.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/User.java b/core-java/src/main/java/com/baeldung/java_8_features/User.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/User.java
rename to core-java/src/main/java/com/baeldung/java_8_features/User.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java b/core-java/src/main/java/com/baeldung/java_8_features/Vehicle.java
similarity index 89%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java
rename to core-java/src/main/java/com/baeldung/java_8_features/Vehicle.java
index 011173bcaf..045fc90590 100644
--- a/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java
+++ b/core-java/src/main/java/com/baeldung/java_8_features/Vehicle.java
@@ -9,7 +9,7 @@ public interface Vehicle {
}
default long[] startPosition() {
- return new long[]{23, 15};
+ return new long[] { 23, 15 };
}
default String getOverview() {
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java b/core-java/src/main/java/com/baeldung/java_8_features/VehicleImpl.java
similarity index 63%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java
rename to core-java/src/main/java/com/baeldung/java_8_features/VehicleImpl.java
index 83e55f5f4d..64bec0246d 100644
--- a/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java
+++ b/core-java/src/main/java/com/baeldung/java_8_features/VehicleImpl.java
@@ -1,9 +1,9 @@
package com.baeldung.java_8_features;
-public class VehicleImpl implements Vehicle {
+public class VehicleImpl implements Vehicle {
@Override
public void moveTo(long altitude, long longitude) {
- //do nothing
+ // do nothing
}
}
diff --git a/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java
new file mode 100644
index 0000000000..7f87b47476
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/printscreen/Screenshot.java
@@ -0,0 +1,22 @@
+package com.baeldung.printscreen;
+
+import javax.imageio.ImageIO;
+import java.awt.*;
+import java.awt.image.BufferedImage;
+import java.io.File;
+
+public class Screenshot {
+
+ private final String path;
+
+ public Screenshot(String path) {
+ this.path = path;
+ }
+
+ public void getScreenshot(int timeToWait) throws Exception {
+ Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
+ Robot robot = new Robot();
+ BufferedImage img = robot.createScreenCapture(rectangle);
+ ImageIO.write(img, "jpg", new File(path));
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/socket/EchoClient.java b/core-java/src/main/java/com/baeldung/socket/EchoClient.java
new file mode 100644
index 0000000000..570bd60b2d
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/socket/EchoClient.java
@@ -0,0 +1,41 @@
+package com.baeldung.socket;
+
+import java.io.*;
+import java.net.*;
+
+public class EchoClient {
+ private Socket clientSocket;
+ private PrintWriter out;
+ private BufferedReader in;
+
+ public void startConnection(String ip, int port) {
+ try {
+ clientSocket = new Socket(ip, port);
+ out = new PrintWriter(clientSocket.getOutputStream(), true);
+ in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
+ } catch (IOException e) {
+ System.out.print(e);
+ }
+
+ }
+
+ public String sendMessage(String msg) {
+ try {
+ out.println(msg);
+ return in.readLine();
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ public void stopConnection() {
+ try {
+ in.close();
+ out.close();
+ clientSocket.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java
new file mode 100644
index 0000000000..b920967545
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/socket/EchoMultiServer.java
@@ -0,0 +1,70 @@
+package com.baeldung.socket;
+
+import java.net.*;
+import java.io.*;
+
+public class EchoMultiServer {
+ private ServerSocket serverSocket;
+
+ public void start(int port) {
+ try {
+ serverSocket = new ServerSocket(port);
+ while (true)
+ new EchoClientHandler(serverSocket.accept()).run();
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ stop();
+ }
+
+ }
+
+ public void stop() {
+ try {
+
+ serverSocket.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ private static class EchoClientHandler extends Thread {
+ private Socket clientSocket;
+ private PrintWriter out;
+ private BufferedReader in;
+
+ public EchoClientHandler(Socket socket) {
+ this.clientSocket = socket;
+ }
+
+ public void run() {
+ try {
+ out = new PrintWriter(clientSocket.getOutputStream(), true);
+ in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
+ String inputLine;
+ while ((inputLine = in.readLine()) != null) {
+ if (".".equals(inputLine)) {
+ out.println("bye");
+ break;
+ }
+ out.println(inputLine);
+ }
+
+ in.close();
+ out.close();
+ clientSocket.close();
+
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ public static void main(String[] args) {
+ EchoMultiServer server = new EchoMultiServer();
+ server.start(5555);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/socket/EchoServer.java b/core-java/src/main/java/com/baeldung/socket/EchoServer.java
new file mode 100644
index 0000000000..dfd281d51c
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/socket/EchoServer.java
@@ -0,0 +1,49 @@
+package com.baeldung.socket;
+
+import java.net.*;
+import java.io.*;
+
+public class EchoServer {
+ private ServerSocket serverSocket;
+ private Socket clientSocket;
+ private PrintWriter out;
+ private BufferedReader in;
+
+ public void start(int port) {
+ try {
+ serverSocket = new ServerSocket(port);
+ clientSocket = serverSocket.accept();
+ out = new PrintWriter(clientSocket.getOutputStream(), true);
+ in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
+ String inputLine;
+ while ((inputLine = in.readLine()) != null) {
+ if (".".equals(inputLine)) {
+ out.println("good bye");
+ break;
+ }
+ out.println(inputLine);
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ public void stop() {
+ try {
+ in.close();
+ out.close();
+ clientSocket.close();
+ serverSocket.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ public static void main(String[] args) {
+ EchoServer server = new EchoServer();
+ server.start(4444);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/socket/GreetClient.java b/core-java/src/main/java/com/baeldung/socket/GreetClient.java
new file mode 100644
index 0000000000..e6f14bb2b6
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/socket/GreetClient.java
@@ -0,0 +1,44 @@
+package com.baeldung.socket;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.net.Socket;
+
+public class GreetClient {
+ private Socket clientSocket;
+ private PrintWriter out;
+ private BufferedReader in;
+
+ public void startConnection(String ip, int port) {
+ try {
+ clientSocket = new Socket(ip, port);
+ out = new PrintWriter(clientSocket.getOutputStream(), true);
+ in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
+ } catch (IOException e) {
+
+ }
+
+ }
+
+ public String sendMessage(String msg) {
+ try {
+ out.println(msg);
+ return in.readLine();
+ } catch (Exception e) {
+ return null;
+ }
+ }
+
+ public void stopConnection() {
+ try {
+ in.close();
+ out.close();
+ clientSocket.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/socket/GreetServer.java b/core-java/src/main/java/com/baeldung/socket/GreetServer.java
new file mode 100644
index 0000000000..05bc65a65e
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/socket/GreetServer.java
@@ -0,0 +1,46 @@
+package com.baeldung.socket;
+
+import java.net.*;
+import java.io.*;
+
+public class GreetServer {
+ private ServerSocket serverSocket;
+ private Socket clientSocket;
+ private PrintWriter out;
+ private BufferedReader in;
+
+ public void start(int port) {
+ try {
+ serverSocket = new ServerSocket(port);
+ clientSocket = serverSocket.accept();
+ out = new PrintWriter(clientSocket.getOutputStream(), true);
+ in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
+ String greeting = in.readLine();
+ if ("hello server".equals(greeting))
+ out.println("hello client");
+ else
+ out.println("unrecognised greeting");
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ public void stop() {
+ try {
+ in.close();
+ out.close();
+ clientSocket.close();
+ serverSocket.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ }
+
+ public static void main(String[] args) {
+ GreetServer server = new GreetServer();
+ server.start(6666);
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/streamApi/Product.java b/core-java/src/main/java/com/baeldung/streamApi/Product.java
similarity index 99%
rename from core-java-8/src/main/java/com/baeldung/streamApi/Product.java
rename to core-java/src/main/java/com/baeldung/streamApi/Product.java
index 18f3a61904..26b8bd6fed 100644
--- a/core-java-8/src/main/java/com/baeldung/streamApi/Product.java
+++ b/core-java/src/main/java/com/baeldung/streamApi/Product.java
@@ -44,7 +44,6 @@ public class Product {
this.name = name;
}
-
public static Stream streamOf(List list) {
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
}
diff --git a/core-java/src/main/java/com/baeldung/threadpool/CountingTask.java b/core-java/src/main/java/com/baeldung/threadpool/CountingTask.java
new file mode 100644
index 0000000000..effdf54916
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/threadpool/CountingTask.java
@@ -0,0 +1,20 @@
+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/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java b/core-java/src/main/java/com/baeldung/threadpool/ExitingExecutorServiceExample.java
new file mode 100644
index 0000000000..4775fde930
--- /dev/null
+++ b/core-java/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/src/main/java/com/baeldung/threadpool/TreeNode.java b/core-java/src/main/java/com/baeldung/threadpool/TreeNode.java
new file mode 100644
index 0000000000..9b43152074
--- /dev/null
+++ b/core-java/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/src/main/java/com/baeldung/unzip/UnzipFile.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java
rename to core-java/src/main/java/com/baeldung/unzip/UnzipFile.java
diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java b/core-java/src/main/java/com/baeldung/zip/ZipDirectory.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java
rename to core-java/src/main/java/com/baeldung/zip/ZipDirectory.java
diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java b/core-java/src/main/java/com/baeldung/zip/ZipFile.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/zip/ZipFile.java
rename to core-java/src/main/java/com/baeldung/zip/ZipFile.java
diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java b/core-java/src/main/java/com/baeldung/zip/ZipMultipleFiles.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java
rename to core-java/src/main/java/com/baeldung/zip/ZipMultipleFiles.java
diff --git a/core-java-8/src/main/resources/dirCompressed.zip b/core-java/src/main/resources/dirCompressed.zip
similarity index 100%
rename from core-java-8/src/main/resources/dirCompressed.zip
rename to core-java/src/main/resources/dirCompressed.zip
diff --git a/core-java/src/main/resources/fileTest.txt b/core-java/src/main/resources/fileTest.txt
new file mode 100644
index 0000000000..ce4bea208b
--- /dev/null
+++ b/core-java/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/multiCompressed.zip b/core-java/src/main/resources/multiCompressed.zip
similarity index 100%
rename from core-java-8/src/main/resources/multiCompressed.zip
rename to core-java/src/main/resources/multiCompressed.zip
diff --git a/core-java/src/test/java/com/baeldung/CharToStringUnitTest.java b/core-java/src/test/java/com/baeldung/CharToStringUnitTest.java
new file mode 100644
index 0000000000..78742e356d
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/CharToStringUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung;
+
+import org.junit.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class CharToStringUnitTest {
+
+ @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/src/test/java/com/baeldung/RandomListElementUnitTest.java b/core-java/src/test/java/com/baeldung/RandomListElementUnitTest.java
new file mode 100644
index 0000000000..6ae7c40f4d
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/RandomListElementUnitTest.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 RandomListElementUnitTest {
+
+ @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/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java b/core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java
new file mode 100644
index 0000000000..a7ad0bf114
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/StringToIntOrIntegerUnitTest.java
@@ -0,0 +1,62 @@
+package com.baeldung;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.Test;
+
+import com.google.common.primitives.Ints;
+
+public class StringToIntOrIntegerUnitTest {
+
+ @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/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java
similarity index 54%
rename from core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java
rename to core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java
index d94f72b685..dbddbe6c54 100644
--- a/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsTest.java
+++ b/core-java/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java
@@ -36,198 +36,143 @@ 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 {
+public class Java8CollectorsUnitTest {
private final List givenList = Arrays.asList("a", "bb", "ccc", "dd");
@Test
public void whenCollectingToList_shouldCollectToList() throws Exception {
- final List result = givenList.stream()
- .collect(toList());
+ final List result = givenList.stream().collect(toList());
- assertThat(result)
- .containsAll(givenList);
+ assertThat(result).containsAll(givenList);
}
@Test
public void whenCollectingToList_shouldCollectToSet() throws Exception {
- final Set result = givenList.stream()
- .collect(toSet());
+ final Set result = givenList.stream().collect(toSet());
- assertThat(result)
- .containsAll(givenList);
+ assertThat(result).containsAll(givenList);
}
@Test
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
- final List result = givenList.stream()
- .collect(toCollection(LinkedList::new));
+ final List result = givenList.stream().collect(toCollection(LinkedList::new));
- assertThat(result)
- .containsAll(givenList)
- .isInstanceOf(LinkedList.class);
+ assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
}
@Test
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
assertThatThrownBy(() -> {
- givenList.stream()
- .collect(toCollection(ImmutableList::of));
+ 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));
+ 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);
+ 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));
+ 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);
+ 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));
+ final List result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
- assertThat(result)
- .containsAll(givenList)
- .isInstanceOf(ImmutableList.class);
+ assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
}
@Test
public void whenJoining_shouldJoin() throws Exception {
- final String result = givenList.stream()
- .collect(joining());
+ final String result = givenList.stream().collect(joining());
- assertThat(result)
- .isEqualTo("abbcccdd");
+ assertThat(result).isEqualTo("abbcccdd");
}
@Test
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
- final String result = givenList.stream()
- .collect(joining(" "));
+ final String result = givenList.stream().collect(joining(" "));
- assertThat(result)
- .isEqualTo("a bb ccc dd");
+ assertThat(result).isEqualTo("a bb ccc dd");
}
@Test
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
- final String result = givenList.stream()
- .collect(joining(" ", "PRE-", "-POST"));
+ final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
- assertThat(result)
- .isEqualTo("PRE-a bb ccc dd-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));
+ 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(result).containsKeys(true, false).satisfies(booleanListMap -> {
+ assertThat(booleanListMap.get(true)).contains("ccc");
- assertThat(booleanListMap.get(false))
- .contains("a", "bb", "dd");
- });
+ assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
+ });
}
@Test
public void whenCounting_shouldCount() throws Exception {
- final Long result = givenList.stream()
- .collect(counting());
+ final Long result = givenList.stream().collect(counting());
- assertThat(result)
- .isEqualTo(4);
+ assertThat(result).isEqualTo(4);
}
@Test
public void whenSummarizing_shouldSummarize() throws Exception {
- final DoubleSummaryStatistics result = givenList.stream()
- .collect(summarizingDouble(String::length));
+ 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);
+ 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));
+ final Double result = givenList.stream().collect(averagingDouble(String::length));
- assertThat(result)
- .isEqualTo(2);
+ assertThat(result).isEqualTo(2);
}
@Test
public void whenSumming_shouldSum() throws Exception {
- final Double result = givenList.stream()
- .collect(summingDouble(String::length));
+ final Double result = givenList.stream().collect(summingDouble(String::length));
- assertThat(result)
- .isEqualTo(8);
+ assertThat(result).isEqualTo(8);
}
@Test
public void whenMaxingBy_shouldMaxBy() throws Exception {
- final Optional result = givenList.stream()
- .collect(maxBy(Comparator.naturalOrder()));
+ final Optional result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
- assertThat(result)
- .isPresent()
- .hasValue("dd");
+ assertThat(result).isPresent().hasValue("dd");
}
@Test
public void whenGroupingBy_shouldGroupBy() throws Exception {
- final Map> result = givenList.stream()
- .collect(groupingBy(String::length, toSet()));
+ 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"));
+ 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());
+ final ImmutableSet result = givenList.stream().collect(toImmutableSet());
- assertThat(result)
- .isInstanceOf(ImmutableSet.class)
- .contains("a", "bb", "ccc", "dd");
+ assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
}
diff --git a/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java
new file mode 100644
index 0000000000..df12c3d79e
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/completablefuture/CompletableFutureUnitTest.java
@@ -0,0 +1,176 @@
+package com.baeldung.completablefuture;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.junit.Test;
+
+public class CompletableFutureUnitTest {
+
+ @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/src/test/java/com/baeldung/dateapi/ConversionExample.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java
rename to core-java/src/test/java/com/baeldung/dateapi/ConversionExample.java
diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java b/core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java
similarity index 98%
rename from core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java
rename to core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java
index 4bce40c2d9..e4753dbd5c 100644
--- a/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java
+++ b/core-java/src/test/java/com/baeldung/dateapi/JavaUtilTimeUnitTest.java
@@ -14,7 +14,7 @@ import java.time.temporal.ChronoUnit;
import static org.assertj.core.api.Assertions.assertThat;
-public class JavaUtilTimeTest {
+public class JavaUtilTimeUnitTest {
@Test
public void currentTime() {
diff --git a/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.java
new file mode 100644
index 0000000000..57e1f33280
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateTimeUnitTest.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 UseLocalDateTimeUnitTest {
+
+ 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/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java
new file mode 100644
index 0000000000..8f1997e9e8
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalDateUnitTest.java
@@ -0,0 +1,54 @@
+package com.baeldung.datetime;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseLocalDateUnitTest {
+
+ 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/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java
new file mode 100644
index 0000000000..996e200ae9
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/datetime/UseLocalTimeUnitTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.datetime;
+
+import java.time.LocalTime;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseLocalTimeUnitTest {
+
+ 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/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java
similarity index 63%
rename from core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java
rename to core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java
index 8a3228aaa5..7c030c328a 100644
--- a/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java
+++ b/core-java/src/test/java/com/baeldung/datetime/UsePeriodUnitTest.java
@@ -1,29 +1,26 @@
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();
-
+public class UsePeriodUnitTest {
+ UsePeriod usingPeriod = new UsePeriod();
+
@Test
- public void givenPeriodAndLocalDate_thenCalculateModifiedDate(){
+ 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));
+ Assert.assertEquals(localDate.plusDays(1), usingPeriod.modifyDates(localDate, period));
}
-
+
@Test
- public void givenDates_thenGetPeriod(){
+ 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/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java b/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.java
new file mode 100644
index 0000000000..5fb079b94c
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/datetime/UseZonedDateTimeUnitTest.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 UseZonedDateTimeUnitTest {
+
+ 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/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java
similarity index 98%
rename from core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java
rename to core-java/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java
index 85194f5aa6..f69e4b03ee 100644
--- a/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java
+++ b/core-java/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java
@@ -13,7 +13,7 @@ import java.util.function.BiFunction;
import static com.baeldung.doublecolon.ComputerUtils.*;
-public class TestComputerUtils {
+public class ComputerUtilsUnitTest {
@Before
public void setup() {
diff --git a/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java b/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java
new file mode 100644
index 0000000000..c944dfa6fe
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/encoderdecoder/EncoderDecoderUnitTest.java
@@ -0,0 +1,77 @@
+package com.baeldung.encoderdecoder;
+
+import org.hamcrest.CoreMatchers;
+import org.junit.Assert;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+import static java.util.stream.Collectors.joining;
+
+public class EncoderDecoderUnitTest {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoderUnitTest.class);
+ private static final String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
+
+ private String encodeValue(String value) {
+ String encoded = null;
+ try {
+ encoded = URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
+ } catch (UnsupportedEncodingException e) {
+ LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
+ }
+ return encoded;
+ }
+
+ private String decode(String value) {
+ String decoded = null;
+ try {
+ decoded = URLDecoder.decode(value, StandardCharsets.UTF_8.toString());
+ } catch (UnsupportedEncodingException e) {
+ LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
+ }
+ return decoded;
+ }
+
+ @Test
+ public void givenURL_whenAnalyze_thenCorrect() throws Exception {
+ URL url = new URL(testUrl);
+
+ Assert.assertThat(url.getProtocol(), CoreMatchers.is("http"));
+ Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com"));
+ Assert.assertThat(url.getQuery(), CoreMatchers.is("key1=value+1&key2=value%40%21%242&key3=value%253"));
+ }
+
+ @Test
+ public void givenRequestParam_whenUTF8Scheme_thenEncode() throws Exception {
+ Map requestParams = new HashMap<>();
+ requestParams.put("key1", "value 1");
+ requestParams.put("key2", "value@!$2");
+ requestParams.put("key3", "value%3");
+
+ String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", ""));
+
+ Assert.assertThat(testUrl, CoreMatchers.is(encodedURL));
+ }
+
+ @Test
+ public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception {
+ URL url = new URL(testUrl);
+
+ String query = url.getQuery();
+
+ String decodedQuery = Arrays.stream(query.split("&")).map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])).collect(joining("&"));
+
+ Assert.assertEquals("http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
similarity index 98%
rename from core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java
rename to core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
index deeebaa240..6cf6ad3551 100644
--- a/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java
+++ b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
@@ -1,6 +1,5 @@
package com.baeldung.enums;
-
import org.junit.Test;
import java.util.ArrayList;
@@ -9,7 +8,7 @@ import java.util.List;
import static junit.framework.TestCase.assertTrue;
-public class PizzaTest {
+public class PizzaUnitTest {
@Test
public void givenPizaOrder_whenReady_thenDeliverable() {
diff --git a/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java b/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java
new file mode 100644
index 0000000000..3319716dc6
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/file/FileOperationsUnitTest.java
@@ -0,0 +1,121 @@
+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.URISyntaxException;
+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.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 FileOperationsUnitTest {
+
+ @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 = FileOperationsUnitTest.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, URISyntaxException {
+ String expectedData = "Hello World from fileTest.txt!!!";
+
+ Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
+
+ byte[] fileBytes = Files.readAllBytes(path);
+ String data = new String(fileBytes);
+
+ Assert.assertEquals(expectedData, data.trim());
+ }
+
+ @Test
+ public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
+ String expectedData = "Hello World from fileTest.txt!!!";
+
+ Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
+
+ StringBuilder data = new StringBuilder();
+ Stream lines = Files.lines(path);
+ lines.forEach(line -> data.append(line).append("\n"));
+ lines.close();
+
+ Assert.assertEquals(expectedData, data.toString().trim());
+ }
+
+ private String readFromInputStream(InputStream inputStream) throws IOException {
+ StringBuilder resultStringBuilder = new StringBuilder();
+ try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
+ String line;
+ while ((line = bufferedReader.readLine()) != null) {
+ resultStringBuilder.append(line).append("\n");
+ }
+ }
+
+ return resultStringBuilder.toString();
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java
new file mode 100644
index 0000000000..6f3384c8eb
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java
@@ -0,0 +1,182 @@
+package com.baeldung.functionalinterface;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+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 org.junit.Test;
+
+import com.google.common.util.concurrent.Uninterruptibles;
+
+public class FunctionalInterfaceUnitTest {
+
+ @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);
+ }
+
+ @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));
+
+ }
+
+ @Test
+ public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() {
+
+ Supplier lazyValue = () -> {
+ Uninterruptibles.sleepUninterruptibly(1000, TimeUnit.MILLISECONDS);
+ return 9d;
+ };
+
+ double valueSquared = squareLazy(lazyValue);
+
+ assertEquals(81d, valueSquared, 0);
+
+ }
+
+ //
+
+ public double squareLazy(Supplier lazyValue) {
+ return Math.pow(lazyValue.get(), 2);
+ }
+
+ 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;
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java b/core-java/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java
new file mode 100644
index 0000000000..3231d6244f
--- /dev/null
+++ b/core-java/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/src/test/java/com/baeldung/hexToAscii/HexToAscii.java b/core-java/src/test/java/com/baeldung/hexToAscii/HexToAscii.java
new file mode 100644
index 0000000000..2a3c4b109e
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/hexToAscii/HexToAscii.java
@@ -0,0 +1,46 @@
+package com.baeldung.hexToAscii;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class HexToAscii {
+
+ @Test
+ public static void whenHexToAscii() {
+ String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
+ String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
+
+ assertEquals(asciiString, hexToAscii(hexEquivalent));
+ }
+
+ @Test
+ public static void whenAsciiToHex() {
+ String asciiString = "http://www.baeldung.com/jackson-serialize-dates";
+ String hexEquivalent = "687474703a2f2f7777772e6261656c64756e672e636f6d2f6a61636b736f6e2d73657269616c697a652d6461746573";
+
+ assertEquals(hexEquivalent, asciiToHex(asciiString));
+ }
+
+ //
+
+ private static String asciiToHex(String asciiStr) {
+ char[] chars = asciiStr.toCharArray();
+ StringBuilder hex = new StringBuilder();
+ for (char ch : chars) {
+ hex.append(Integer.toHexString((int) ch));
+ }
+
+ return hex.toString();
+ }
+
+ private static String hexToAscii(String hexStr) {
+ StringBuilder output = new StringBuilder("");
+ for (int i = 0; i < hexStr.length(); i += 2) {
+ String str = hexStr.substring(i, i + 2);
+ output.append((char) Integer.parseInt(str, 16));
+ }
+ return output.toString();
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java b/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java
new file mode 100644
index 0000000000..8635a24f18
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/networking/interfaces/NetworkInterfaceManualTest.java
@@ -0,0 +1,118 @@
+package com.baeldung.java.networking.interfaces;
+
+import org.junit.Test;
+
+import java.net.*;
+import java.util.Enumeration;
+import java.util.List;
+
+import static org.junit.Assert.*;
+
+public class NetworkInterfaceManualTest {
+ @Test
+ public void givenName_whenReturnsNetworkInterface_thenCorrect() throws SocketException {
+ NetworkInterface nif = NetworkInterface.getByName("lo");
+ assertNotNull(nif);
+ }
+
+ @Test
+ public void givenInExistentName_whenReturnsNull_thenCorrect() throws SocketException {
+ NetworkInterface nif = NetworkInterface.getByName("inexistent_name");
+ assertNull(nif);
+ }
+
+ @Test
+ public void givenIP_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
+ byte[] ip = new byte[] { 127, 0, 0, 1 };
+ NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByAddress(ip));
+ assertNotNull(nif);
+ }
+
+ @Test
+ public void givenHostName_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
+ NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByName("localhost"));
+ assertNotNull(nif);
+ }
+
+ @Test
+ public void givenLocalHost_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
+ NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
+ assertNotNull(nif);
+ }
+
+ @Test
+ public void givenLoopBack_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
+ NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLoopbackAddress());
+ assertNotNull(nif);
+ }
+
+ @Test
+ public void givenIndex_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
+ NetworkInterface nif = NetworkInterface.getByIndex(0);
+ assertNotNull(nif);
+ }
+
+ @Test
+ public void givenInterface_whenReturnsInetAddresses_thenCorrect() throws SocketException, UnknownHostException {
+ NetworkInterface nif = NetworkInterface.getByName("lo");
+ Enumeration addressEnum = nif.getInetAddresses();
+ InetAddress address = addressEnum.nextElement();
+ assertEquals("127.0.0.1", address.getHostAddress());
+ }
+
+ @Test
+ public void givenInterface_whenReturnsInterfaceAddresses_thenCorrect() throws SocketException, UnknownHostException {
+ NetworkInterface nif = NetworkInterface.getByName("lo");
+
+ List addressEnum = nif.getInterfaceAddresses();
+ InterfaceAddress address = addressEnum.get(0);
+ InetAddress localAddress = address.getAddress();
+ InetAddress broadCastAddress = address.getBroadcast();
+ assertEquals("127.0.0.1", localAddress.getHostAddress());
+ assertEquals("127.255.255.255", broadCastAddress.getHostAddress());
+ }
+
+ @Test
+ public void givenInterface_whenChecksIfLoopback_thenCorrect() throws SocketException, UnknownHostException {
+ NetworkInterface nif = NetworkInterface.getByName("lo");
+ assertTrue(nif.isLoopback());
+ }
+
+ @Test
+ public void givenInterface_whenChecksIfUp_thenCorrect() throws SocketException, UnknownHostException {
+ NetworkInterface nif = NetworkInterface.getByName("lo");
+ assertTrue(nif.isUp());
+ }
+
+ @Test
+ public void givenInterface_whenChecksIfPointToPoint_thenCorrect() throws SocketException, UnknownHostException {
+ NetworkInterface nif = NetworkInterface.getByName("lo");
+ assertFalse(nif.isPointToPoint());
+ }
+
+ @Test
+ public void givenInterface_whenChecksIfVirtual_thenCorrect() throws SocketException, UnknownHostException {
+ NetworkInterface nif = NetworkInterface.getByName("lo");
+ assertFalse(nif.isVirtual());
+ }
+
+ @Test
+ public void givenInterface_whenChecksMulticastSupport_thenCorrect() throws SocketException, UnknownHostException {
+ NetworkInterface nif = NetworkInterface.getByName("lo");
+ assertTrue(nif.supportsMulticast());
+ }
+
+ @Test
+ public void givenInterface_whenGetsMacAddress_thenCorrect() throws SocketException, UnknownHostException {
+ NetworkInterface nif = NetworkInterface.getByName("lo");
+ byte[] bytes = nif.getHardwareAddress();
+ assertNotNull(bytes);
+ }
+
+ @Test
+ public void givenInterface_whenGetsMTU_thenCorrect() throws SocketException, UnknownHostException {
+ NetworkInterface nif = NetworkInterface.getByName("net0");
+ int mtu = nif.getMTU();
+ assertEquals(1500, mtu);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java
new file mode 100644
index 0000000000..aff851ae4b
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/networking/udp/UDPIntegrationTest.java
@@ -0,0 +1,38 @@
+package com.baeldung.java.networking.udp;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.IOException;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+
+public class UDPIntegrationTest {
+ private EchoClient client;
+
+ @Before
+ public void setup() throws IOException {
+ new EchoServer().start();
+ client = new EchoClient();
+ }
+
+ @Test
+ public void whenCanSendAndReceivePacket_thenCorrect1() {
+ String echo = client.sendEcho("hello server");
+ assertEquals("hello server", echo);
+ echo = client.sendEcho("server is working");
+ assertFalse(echo.equals("hello server"));
+ }
+
+ @After
+ public void tearDown() {
+ stopEchoServer();
+ client.close();
+ }
+
+ private void stopEchoServer() {
+ client.sendEcho("end");
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/java/networking/url/UrlUnitTest.java b/core-java/src/test/java/com/baeldung/java/networking/url/UrlUnitTest.java
new file mode 100644
index 0000000000..505d9595ab
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/networking/url/UrlUnitTest.java
@@ -0,0 +1,104 @@
+package com.baeldung.java.networking.url;
+
+import static org.junit.Assert.assertEquals;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.junit.Test;
+
+public class UrlUnitTest {
+
+ @Test
+ public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException {
+ final URL url = new URL("http://baeldung.com");
+ assertEquals("http", url.getProtocol());
+ }
+
+ @Test
+ public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException {
+ final URL url = new URL("http://baeldung.com");
+ assertEquals("baeldung.com", url.getHost());
+ }
+
+ @Test
+ public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException {
+ final URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
+ assertEquals("/articles?topic=java&version=8", url.getFile());
+ }
+
+ @Test
+ public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException {
+ final URL url = new URL("http://baeldung.com/guidelines.txt");
+ assertEquals("/guidelines.txt", url.getFile());
+ }
+
+ @Test
+ public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException {
+ final URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
+ assertEquals("/articles", url.getPath());
+ }
+
+ @Test
+ public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException {
+ final URL url = new URL("http://baeldung.com/articles?topic=java");
+ assertEquals("topic=java", url.getQuery());
+ }
+
+ @Test
+ public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException {
+ final URL url = new URL("http://baeldung.com");
+ assertEquals(-1, url.getPort());
+ assertEquals(80, url.getDefaultPort());
+ }
+
+ @Test
+ public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException {
+ final URL url = new URL("http://baeldung.com:8090");
+ assertEquals(8090, url.getPort());
+ assertEquals(80, url.getDefaultPort());
+ }
+
+ @Test
+ public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() throws MalformedURLException {
+ final URL baseUrl = new URL("http://baeldung.com");
+ final URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets");
+ assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
+ }
+
+ @Test
+ public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() throws MalformedURLException {
+ final URL baseUrl = new URL("http://baeldung.com");
+ final URL relativeUrl = new URL(baseUrl, "http://baeldung.com/a-guide-to-java-sockets");
+ assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
+ }
+
+ @Test
+ public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
+ final String protocol = "http";
+ final String host = "baeldung.com";
+ final String file = "/guidelines.txt";
+ final URL url = new URL(protocol, host, file);
+ assertEquals("http://baeldung.com/guidelines.txt", url.toString());
+ }
+
+ @Test
+ public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException {
+ final String protocol = "http";
+ final String host = "baeldung.com";
+ final String file = "/articles?topic=java&version=8";
+ final URL url = new URL(protocol, host, file);
+ assertEquals("http://baeldung.com/articles?topic=java&version=8", url.toString());
+ }
+
+ @Test
+ public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
+ final String protocol = "http";
+ final String host = "baeldung.com";
+ final int port = 9000;
+ final String file = "/guidelines.txt";
+ final URL url = new URL(protocol, host, port, file);
+ assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java b/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java
new file mode 100644
index 0000000000..fc64799578
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/nio/selector/NioEchoIntegrationTest.java
@@ -0,0 +1,35 @@
+package com.baeldung.java.nio.selector;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.IOException;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class NioEchoIntegrationTest {
+
+ Process server;
+ EchoClient client;
+
+ @Before
+ public void setup() throws IOException, InterruptedException {
+ server = EchoServer.start();
+ client = EchoClient.start();
+ }
+
+ @Test
+ public void givenServerClient_whenServerEchosMessage_thenCorrect() {
+ String resp1 = client.sendMessage("hello");
+ String resp2 = client.sendMessage("world");
+ assertEquals("hello", resp1);
+ assertEquals("world", resp2);
+ }
+
+ @After
+ public void teardown() throws IOException {
+ server.destroy();
+ EchoClient.stop();
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java b/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java
new file mode 100644
index 0000000000..64fbb4ae25
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/nio2/FileTest.java
@@ -0,0 +1,246 @@
+package com.baeldung.java.nio2;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.nio.file.DirectoryNotEmptyException;
+import java.nio.file.FileAlreadyExistsException;
+import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.util.UUID;
+
+import org.junit.Test;
+
+public class FileTest {
+ private static final String HOME = System.getProperty("user.home");
+
+ // checking file or dir
+ @Test
+ public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
+ Path p = Paths.get(HOME);
+ assertTrue(Files.exists(p));
+ }
+
+ @Test
+ public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() {
+ Path p = Paths.get(HOME + "/inexistent_file.txt");
+ assertTrue(Files.notExists(p));
+ }
+
+ @Test
+ public void givenDirPath_whenConfirmsNotRegularFile_thenCorrect() {
+ Path p = Paths.get(HOME);
+ assertFalse(Files.isRegularFile(p));
+ }
+
+ @Test
+ public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
+ Path p = Paths.get(HOME);
+ assertTrue(Files.isReadable(p));
+ }
+
+ @Test
+ public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
+ Path p = Paths.get(HOME);
+ assertTrue(Files.isWritable(p));
+ }
+
+ @Test
+ public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
+ Path p = Paths.get(HOME);
+ assertTrue(Files.isExecutable(p));
+ }
+
+ @Test
+ public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
+ Path p1 = Paths.get(HOME);
+ Path p2 = Paths.get(HOME);
+ assertTrue(Files.isSameFile(p1, p2));
+ }
+
+ // reading, writing and creating files
+ // creating file
+ @Test
+ public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
+ String fileName = "myfile_" + UUID.randomUUID().toString() + ".txt";
+ Path p = Paths.get(HOME + "/" + fileName);
+ assertFalse(Files.exists(p));
+ Files.createFile(p);
+ assertTrue(Files.exists(p));
+
+ }
+
+ @Test
+ public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
+ String dirName = "myDir_" + UUID.randomUUID().toString();
+ Path p = Paths.get(HOME + "/" + dirName);
+ assertFalse(Files.exists(p));
+ Files.createDirectory(p);
+ assertTrue(Files.exists(p));
+ assertFalse(Files.isRegularFile(p));
+ assertTrue(Files.isDirectory(p));
+
+ }
+
+ @Test(expected = NoSuchFileException.class)
+ public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
+ String dirName = "myDir_" + UUID.randomUUID().toString() + "/subdir";
+ Path p = Paths.get(HOME + "/" + dirName);
+ assertFalse(Files.exists(p));
+ Files.createDirectory(p);
+
+ }
+
+ @Test
+ public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
+ Path dir = Paths.get(HOME + "/myDir_" + UUID.randomUUID().toString());
+ Path subdir = dir.resolve("subdir");
+ assertFalse(Files.exists(dir));
+ assertFalse(Files.exists(subdir));
+ Files.createDirectories(subdir);
+ assertTrue(Files.exists(dir));
+ assertTrue(Files.exists(subdir));
+ }
+
+ @Test
+ public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException {
+ String prefix = "log_";
+ String suffix = ".txt";
+ Path p = Paths.get(HOME + "/");
+ p = Files.createTempFile(p, prefix, suffix);
+ // like log_8821081429012075286.txt
+ assertTrue(Files.exists(p));
+
+ }
+
+ @Test
+ public void givenPath_whenCreatesTempFileWithDefaults_thenCorrect() throws IOException {
+ Path p = Paths.get(HOME + "/");
+ p = Files.createTempFile(p, null, null);
+ // like 8600179353689423985.tmp
+ assertTrue(Files.exists(p));
+ }
+
+ @Test
+ public void givenNoFilePath_whenCreatesTempFileInTempDir_thenCorrect() throws IOException {
+ Path p = Files.createTempFile(null, null);
+ // like C:\Users\new\AppData\Local\Temp\6100927974988978748.tmp
+ assertTrue(Files.exists(p));
+
+ }
+
+ // delete file
+ @Test
+ public void givenPath_whenDeletes_thenCorrect() throws IOException {
+ Path p = Paths.get(HOME + "/fileToDelete.txt");
+ assertFalse(Files.exists(p));
+ Files.createFile(p);
+ assertTrue(Files.exists(p));
+ Files.delete(p);
+ assertFalse(Files.exists(p));
+
+ }
+
+ @Test(expected = DirectoryNotEmptyException.class)
+ public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
+ Path dir = Paths.get(HOME + "/emptyDir" + UUID.randomUUID().toString());
+ Files.createDirectory(dir);
+ assertTrue(Files.exists(dir));
+ Path file = dir.resolve("file.txt");
+ Files.createFile(file);
+ Files.delete(dir);
+
+ assertTrue(Files.exists(dir));
+
+ }
+
+ @Test(expected = NoSuchFileException.class)
+ public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
+ Path p = Paths.get(HOME + "/inexistentFile.txt");
+ assertFalse(Files.exists(p));
+ Files.delete(p);
+
+ }
+
+ @Test
+ public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException {
+ Path p = Paths.get(HOME + "/inexistentFile.txt");
+ assertFalse(Files.exists(p));
+ Files.deleteIfExists(p);
+
+ }
+
+ // copy file
+ @Test
+ public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
+ Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
+ Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
+ Files.createDirectory(dir1);
+ Files.createDirectory(dir2);
+ Path file1 = dir1.resolve("filetocopy.txt");
+ Path file2 = dir2.resolve("filetocopy.txt");
+ Files.createFile(file1);
+ assertTrue(Files.exists(file1));
+ assertFalse(Files.exists(file2));
+ Files.copy(file1, file2);
+ assertTrue(Files.exists(file2));
+
+ }
+
+ @Test(expected = FileAlreadyExistsException.class)
+ public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
+ Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
+ Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
+ Files.createDirectory(dir1);
+ Files.createDirectory(dir2);
+ Path file1 = dir1.resolve("filetocopy.txt");
+ Path file2 = dir2.resolve("filetocopy.txt");
+ Files.createFile(file1);
+ Files.createFile(file2);
+ assertTrue(Files.exists(file1));
+ assertTrue(Files.exists(file2));
+ Files.copy(file1, file2);
+ Files.copy(file1, file2, StandardCopyOption.REPLACE_EXISTING);
+ }
+
+ // moving files
+ @Test
+ public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
+ Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
+ Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
+ Files.createDirectory(dir1);
+ Files.createDirectory(dir2);
+ Path file1 = dir1.resolve("filetocopy.txt");
+ Path file2 = dir2.resolve("filetocopy.txt");
+ Files.createFile(file1);
+ assertTrue(Files.exists(file1));
+ assertFalse(Files.exists(file2));
+ Files.move(file1, file2);
+ assertTrue(Files.exists(file2));
+ assertFalse(Files.exists(file1));
+
+ }
+
+ @Test(expected = FileAlreadyExistsException.class)
+ public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
+ Path dir1 = Paths.get(HOME + "/firstdir_" + UUID.randomUUID().toString());
+ Path dir2 = Paths.get(HOME + "/otherdir_" + UUID.randomUUID().toString());
+ Files.createDirectory(dir1);
+ Files.createDirectory(dir2);
+ Path file1 = dir1.resolve("filetocopy.txt");
+ Path file2 = dir2.resolve("filetocopy.txt");
+ Files.createFile(file1);
+ Files.createFile(file2);
+ assertTrue(Files.exists(file1));
+ assertTrue(Files.exists(file2));
+ Files.move(file1, file2);
+ Files.move(file1, file2, StandardCopyOption.REPLACE_EXISTING);
+ assertTrue(Files.exists(file2));
+ assertFalse(Files.exists(file1));
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/java/nio2/PathManualTest.java b/core-java/src/test/java/com/baeldung/java/nio2/PathManualTest.java
new file mode 100644
index 0000000000..acfb2c08e9
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/nio2/PathManualTest.java
@@ -0,0 +1,195 @@
+package com.baeldung.java.nio2;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.net.URI;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Date;
+
+import org.junit.Test;
+
+public class PathManualTest {
+
+ private static final String HOME = System.getProperty("user.home");
+
+ // creating a path
+ @Test
+ public void givenPathString_whenCreatesPathObject_thenCorrect() {
+ Path p = Paths.get("/articles/baeldung");
+ assertEquals("\\articles\\baeldung", p.toString());
+
+ }
+
+ @Test
+ public void givenPathParts_whenCreatesPathObject_thenCorrect() {
+ Path p = Paths.get("/articles", "baeldung");
+ assertEquals("\\articles\\baeldung", p.toString());
+
+ }
+
+ // retrieving path info
+ @Test
+ public void givenPath_whenRetrievesFileName_thenCorrect() {
+ Path p = Paths.get("/articles/baeldung/logs");
+ assertEquals("logs", p.getFileName().toString());
+ }
+
+ @Test
+ public void givenPath_whenRetrievesNameByIndex_thenCorrect() {
+ Path p = Paths.get("/articles/baeldung/logs");
+ assertEquals("articles", p.getName(0).toString());
+ assertEquals("baeldung", p.getName(1).toString());
+ assertEquals("logs", p.getName(2).toString());
+ }
+
+ @Test
+ public void givenPath_whenCountsParts_thenCorrect() {
+ Path p = Paths.get("/articles/baeldung/logs");
+ assertEquals(3, p.getNameCount());
+ }
+
+ @Test
+ public void givenPath_whenCanRetrieveSubsequenceByIndex_thenCorrect() {
+ Path p = Paths.get("/articles/baeldung/logs");
+ assertEquals("articles", p.subpath(0, 1).toString());
+ assertEquals("articles\\baeldung", p.subpath(0, 2).toString());
+ assertEquals("articles\\baeldung\\logs", p.subpath(0, 3).toString());
+ assertEquals("baeldung", p.subpath(1, 2).toString());
+ assertEquals("baeldung\\logs", p.subpath(1, 3).toString());
+ assertEquals("logs", p.subpath(2, 3).toString());
+ }
+
+ @Test
+ public void givenPath_whenRetrievesParent_thenCorrect() {
+ Path p1 = Paths.get("/articles/baeldung/logs");
+ Path p2 = Paths.get("/articles/baeldung");
+ Path p3 = Paths.get("/articles");
+ Path p4 = Paths.get("/");
+
+ assertEquals("\\articles\\baeldung", p1.getParent().toString());
+ assertEquals("\\articles", p2.getParent().toString());
+ assertEquals("\\", p3.getParent().toString());
+ assertEquals(null, p4.getParent());
+ }
+
+ @Test
+ public void givenPath_whenRetrievesRoot_thenCorrect() {
+ Path p1 = Paths.get("/articles/baeldung/logs");
+ Path p2 = Paths.get("c:/articles/baeldung/logs");
+
+ assertEquals("\\", p1.getRoot().toString());
+ assertEquals("c:\\", p2.getRoot().toString());
+ }
+
+ // removing redundancies from path
+ @Test
+ public void givenPath_whenRemovesRedundancies_thenCorrect1() {
+ Path p = Paths.get("/home/./baeldung/articles");
+ p = p.normalize();
+ assertEquals("\\home\\baeldung\\articles", p.toString());
+ }
+
+ @Test
+ public void givenPath_whenRemovesRedundancies_thenCorrect2() {
+ Path p = Paths.get("/home/baeldung/../articles");
+ p = p.normalize();
+ assertEquals("\\home\\articles", p.toString());
+ }
+
+ // converting a path
+ @Test
+ public void givenPath_whenConvertsToBrowseablePath_thenCorrect() {
+ Path p = Paths.get("/home/baeldung/articles.html");
+ URI uri = p.toUri();
+ assertEquals("file:///E:/home/baeldung/articles.html", uri.toString());
+ }
+
+ @Test
+ public void givenPath_whenConvertsToAbsolutePath_thenCorrect() {
+ Path p = Paths.get("/home/baeldung/articles.html");
+ assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
+ }
+
+ @Test
+ public void givenAbsolutePath_whenRetainsAsAbsolute_thenCorrect() {
+ Path p = Paths.get("E:\\home\\baeldung\\articles.html");
+ assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
+ }
+
+ @Test
+ public void givenExistingPath_whenGetsRealPathToFile_thenCorrect() throws IOException {
+ Path p = Paths.get(HOME);
+ assertEquals(HOME, p.toRealPath().toString());
+ }
+
+ @Test(expected = NoSuchFileException.class)
+ public void givenInExistentPath_whenFailsToConvert_thenCorrect() throws IOException {
+ Path p = Paths.get("E:\\home\\baeldung\\articles.html");
+
+ p.toRealPath();
+ }
+
+ // joining paths
+ @Test
+ public void givenTwoPaths_whenJoinsAndResolves_thenCorrect() throws IOException {
+ Path p = Paths.get("/baeldung/articles");
+ assertEquals("\\baeldung\\articles\\java", p.resolve("java").toString());
+ }
+
+ @Test
+ public void givenAbsolutePath_whenResolutionRetainsIt_thenCorrect() throws IOException {
+ Path p = Paths.get("/baeldung/articles");
+ assertEquals("C:\\baeldung\\articles\\java", p.resolve("C:\\baeldung\\articles\\java").toString());
+ }
+
+ @Test
+ public void givenPathWithRoot_whenResolutionRetainsIt_thenCorrect2() throws IOException {
+ Path p = Paths.get("/baeldung/articles");
+ assertEquals("\\java", p.resolve("/java").toString());
+ }
+
+ // creating a path between 2 paths
+ @Test
+ public void givenSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
+ Path p1 = Paths.get("articles");
+ Path p2 = Paths.get("authors");
+ assertEquals("..\\authors", p1.relativize(p2).toString());
+ assertEquals("..\\articles", p2.relativize(p1).toString());
+ }
+
+ @Test
+ public void givenNonSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
+ Path p1 = Paths.get("/baeldung");
+ Path p2 = Paths.get("/baeldung/authors/articles");
+ assertEquals("authors\\articles", p1.relativize(p2).toString());
+ assertEquals("..\\..", p2.relativize(p1).toString());
+ }
+
+ // comparing 2 paths
+ @Test
+ public void givenTwoPaths_whenTestsEquality_thenCorrect() throws IOException {
+ Path p1 = Paths.get("/baeldung/articles");
+ Path p2 = Paths.get("/baeldung/articles");
+ Path p3 = Paths.get("/baeldung/authors");
+
+ assertTrue(p1.equals(p2));
+ assertFalse(p1.equals(p3));
+ }
+
+ @Test
+ public void givenPath_whenInspectsStart_thenCorrect() {
+ Path p1 = Paths.get("/baeldung/articles");
+ assertTrue(p1.startsWith("/baeldung"));
+ }
+
+ @Test
+ public void givenPath_whenInspectsEnd_thenCorrect() {
+ Path p1 = Paths.get("/baeldung/articles");
+ assertTrue(p1.endsWith("articles"));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java
new file mode 100644
index 0000000000..0c090901e7
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/reflection/ReflectionUnitTest.java
@@ -0,0 +1,302 @@
+package com.baeldung.java.reflection;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ReflectionUnitTest {
+
+ @Test
+ public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() {
+ final Object person = new Person();
+ final Field[] fields = person.getClass().getDeclaredFields();
+
+ final List actualFieldNames = getFieldNames(fields);
+
+ assertTrue(Arrays.asList("name", "age").containsAll(actualFieldNames));
+ }
+
+ @Test
+ public void givenObject_whenGetsClassName_thenCorrect() {
+ final Object goat = new Goat("goat");
+ final 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 {
+ final 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 {
+ final Class> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
+ final Class> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
+ final int goatMods = goatClass.getModifiers();
+ final int animalMods = animalClass.getModifiers();
+
+ assertTrue(Modifier.isPublic(goatMods));
+ assertTrue(Modifier.isAbstract(animalMods));
+ assertTrue(Modifier.isPublic(animalMods));
+ }
+
+ @Test
+ public void givenClass_whenGetsPackageInfo_thenCorrect() {
+ final Goat goat = new Goat("goat");
+ final Class> goatClass = goat.getClass();
+ final Package pkg = goatClass.getPackage();
+
+ assertEquals("com.baeldung.java.reflection", pkg.getName());
+ }
+
+ @Test
+ public void givenClass_whenGetsSuperClass_thenCorrect() {
+ final Goat goat = new Goat("goat");
+ final String str = "any string";
+
+ final Class> goatClass = goat.getClass();
+ final Class> goatSuperClass = goatClass.getSuperclass();
+
+ assertEquals("Animal", goatSuperClass.getSimpleName());
+ assertEquals("Object", str.getClass().getSuperclass().getSimpleName());
+
+ }
+
+ @Test
+ public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException {
+ final Class> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
+ final Class> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
+ final Class>[] goatInterfaces = goatClass.getInterfaces();
+ final 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 {
+ final Class> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
+ final 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 {
+ final Class> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
+ final Field[] fields = animalClass.getDeclaredFields();
+
+ final List actualFields = getFieldNames(fields);
+
+ assertEquals(2, actualFields.size());
+ assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY")));
+ }
+
+ @Test
+ public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException {
+ final Class> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
+ final Method[] methods = animalClass.getDeclaredMethods();
+ final List actualMethods = getMethodNames(methods);
+
+ assertEquals(3, actualMethods.size());
+ assertTrue(actualMethods.containsAll(Arrays.asList("getName", "setName", "getSound")));
+ }
+
+ @Test
+ public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException {
+ final Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ final Constructor>[] constructors = birdClass.getConstructors();
+
+ assertEquals(3, constructors.length);
+ }
+
+ @Test
+ public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception {
+ final Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ birdClass.getConstructor();
+ birdClass.getConstructor(String.class);
+ birdClass.getConstructor(String.class, boolean.class);
+ }
+
+ @Test
+ public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception {
+ final Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+
+ final Constructor> cons1 = birdClass.getConstructor();
+ final Constructor> cons2 = birdClass.getConstructor(String.class);
+ final Constructor> cons3 = birdClass.getConstructor(String.class, boolean.class);
+
+ final Bird bird1 = (Bird) cons1.newInstance();
+ final Bird bird2 = (Bird) cons2.newInstance("Weaver bird");
+ final 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 {
+ final Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ final Field[] fields = birdClass.getFields();
+ assertEquals(1, fields.length);
+ assertEquals("CATEGORY", fields[0].getName());
+
+ }
+
+ @Test
+ public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception {
+ final Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ final Field field = birdClass.getField("CATEGORY");
+ assertEquals("CATEGORY", field.getName());
+
+ }
+
+ @Test
+ public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException {
+ final Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ final Field[] fields = birdClass.getDeclaredFields();
+ assertEquals(1, fields.length);
+ assertEquals("walks", fields[0].getName());
+ }
+
+ @Test
+ public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception {
+ final Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ final Field field = birdClass.getDeclaredField("walks");
+ assertEquals("walks", field.getName());
+
+ }
+
+ @Test
+ public void givenClassField_whenGetsType_thenCorrect() throws Exception {
+ final Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks");
+ final Class> fieldClass = field.getType();
+ assertEquals("boolean", fieldClass.getSimpleName());
+ }
+
+ @Test
+ public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception {
+ final Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ final Bird bird = (Bird) birdClass.newInstance();
+ final 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 {
+ final Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ final Field field = birdClass.getField("CATEGORY");
+ field.setAccessible(true);
+
+ assertEquals("domestic", field.get(null));
+ }
+
+ @Test
+ public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException {
+ final Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ final Method[] methods = birdClass.getMethods();
+ final List methodNames = getMethodNames(methods);
+
+ assertTrue(methodNames.containsAll(Arrays.asList("equals", "notifyAll", "hashCode", "walks", "eats", "toString")));
+
+ }
+
+ @Test
+ public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException {
+ final Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ final List actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
+
+ final 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 {
+ final Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ final Method walksMethod = birdClass.getDeclaredMethod("walks");
+ final 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 {
+ final Class> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
+ final Bird bird = (Bird) birdClass.newInstance();
+ final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
+ final Method walksMethod = birdClass.getDeclaredMethod("walks");
+ final boolean walks = (boolean) walksMethod.invoke(bird);
+
+ assertFalse(walks);
+ assertFalse(bird.walks());
+
+ setWalksMethod.invoke(bird, true);
+ final boolean walks2 = (boolean) walksMethod.invoke(bird);
+
+ assertTrue(walks2);
+ assertTrue(bird.walks());
+
+ }
+
+ private static List getFieldNames(Field[] fields) {
+ final List fieldNames = new ArrayList<>();
+ for (final Field field : fields) {
+ fieldNames.add(field.getName());
+ }
+ return fieldNames;
+
+ }
+
+ private static List getMethodNames(Method[] methods) {
+ final List methodNames = new ArrayList<>();
+ for (final Method method : methods) {
+ methodNames.add(method.getName());
+ }
+ return methodNames;
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java b/core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java
new file mode 100644
index 0000000000..e4ea55aae3
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/regex/RegexUnitTest.java
@@ -0,0 +1,501 @@
+package com.baeldung.java.regex;
+
+import static org.junit.Assert.*;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.junit.Test;
+
+public class RegexUnitTest {
+ private static Pattern pattern;
+ private static Matcher matcher;
+
+ @Test
+ public void givenText_whenSimpleRegexMatches_thenCorrect() {
+ Pattern pattern = Pattern.compile("foo");
+ Matcher matcher = pattern.matcher("foo");
+ assertTrue(matcher.find());
+ }
+
+ @Test
+ public void givenText_whenSimpleRegexMatchesTwice_thenCorrect() {
+ Pattern pattern = Pattern.compile("foo");
+ Matcher matcher = pattern.matcher("foofoo");
+ int matches = 0;
+ while (matcher.find())
+ matches++;
+ assertEquals(matches, 2);
+
+ }
+
+ @Test
+ public void givenText_whenMatchesWithDotMetach_thenCorrect() {
+ int matches = runTest(".", "foo");
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenRepeatedText_whenMatchesOnceWithDotMetach_thenCorrect() {
+ int matches = runTest("foo.", "foofoo");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
+ }
+
+ @Test
+ public void givenORSet_whenMatchesAny_thenCorrect() {
+ int matches = runTest("[abc]", "b");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
+ }
+
+ @Test
+ public void givenORSet_whenMatchesAnyAndAll_thenCorrect() {
+ int matches = runTest("[abc]", "cab");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
+ }
+
+ @Test
+ public void givenORSet_whenMatchesAllCombinations_thenCorrect() {
+ int matches = runTest("[bcr]at", "bat cat rat");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
+ }
+
+ @Test
+ public void givenNORSet_whenMatchesNon_thenCorrect() {
+ int matches = runTest("[^abc]", "g");
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenNORSet_whenMatchesAllExceptElements_thenCorrect() {
+ int matches = runTest("[^bcr]at", "sat mat eat");
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenUpperCaseRange_whenMatchesUpperCase_thenCorrect() {
+ int matches = runTest("[A-Z]", "Two Uppercase alphabets 34 overall");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
+ }
+
+ @Test
+ public void givenLowerCaseRange_whenMatchesLowerCase_thenCorrect() {
+ int matches = runTest("[a-z]", "Two Uppercase alphabets 34 overall");
+ assertTrue(matches > 0);
+ assertEquals(matches, 26);
+ }
+
+ @Test
+ public void givenBothLowerAndUpperCaseRange_whenMatchesAllLetters_thenCorrect() {
+ int matches = runTest("[a-zA-Z]", "Two Uppercase alphabets 34 overall");
+ assertTrue(matches > 0);
+ assertEquals(matches, 28);
+ }
+
+ @Test
+ public void givenNumberRange_whenMatchesAccurately_thenCorrect() {
+ int matches = runTest("[1-5]", "Two Uppercase alphabets 34 overall");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
+ }
+
+ @Test
+ public void givenNumberRange_whenMatchesAccurately_thenCorrect2() {
+ int matches = runTest("[30-35]", "Two Uppercase alphabets 34 overall");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
+ }
+
+ @Test
+ public void givenTwoSets_whenMatchesUnion_thenCorrect() {
+ int matches = runTest("[1-3[7-9]]", "123456789");
+ assertTrue(matches > 0);
+ assertEquals(matches, 6);
+ }
+
+ @Test
+ public void givenTwoSets_whenMatchesIntersection_thenCorrect() {
+ int matches = runTest("[1-6&&[3-9]]", "123456789");
+ assertTrue(matches > 0);
+ assertEquals(matches, 4);
+ }
+
+ @Test
+ public void givenSetWithSubtraction_whenMatchesAccurately_thenCorrect() {
+ int matches = runTest("[0-9&&[^2468]]", "123456789");
+ assertTrue(matches > 0);
+ assertEquals(matches, 5);
+ }
+
+ @Test
+ public void givenDigits_whenMatches_thenCorrect() {
+ int matches = runTest("\\d", "123");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
+ }
+
+ @Test
+ public void givenNonDigits_whenMatches_thenCorrect() {
+ int matches = runTest("\\D", "a6c");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
+ }
+
+ @Test
+ public void givenWhiteSpace_whenMatches_thenCorrect() {
+ int matches = runTest("\\s", "a c");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
+ }
+
+ @Test
+ public void givenNonWhiteSpace_whenMatches_thenCorrect() {
+ int matches = runTest("\\S", "a c");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
+ }
+
+ @Test
+ public void givenWordCharacter_whenMatches_thenCorrect() {
+ int matches = runTest("\\w", "hi!");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
+ }
+
+ @Test
+ public void givenNonWordCharacter_whenMatches_thenCorrect() {
+ int matches = runTest("\\W", "hi!");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
+ }
+
+ @Test
+ public void givenZeroOrOneQuantifier_whenMatches_thenCorrect() {
+ int matches = runTest("\\a?", "hi");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
+ }
+
+ @Test
+ public void givenZeroOrOneQuantifier_whenMatches_thenCorrect2() {
+ int matches = runTest("\\a{0,1}", "hi");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
+ }
+
+ @Test
+ public void givenZeroOrManyQuantifier_whenMatches_thenCorrect() {
+ int matches = runTest("\\a*", "hi");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
+ }
+
+ @Test
+ public void givenZeroOrManyQuantifier_whenMatches_thenCorrect2() {
+ int matches = runTest("\\a{0,}", "hi");
+ assertTrue(matches > 0);
+ assertEquals(matches, 3);
+ }
+
+ @Test
+ public void givenOneOrManyQuantifier_whenMatches_thenCorrect() {
+ int matches = runTest("\\a+", "hi");
+ assertFalse(matches > 0);
+ }
+
+ @Test
+ public void givenOneOrManyQuantifier_whenMatches_thenCorrect2() {
+ int matches = runTest("\\a{1,}", "hi");
+ assertFalse(matches > 0);
+ }
+
+ @Test
+ public void givenBraceQuantifier_whenMatches_thenCorrect() {
+ int matches = runTest("a{3}", "aaaaaa");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
+ }
+
+ @Test
+ public void givenBraceQuantifier_whenFailsToMatch_thenCorrect() {
+ int matches = runTest("a{3}", "aa");
+ assertFalse(matches > 0);
+ }
+
+ @Test
+ public void givenBraceQuantifierWithRange_whenMatches_thenCorrect() {
+ int matches = runTest("a{2,3}", "aaaa");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
+ }
+
+ @Test
+ public void givenBraceQuantifierWithRange_whenMatchesLazily_thenCorrect() {
+ int matches = runTest("a{2,3}?", "aaaa");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
+ }
+
+ @Test
+ public void givenCapturingGroup_whenMatches_thenCorrect() {
+ int matches = runTest("(\\d\\d)", "12");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
+ }
+
+ @Test
+ public void givenCapturingGroup_whenMatches_thenCorrect2() {
+ int matches = runTest("(\\d\\d)", "1212");
+ assertTrue(matches > 0);
+ assertEquals(matches, 2);
+ }
+
+ @Test
+ public void givenCapturingGroup_whenMatches_thenCorrect3() {
+ int matches = runTest("(\\d\\d)(\\d\\d)", "1212");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
+ }
+
+ @Test
+ public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect() {
+ int matches = runTest("(\\d\\d)\\1", "1212");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
+ }
+
+ @Test
+ public void givenCapturingGroup_whenMatchesWithBackReference_thenCorrect2() {
+ int matches = runTest("(\\d\\d)\\1\\1\\1", "12121212");
+ assertTrue(matches > 0);
+ assertEquals(matches, 1);
+ }
+
+ @Test
+ public void givenCapturingGroupAndWrongInput_whenMatchFailsWithBackReference_thenCorrect() {
+ int matches = runTest("(\\d\\d)\\1", "1213");
+ assertFalse(matches > 0);
+ }
+
+ @Test
+ public void givenText_whenMatchesAtBeginning_thenCorrect() {
+ int matches = runTest("^dog", "dogs are friendly");
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenTextAndWrongInput_whenMatchFailsAtBeginning_thenCorrect() {
+ int matches = runTest("^dog", "are dogs are friendly?");
+ assertFalse(matches > 0);
+ }
+
+ @Test
+ public void givenText_whenMatchesAtEnd_thenCorrect() {
+ int matches = runTest("dog$", "Man's best friend is a dog");
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenTextAndWrongInput_whenMatchFailsAtEnd_thenCorrect() {
+ int matches = runTest("dog$", "is a dog man's best friend?");
+ assertFalse(matches > 0);
+ }
+
+ @Test
+ public void givenText_whenMatchesAtWordBoundary_thenCorrect() {
+ int matches = runTest("\\bdog\\b", "a dog is friendly");
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenText_whenMatchesAtWordBoundary_thenCorrect2() {
+ int matches = runTest("\\bdog\\b", "dog is man's best friend");
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenWrongText_whenMatchFailsAtWordBoundary_thenCorrect() {
+ int matches = runTest("\\bdog\\b", "snoop dogg is a rapper");
+ assertFalse(matches > 0);
+ }
+
+ @Test
+ public void givenText_whenMatchesAtWordAndNonBoundary_thenCorrect() {
+ int matches = runTest("\\bdog\\B", "snoop dogg is a rapper");
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenRegexWithoutCanonEq_whenMatchFailsOnEquivalentUnicode_thenCorrect() {
+ int matches = runTest("\u00E9", "\u0065\u0301");
+ assertFalse(matches > 0);
+ }
+
+ @Test
+ public void givenRegexWithCanonEq_whenMatchesOnEquivalentUnicode_thenCorrect() {
+ int matches = runTest("\u00E9", "\u0065\u0301", Pattern.CANON_EQ);
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenRegexWithDefaultMatcher_whenMatchFailsOnDifferentCases_thenCorrect() {
+ int matches = runTest("dog", "This is a Dog");
+ assertFalse(matches > 0);
+ }
+
+ @Test
+ public void givenRegexWithCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
+ int matches = runTest("dog", "This is a Dog", Pattern.CASE_INSENSITIVE);
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenRegexWithEmbeddedCaseInsensitiveMatcher_whenMatchesOnDifferentCases_thenCorrect() {
+ int matches = runTest("(?i)dog", "This is a Dog");
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenRegexWithComments_whenMatchFailsWithoutFlag_thenCorrect() {
+ int matches = runTest("dog$ #check for word dog at end of text", "This is a dog");
+ assertFalse(matches > 0);
+ }
+
+ @Test
+ public void givenRegexWithComments_whenMatchesWithFlag_thenCorrect() {
+ int matches = runTest("dog$ #check for word dog at end of text", "This is a dog", Pattern.COMMENTS);
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenRegexWithComments_whenMatchesWithEmbeddedFlag_thenCorrect() {
+ int matches = runTest("(?x)dog$ #check for word dog at end of text", "This is a dog");
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenRegexWithLineTerminator_whenMatchFails_thenCorrect() {
+ Pattern pattern = Pattern.compile("(.*)");
+ Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
+ matcher.find();
+ assertEquals("this is a text", matcher.group(1));
+ }
+
+ @Test
+ public void givenRegexWithLineTerminator_whenMatchesWithDotall_thenCorrect() {
+ Pattern pattern = Pattern.compile("(.*)", Pattern.DOTALL);
+ Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
+ matcher.find();
+ assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1));
+ }
+
+ @Test
+ public void givenRegexWithLineTerminator_whenMatchesWithEmbeddedDotall_thenCorrect() {
+ Pattern pattern = Pattern.compile("(?s)(.*)");
+ Matcher matcher = pattern.matcher("this is a text" + System.getProperty("line.separator") + " continued on another line");
+ matcher.find();
+ assertEquals("this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1));
+ }
+
+ @Test
+ public void givenRegex_whenMatchesWithoutLiteralFlag_thenCorrect() {
+ int matches = runTest("(.*)", "text");
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenRegex_whenMatchFailsWithLiteralFlag_thenCorrect() {
+ int matches = runTest("(.*)", "text", Pattern.LITERAL);
+ assertFalse(matches > 0);
+ }
+
+ @Test
+ public void givenRegex_whenMatchesWithLiteralFlag_thenCorrect() {
+ int matches = runTest("(.*)", "text(.*)", Pattern.LITERAL);
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenRegex_whenMatchFailsWithoutMultilineFlag_thenCorrect() {
+ int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
+ assertFalse(matches > 0);
+ }
+
+ @Test
+ public void givenRegex_whenMatchesWithMultilineFlag_thenCorrect() {
+ int matches = runTest("dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox", Pattern.MULTILINE);
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenRegex_whenMatchesWithEmbeddedMultilineFlag_thenCorrect() {
+ int matches = runTest("(?m)dog$", "This is a dog" + System.getProperty("line.separator") + "this is a fox");
+ assertTrue(matches > 0);
+ }
+
+ @Test
+ public void givenMatch_whenGetsIndices_thenCorrect() {
+ Pattern pattern = Pattern.compile("dog");
+ Matcher matcher = pattern.matcher("This dog is mine");
+ matcher.find();
+ assertEquals(5, matcher.start());
+ assertEquals(8, matcher.end());
+ }
+
+ @Test
+ public void whenStudyMethodsWork_thenCorrect() {
+ Pattern pattern = Pattern.compile("dog");
+ Matcher matcher = pattern.matcher("dogs are friendly");
+ assertTrue(matcher.lookingAt());
+ assertFalse(matcher.matches());
+
+ }
+
+ @Test
+ public void whenMatchesStudyMethodWorks_thenCorrect() {
+ Pattern pattern = Pattern.compile("dog");
+ Matcher matcher = pattern.matcher("dog");
+ assertTrue(matcher.matches());
+
+ }
+
+ @Test
+ public void whenReplaceFirstWorks_thenCorrect() {
+ Pattern pattern = Pattern.compile("dog");
+ Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly");
+ String newStr = matcher.replaceFirst("cat");
+ assertEquals("cats are domestic animals, dogs are friendly", newStr);
+
+ }
+
+ @Test
+ public void whenReplaceAllWorks_thenCorrect() {
+ Pattern pattern = Pattern.compile("dog");
+ Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly");
+ String newStr = matcher.replaceAll("cat");
+ assertEquals("cats are domestic animals, cats are friendly", newStr);
+
+ }
+
+ public synchronized static int runTest(String regex, String text) {
+ pattern = Pattern.compile(regex);
+ matcher = pattern.matcher(text);
+ int matches = 0;
+ while (matcher.find())
+ matches++;
+ return matches;
+ }
+
+ public synchronized static int runTest(String regex, String text, int flags) {
+ pattern = Pattern.compile(regex, flags);
+ matcher = pattern.matcher(text);
+ int matches = 0;
+ while (matcher.find())
+ matches++;
+ return matches;
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java
rename to core-java/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java b/core-java/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsUnitTest.java
similarity index 93%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java
rename to core-java/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsUnitTest.java
index 21a5e34b9b..5b07b3e3ae 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java
+++ b/core-java/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsUnitTest.java
@@ -6,7 +6,7 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals;
-public class Java8DefaultStaticIntefaceMethodsTest {
+public class Java8DefaultStaticIntefaceMethodsUnitTest {
@Test
public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() {
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java b/core-java/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java
similarity index 83%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java
rename to core-java/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java
index 581ccec182..41eb864fd9 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java
+++ b/core-java/src/test/java/com/baeldung/java8/Java8ExecutorServiceIntegrationTest.java
@@ -1,17 +1,26 @@
package com.baeldung.java8;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
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 {
+public class Java8ExecutorServiceIntegrationTest {
private Runnable runnableTask;
private Callable callableTask;
@@ -53,9 +62,7 @@ public class Java8ExecutorServiceTest {
@Test
public void creationSubmittingTasksShuttingDownNow_whenShutDownAfterAwating_thenCorrect() {
- ExecutorService threadPoolExecutor =
- new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue<>());
+ ExecutorService threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
for (int i = 0; i < 100; i++) {
threadPoolExecutor.submit(callableTask);
@@ -138,8 +145,7 @@ public class Java8ExecutorServiceTest {
@Test
public void submittingTaskScheduling_whenExecuted_thenCorrect() {
- ScheduledExecutorService executorService = Executors
- .newSingleThreadScheduledExecutor();
+ ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
Future resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS);
String result = null;
diff --git a/core-java/src/test/java/com/baeldung/java8/Java8ForEachTest.java b/core-java/src/test/java/com/baeldung/java8/Java8ForEachTest.java
new file mode 100644
index 0000000000..d9b0aa9d98
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java8/Java8ForEachTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.java8;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Consumer;
+
+import org.junit.Test;
+
+public class Java8ForEachTest {
+
+ @Test
+ public void compareForEachMethods_thenPrintResults() {
+
+ List names = new ArrayList<>();
+ names.add("Larry");
+ names.add("Steve");
+ names.add("James");
+ names.add("Conan");
+ names.add("Ellen");
+
+ // Java 5 - for-loop
+ System.out.println("--- Enhanced for-loop ---");
+ for (String name : names) {
+ System.out.println(name);
+ }
+
+ // Java 8 - forEach
+ System.out.println("--- forEach method ---");
+ names.forEach(name -> System.out.println(name));
+
+ // Anonymous inner class that implements Consumer interface
+ System.out.println("--- Anonymous inner class ---");
+ names.forEach(new Consumer() {
+ public void accept(String name) {
+ System.out.println(name);
+ }
+ });
+
+ // Create a Consumer implementation to then use in a forEach method
+ Consumer consumerNames = name -> {
+ System.out.println(name);
+ };
+ System.out.println("--- Implementation of Consumer interface ---");
+ names.forEach(consumerNames);
+
+ // Print elements using a Method Reference
+ System.out.println("--- Method Reference ---");
+ names.forEach(System.out::println);
+
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java b/core-java/src/test/java/com/baeldung/java8/Java8ForkJoinIntegrationTest.java
similarity index 94%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java
rename to core-java/src/test/java/com/baeldung/java8/Java8ForkJoinIntegrationTest.java
index 273b2d78db..6778fd782b 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java
+++ b/core-java/src/test/java/com/baeldung/java8/Java8ForkJoinIntegrationTest.java
@@ -1,18 +1,20 @@
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 static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
-import static org.junit.Assert.*;
+import org.junit.Before;
+import org.junit.Test;
-public class Java8ForkJoinTest {
+import com.baeldung.forkjoin.CustomRecursiveAction;
+import com.baeldung.forkjoin.CustomRecursiveTask;
+import com.baeldung.forkjoin.util.PoolUtil;
+
+public class Java8ForkJoinIntegrationTest {
private int[] arr;
private CustomRecursiveTask customRecursiveTask;
@@ -27,28 +29,23 @@ public class Java8ForkJoinTest {
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
@@ -63,7 +60,6 @@ public class Java8ForkJoinTest {
@Test
public void executeRecursiveTask_whenExecuted_thenCorrect() {
-
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
forkJoinPool.execute(customRecursiveTask);
@@ -73,12 +69,10 @@ public class Java8ForkJoinTest {
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);
@@ -95,6 +89,6 @@ public class Java8ForkJoinTest {
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/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasUnitTest.java
similarity index 98%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java
rename to core-java/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasUnitTest.java
index faaf3ae407..13ddcc805f 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java
+++ b/core-java/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasUnitTest.java
@@ -11,7 +11,7 @@ import java.util.function.Function;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
-public class Java8FunctionalInteracesLambdasTest {
+public class Java8FunctionalInteracesLambdasUnitTest {
private UseFoo useFoo;
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java b/core-java/src/test/java/com/baeldung/java8/Java8MethodReferenceUnitTest.java
similarity index 97%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java
rename to core-java/src/test/java/com/baeldung/java8/Java8MethodReferenceUnitTest.java
index d9d88c5052..2dc1fe18e6 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java
+++ b/core-java/src/test/java/com/baeldung/java8/Java8MethodReferenceUnitTest.java
@@ -12,7 +12,7 @@ import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-public class Java8MethodReferenceTest {
+public class Java8MethodReferenceUnitTest {
private List list;
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java b/core-java/src/test/java/com/baeldung/java8/Java8OptionalUnitTest.java
similarity index 80%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java
rename to core-java/src/test/java/com/baeldung/java8/Java8OptionalUnitTest.java
index 26de39bc0e..c6d5836387 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java
+++ b/core-java/src/test/java/com/baeldung/java8/Java8OptionalUnitTest.java
@@ -1,16 +1,23 @@
package com.baeldung.java8;
-import com.baeldung.java_8_features.*;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
-import static org.junit.Assert.*;
+import org.junit.Before;
+import org.junit.Test;
-public class Java8OptionalTest {
+import com.baeldung.java_8_features.Address;
+import com.baeldung.java_8_features.CustomException;
+import com.baeldung.java_8_features.OptionalAddress;
+import com.baeldung.java_8_features.OptionalUser;
+import com.baeldung.java_8_features.User;
+
+public class Java8OptionalUnitTest {
private List list;
@@ -32,7 +39,6 @@ public class Java8OptionalTest {
@Test
public void checkOptional_whenAsExpected_thenCorrect() {
-
Optional optionalEmpty = Optional.empty();
assertFalse(optionalEmpty.isPresent());
@@ -52,27 +58,19 @@ public class Java8OptionalTest {
assertTrue(listOptNull.isEmpty());
Optional user = Optional.ofNullable(getUser());
- String result = user.map(User::getAddress)
- .map(Address::getStreet)
- .orElse("not specified");
+ 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");
+ 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");
+ 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");
+ String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified");
assertEquals(resultOptNull, "not specified");
}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
rename to core-java/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java b/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java
similarity index 71%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java
rename to core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java
index 37326c6d26..73a10a57f4 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java
+++ b/core-java/src/test/java/com/baeldung/java8/Java8StreamApiUnitTest.java
@@ -17,28 +17,24 @@ import java.util.stream.*;
import static org.junit.Assert.*;
-public class Java8StreamApiTest {
+public class Java8StreamApiUnitTest {
private long counter;
- private static Logger log = LoggerFactory.getLogger(Java8StreamApiTest.class);
+ private static Logger log = LoggerFactory.getLogger(Java8StreamApiUnitTest.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"));
+ 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();
+ long size = list.stream().skip(1).map(element -> element.substring(0, 3)).count();
assertEquals(list.size() - 1, size);
}
@@ -48,11 +44,10 @@ public class Java8StreamApiTest {
List list = Arrays.asList("abc1", "abc2", "abc3");
counter = 0;
- long sizeFirst = list.stream()
- .skip(2).map(element -> {
- wasCalled();
- return element.substring(0, 3);
- }).count();
+ long sizeFirst = list.stream().skip(2).map(element -> {
+ wasCalled();
+ return element.substring(0, 3);
+ }).count();
assertEquals(1, counter);
counter = 0;
@@ -84,7 +79,7 @@ public class Java8StreamApiTest {
Stream streamOfArray = Stream.of("a", "b", "c");
assertEquals(3, streamOfArray.count());
- String[] arr = new String[]{"a", "b", "c"};
+ String[] arr = new String[] { "a", "b", "c" };
Stream streamOfArrayPart = Arrays.stream(arr, 1, 3);
assertEquals(2, streamOfArrayPart.count());
@@ -112,7 +107,7 @@ public class Java8StreamApiTest {
}
assertEquals("a", streamOfStrings.findFirst().get());
- Stream streamBuilder = Stream.builder().add("a").add("b").add("c").build();
+ Stream streamBuilder = Stream. builder().add("a").add("b").add("c").build();
assertEquals(3, streamBuilder.count());
Stream streamGenerated = Stream.generate(() -> "element").limit(10);
@@ -126,14 +121,13 @@ public class Java8StreamApiTest {
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();
+ 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
@@ -145,32 +139,28 @@ public class Java8StreamApiTest {
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;
- });
+ 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;
- });
+ 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());
+ 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(", ", "[", "]"));
+ String listToString = productList.stream().map(Product::getName).collect(Collectors.joining(", ", "[", "]"));
assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
@@ -180,36 +170,29 @@ public class Java8StreamApiTest {
int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
assertEquals(86, summingPrice);
- IntSummaryStatistics statistics = productList.stream()
- .collect(Collectors.summarizingInt(Product::getPrice));
+ IntSummaryStatistics statistics = productList.stream().collect(Collectors.summarizingInt(Product::getPrice));
assertEquals(23, statistics.getMax());
- Map> collectorMapOfLists = productList.stream()
- .collect(Collectors.groupingBy(Product::getPrice));
+ 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));
+ 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));
+ 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;
- });
+ 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));
@@ -219,23 +202,20 @@ public class Java8StreamApiTest {
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);
+ 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);
+ 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 intStreamParallel = IntStream.range(1, 150).parallel().map(element -> element * 34);
IntStream intStreamSequential = intStreamParallel.sequential();
boolean isParallel = intStreamParallel.isParallel();
assertFalse(isParallel);
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java b/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java
similarity index 87%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java
rename to core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java
index 1f1dda49ce..e40f9f9506 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java
+++ b/core-java/src/test/java/com/baeldung/java8/Java8StreamsUnitTest.java
@@ -14,7 +14,7 @@ import java.util.stream.Stream;
import static org.junit.Assert.*;
-public class Java8StreamsTest {
+public class Java8StreamsUnitTest {
private List list;
@@ -36,7 +36,7 @@ public class Java8StreamsTest {
@Test
public void checkStreamCount_whenCreating_givenDifferentSources() {
- String[] arr = new String[]{"a", "b", "c"};
+ String[] arr = new String[] { "a", "b", "c" };
Stream streamArr = Arrays.stream(arr);
assertEquals(streamArr.count(), 3);
@@ -47,14 +47,12 @@ public class Java8StreamsTest {
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<>();
@@ -65,12 +63,10 @@ public class Java8StreamsTest {
List details = new ArrayList<>();
details.add(new Detail());
details.add(new Detail());
- Stream streamFlatMap = details.stream()
- .flatMap(detail -> detail.getParts().stream());
+ 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"));
@@ -81,7 +77,6 @@ public class Java8StreamsTest {
assertFalse(isValidTwo);
}
-
@Test
public void checkStreamReducedValue_whenOperationReduce_thenCorrect() {
List integers = new ArrayList<>();
@@ -94,20 +89,17 @@ public class Java8StreamsTest {
@Test
public void checkStreamContains_whenOperationCollect_thenCorrect() {
- List resultList = list.stream()
- .map(element -> element.toUpperCase())
- .collect(Collectors.toList());
+ 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
+ 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/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java
similarity index 72%
rename from core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java
rename to core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java
index efd548a4b1..1f3b380772 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java
+++ b/core-java/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java
@@ -1,43 +1,43 @@
package com.baeldung.java8;
-import org.apache.commons.io.FileUtils;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
-import java.nio.file.*;
+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.attribute.BasicFileAttributes;
import java.text.DecimalFormat;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.StreamSupport;
-import static org.junit.Assert.assertEquals;
-
-public class JavaFolderSizeTest {
+import org.apache.commons.io.FileUtils;
+import org.junit.Before;
+import org.junit.Test;
+public class JavaFolderSizeUnitTest {
+ private final long EXPECTED_SIZE = 24;
private String path;
@Before
public void init() {
final String separator = File.separator;
- path = "src" + separator + "test" + separator + "resources";
+ path = String.format("src%stest%sresources%stestFolder", separator, separator, separator);
}
@Test
public void whenGetFolderSizeRecursive_thenCorrect() {
- final long expectedSize = 136;
-
final File folder = new File(path);
final long size = getFolderSize(folder);
- assertEquals(expectedSize, size);
+ assertEquals(EXPECTED_SIZE, size);
}
@Test
public void whenGetFolderSizeUsingJava7_thenCorrect() throws IOException {
- final long expectedSize = 136;
-
final AtomicLong size = new AtomicLong(0);
final Path folder = Paths.get(path);
@@ -49,39 +49,33 @@ public class JavaFolderSizeTest {
}
});
- assertEquals(expectedSize, size.longValue());
+ assertEquals(EXPECTED_SIZE, size.longValue());
}
@Test
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
- final long expectedSize = 136;
-
final Path folder = Paths.get(path);
final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum();
- assertEquals(expectedSize, size);
+ assertEquals(EXPECTED_SIZE, size);
}
@Test
public void whenGetFolderSizeUsingApacheCommonsIO_thenCorrect() {
- final long expectedSize = 136;
-
final File folder = new File(path);
final long size = FileUtils.sizeOfDirectory(folder);
- assertEquals(expectedSize, size);
+ assertEquals(EXPECTED_SIZE, size);
}
@Test
public void whenGetFolderSizeUsingGuava_thenCorrect() {
- final long expectedSize = 136;
-
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);
+ assertEquals(EXPECTED_SIZE, size);
}
@Test
@@ -89,25 +83,23 @@ 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);
final String readableSize = new DecimalFormat("#,##0.#").format(size / unitValue) + " " + units[unitIndex];
- assertEquals("136 B", readableSize);
+ assertEquals(EXPECTED_SIZE + " B", readableSize);
}
private long getFolderSize(final File folder) {
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 (final 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/src/test/java/com/baeldung/java8/JavaTryWithResourcesUnitTest.java
similarity index 98%
rename from core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java
rename to core-java/src/test/java/com/baeldung/java8/JavaTryWithResourcesUnitTest.java
index 224c4e9d6a..4c843ccaaf 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java
+++ b/core-java/src/test/java/com/baeldung/java8/JavaTryWithResourcesUnitTest.java
@@ -8,7 +8,7 @@ import java.io.StringWriter;
import java.util.Date;
import java.util.Scanner;
-public class JavaTryWithResourcesTest {
+public class JavaTryWithResourcesUnitTest {
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
private Date resource1Date, resource2Date;
diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java b/core-java/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java
similarity index 97%
rename from core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java
rename to core-java/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java
index 164a571817..7889e6ad53 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java
+++ b/core-java/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeUnitTest.java
@@ -7,7 +7,7 @@ import java.io.UnsupportedEncodingException;
import static org.junit.Assert.*;
-public class ApacheCommonsEncodeDecodeTest {
+public class ApacheCommonsEncodeDecodeUnitTest {
// tests
diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java b/core-java/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java
similarity index 98%
rename from core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java
rename to core-java/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java
index 18dccf71ba..62cfa4c0a1 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java
+++ b/core-java/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeUnitTest.java
@@ -8,7 +8,7 @@ import java.util.UUID;
import static org.junit.Assert.*;
-public class Java8EncodeDecodeTest {
+public class Java8EncodeDecodeUnitTest {
// tests
diff --git a/core-java-8/src/test/java/com/baeldung/java8/entity/Human.java b/core-java/src/test/java/com/baeldung/java8/entity/Human.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/entity/Human.java
rename to core-java/src/test/java/com/baeldung/java8/entity/Human.java
diff --git a/core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java
new file mode 100644
index 0000000000..13609b6977
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/printscreen/ScreenshotIntegrationTest.java
@@ -0,0 +1,25 @@
+package com.baeldung.printscreen;
+
+import org.junit.After;
+import org.junit.Test;
+
+import java.io.File;
+
+import static org.junit.Assert.assertTrue;
+
+public class ScreenshotIntegrationTest {
+
+ private Screenshot screenshot = new Screenshot("Screenshot.jpg");
+ private File file = new File("Screenshot.jpg");
+
+ @Test
+ public void testGetScreenshot() throws Exception {
+ screenshot.getScreenshot(2000);
+ assertTrue(file.exists());
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ file.delete();
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java
new file mode 100644
index 0000000000..7ac8e0a97a
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/socket/EchoIntegrationTest.java
@@ -0,0 +1,47 @@
+package com.baeldung.socket;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.concurrent.Executors;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class EchoIntegrationTest {
+ private static final Integer PORT = 4444;
+
+ @BeforeClass
+ public static void start() throws InterruptedException {
+ Executors.newSingleThreadExecutor().submit(() -> new EchoServer().start(PORT));
+ Thread.sleep(500);
+ }
+
+ private EchoClient client = new EchoClient();
+
+ @Before
+ public void init() {
+ client.startConnection("127.0.0.1", PORT);
+ }
+
+ @After
+ public void tearDown() {
+ client.stopConnection();
+ }
+
+ //
+
+ @Test
+ public void givenClient_whenServerEchosMessage_thenCorrect() {
+ String resp1 = client.sendMessage("hello");
+ String resp2 = client.sendMessage("world");
+ String resp3 = client.sendMessage("!");
+ String resp4 = client.sendMessage(".");
+ assertEquals("hello", resp1);
+ assertEquals("world", resp2);
+ assertEquals("!", resp3);
+ assertEquals("good bye", resp4);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java
new file mode 100644
index 0000000000..06b37d8539
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/socket/GreetServerIntegrationTest.java
@@ -0,0 +1,41 @@
+package com.baeldung.socket;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.concurrent.Executors;
+
+import static org.junit.Assert.assertEquals;
+
+public class GreetServerIntegrationTest {
+
+ private GreetClient client;
+
+ private static final Integer PORT = 6666;
+
+ @BeforeClass
+ public static void start() throws InterruptedException {
+ Executors.newSingleThreadExecutor().submit(() -> new GreetServer().start(PORT));
+ Thread.sleep(500);
+ }
+
+ @Before
+ public void init() {
+ client = new GreetClient();
+ client.startConnection("127.0.0.1", PORT);
+
+ }
+
+ @Test
+ public void givenGreetingClient_whenServerRespondsWhenStarted_thenCorrect() {
+ String response = client.sendMessage("hello server");
+ assertEquals("hello client", response);
+ }
+
+ @After
+ public void finish() {
+ client.stopConnection();
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java b/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java
new file mode 100644
index 0000000000..6ebc0946c5
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/socket/SocketEchoMultiIntegrationTest.java
@@ -0,0 +1,59 @@
+package com.baeldung.socket;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.concurrent.Executors;
+
+import static org.junit.Assert.assertEquals;
+
+public class SocketEchoMultiIntegrationTest {
+
+ private static final Integer PORT = 5555;
+
+ @BeforeClass
+ public static void start() throws InterruptedException {
+ Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(PORT));
+ Thread.sleep(500);
+ }
+
+ @Test
+ public void givenClient1_whenServerResponds_thenCorrect() {
+ EchoClient client = new EchoClient();
+ client.startConnection("127.0.0.1", PORT);
+ String msg1 = client.sendMessage("hello");
+ String msg2 = client.sendMessage("world");
+ String terminate = client.sendMessage(".");
+
+ assertEquals(msg1, "hello");
+ assertEquals(msg2, "world");
+ assertEquals(terminate, "bye");
+ client.stopConnection();
+ }
+
+ @Test
+ public void givenClient2_whenServerResponds_thenCorrect() {
+ EchoClient client = new EchoClient();
+ client.startConnection("127.0.0.1", PORT);
+ String msg1 = client.sendMessage("hello");
+ String msg2 = client.sendMessage("world");
+ String terminate = client.sendMessage(".");
+ assertEquals(msg1, "hello");
+ assertEquals(msg2, "world");
+ assertEquals(terminate, "bye");
+ client.stopConnection();
+ }
+
+ @Test
+ public void givenClient3_whenServerResponds_thenCorrect() {
+ EchoClient client = new EchoClient();
+ client.startConnection("127.0.0.1", PORT);
+ String msg1 = client.sendMessage("hello");
+ String msg2 = client.sendMessage("world");
+ String terminate = client.sendMessage(".");
+ assertEquals(msg1, "hello");
+ assertEquals(msg2, "world");
+ assertEquals(terminate, "bye");
+ client.stopConnection();
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java
new file mode 100644
index 0000000000..a62ec99043
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/threadpool/CoreThreadPoolIntegrationTest.java
@@ -0,0 +1,153 @@
+package com.baeldung.threadpool;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.junit.Test;
+
+public class CoreThreadPoolIntegrationTest {
+
+ @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/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java b/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java
new file mode 100644
index 0000000000..550e9dda6f
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/threadpool/GuavaThreadPoolIntegrationTest.java
@@ -0,0 +1,54 @@
+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 GuavaThreadPoolIntegrationTest {
+
+ @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/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java b/core-java/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java
new file mode 100644
index 0000000000..3ad3deb548
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.util;
+
+import static org.junit.Assert.assertEquals;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.time.LocalDate;
+import java.time.LocalTime;
+import java.time.ZoneId;
+import java.time.temporal.ChronoField;
+
+import org.junit.Test;
+
+public class CurrentDateTimeUnitTest {
+
+ private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
+
+ @Test
+ public void shouldReturnCurrentDate() {
+ final LocalDate now = LocalDate.now(clock);
+
+ assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
+ assertEquals(10, now.get(ChronoField.MONTH_OF_YEAR));
+ assertEquals(2016, now.get(ChronoField.YEAR));
+ }
+
+ @Test
+ public void shouldReturnCurrentTime() {
+ final LocalTime now = LocalTime.now(clock);
+
+ assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
+ assertEquals(10, now.get(ChronoField.MINUTE_OF_HOUR));
+ assertEquals(30, now.get(ChronoField.SECOND_OF_MINUTE));
+ }
+
+ @Test
+ public void shouldReturnCurrentTimestamp() {
+ final Instant now = Instant.now(clock);
+
+ assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
+ }
+
+}
diff --git a/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionUnitTest.java b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionUnitTest.java
new file mode 100644
index 0000000000..e615e6a7d1
--- /dev/null
+++ b/core-java/src/test/java/org/baeldung/core/exceptions/FileNotFoundExceptionUnitTest.java
@@ -0,0 +1,61 @@
+package org.baeldung.core.exceptions;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+
+import org.apache.log4j.Logger;
+import org.junit.Test;
+
+public class FileNotFoundExceptionUnitTest {
+
+ private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionUnitTest.class);
+
+ private String fileName = Double.toString(Math.random());
+
+ @Test(expected = BusinessException.class)
+ public void raiseBusinessSpecificException() throws IOException {
+ try {
+ readFailingFile();
+ } catch (FileNotFoundException ex) {
+ throw new BusinessException("BusinessException: necessary file was not present.", ex);
+ }
+ }
+
+ @Test
+ public void createFile() throws IOException {
+ try {
+ readFailingFile();
+ } catch (FileNotFoundException ex) {
+ try {
+ new File(fileName).createNewFile();
+ readFailingFile();
+ } catch (IOException ioe) {
+ throw new RuntimeException("BusinessException: even creation is not possible.", ioe);
+ }
+ }
+ }
+
+ @Test
+ public void logError() throws IOException {
+ try {
+ readFailingFile();
+ } catch (FileNotFoundException ex) {
+ LOG.error("Optional file " + fileName + " was not found.", ex);
+ }
+ }
+
+ private void readFailingFile() throws IOException {
+ BufferedReader rd = new BufferedReader(new FileReader(new File(fileName)));
+ rd.readLine();
+ // no need to close file
+ }
+
+ private class BusinessException extends RuntimeException {
+ BusinessException(String string, FileNotFoundException ex) {
+ super(string, ex);
+ }
+ }
+}
diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java
new file mode 100644
index 0000000000..680a6d57b5
--- /dev/null
+++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/ComplexClassUnitTest.java
@@ -0,0 +1,35 @@
+package org.baeldung.equalshashcode.entities;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.baeldung.equalshashcode.entities.ComplexClass;
+
+public class ComplexClassUnitTest {
+
+ @Test
+ public void testEqualsAndHashcodes() {
+ List strArrayList = new ArrayList();
+ strArrayList.add("abc");
+ strArrayList.add("def");
+ ComplexClass aObject = new ComplexClass(strArrayList, new HashSet(45, 67));
+ ComplexClass bObject = new ComplexClass(strArrayList, new HashSet(45, 67));
+
+ List strArrayListD = new ArrayList();
+ strArrayListD.add("lmn");
+ strArrayListD.add("pqr");
+ ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet(45, 67));
+
+ Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
+
+ Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
+
+ Assert.assertFalse(aObject.equals(dObject));
+ Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
+ }
+
+}
diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java
new file mode 100644
index 0000000000..f4e9f2b99f
--- /dev/null
+++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/PrimitiveClassUnitTest.java
@@ -0,0 +1,25 @@
+package org.baeldung.equalshashcode.entities;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.baeldung.equalshashcode.entities.PrimitiveClass;
+
+public class PrimitiveClassUnitTest {
+
+ @Test
+ public void testTwoEqualsObjects() {
+
+ PrimitiveClass aObject = new PrimitiveClass(false, 2);
+ PrimitiveClass bObject = new PrimitiveClass(false, 2);
+ PrimitiveClass dObject = new PrimitiveClass(true, 2);
+
+ Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
+
+ Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
+
+ Assert.assertFalse(aObject.equals(dObject));
+ Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
+ }
+
+}
diff --git a/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java
new file mode 100644
index 0000000000..5c860bd62d
--- /dev/null
+++ b/core-java/src/test/java/org/baeldung/equalshashcode/entities/SquareClassUnitTest.java
@@ -0,0 +1,27 @@
+package org.baeldung.equalshashcode.entities;
+
+import java.awt.Color;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.baeldung.equalshashcode.entities.Square;
+
+public class SquareClassUnitTest {
+
+ @Test
+ public void testEqualsAndHashcodes() {
+ Square aObject = new Square(10, Color.BLUE);
+ Square bObject = new Square(10, Color.BLUE);
+
+ Square dObject = new Square(20, Color.BLUE);
+
+ Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
+
+ Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
+
+ Assert.assertFalse(aObject.equals(dObject));
+ Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
+ }
+
+}
diff --git a/core-java/src/test/java/org/baeldung/java/JavaIoIntegrationTest.java b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java
similarity index 97%
rename from core-java/src/test/java/org/baeldung/java/JavaIoIntegrationTest.java
rename to core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java
index ff92410bc4..3ab8e1de91 100644
--- a/core-java/src/test/java/org/baeldung/java/JavaIoIntegrationTest.java
+++ b/core-java/src/test/java/org/baeldung/java/JavaIoUnitTest.java
@@ -7,6 +7,7 @@ import java.util.Scanner;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
+import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -14,7 +15,8 @@ import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
-public class JavaIoIntegrationTest {
+@Ignore("need large file for testing")
+public class JavaIoUnitTest {
protected final Logger logger = LoggerFactory.getLogger(getClass());
// tests - iterate lines in a file
diff --git a/core-java/src/test/java/org/baeldung/java/JavaTimerUnitTest.java b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java
similarity index 98%
rename from core-java/src/test/java/org/baeldung/java/JavaTimerUnitTest.java
rename to core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java
index fcc74dbe64..3b126464ab 100644
--- a/core-java/src/test/java/org/baeldung/java/JavaTimerUnitTest.java
+++ b/core-java/src/test/java/org/baeldung/java/JavaTimerLongRunningUnitTest.java
@@ -9,7 +9,7 @@ import java.util.concurrent.TimeUnit;
import org.junit.Test;
-public class JavaTimerUnitTest {
+public class JavaTimerLongRunningUnitTest {
// tests
@@ -90,7 +90,6 @@ public class JavaTimerUnitTest {
@Override
public void run() {
System.out.println("Task performed on " + new Date());
- // TODO: stop the thread
}
};
final Timer timer = new Timer("Timer");
diff --git a/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java b/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java
new file mode 100644
index 0000000000..885c3bcd6c
--- /dev/null
+++ b/core-java/src/test/java/org/baeldung/java/arrays/ArraysJoinAndSplitJUnitTest.java
@@ -0,0 +1,41 @@
+package org.baeldung.java.arrays;
+
+import java.util.Arrays;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class ArraysJoinAndSplitJUnitTest {
+
+ private final String[] sauces = { "Marinara", "Olive Oil" };
+ private final String[] cheeses = { "Mozzarella", "Feta", "Parmesan" };
+ private final String[] vegetables = { "Olives", "Spinach", "Green Peppers" };
+
+ private final String[] customers = { "Jay", "Harry", "Ronnie", "Gary", "Ross" };
+
+ @Test
+ public void givenThreeStringArrays_whenJoiningIntoOneStringArray_shouldSucceed() {
+ String[] toppings = new String[sauces.length + cheeses.length + vegetables.length];
+
+ System.arraycopy(sauces, 0, toppings, 0, sauces.length);
+ int AddedSoFar = sauces.length;
+
+ System.arraycopy(cheeses, 0, toppings, AddedSoFar, cheeses.length);
+ AddedSoFar += cheeses.length;
+
+ System.arraycopy(vegetables, 0, toppings, AddedSoFar, vegetables.length);
+
+ Assert.assertArrayEquals(toppings, new String[] { "Marinara", "Olive Oil", "Mozzarella", "Feta", "Parmesan", "Olives", "Spinach", "Green Peppers" });
+ }
+
+ @Test
+ public void givenOneStringArray_whenSplittingInHalfTwoStringArrays_shouldSucceed() {
+ int ordersHalved = (customers.length / 2) + (customers.length % 2);
+
+ String[] driverOne = Arrays.copyOf(customers, ordersHalved);
+ String[] driverTwo = Arrays.copyOfRange(customers, ordersHalved, customers.length);
+
+ Assert.assertArrayEquals(driverOne, new String[] { "Jay", "Harry", "Ronnie" });
+ Assert.assertArrayEquals(driverTwo, new String[] { "Gary", "Ross" });
+ }
+}
diff --git a/core-java/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java
new file mode 100644
index 0000000000..5d07628a96
--- /dev/null
+++ b/core-java/src/test/java/org/baeldung/java/collections/ArrayListUnitTest.java
@@ -0,0 +1,137 @@
+package org.baeldung.java.collections;
+
+import com.google.common.collect.Sets;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.*;
+import java.util.stream.*;
+
+import static java.util.stream.Collectors.*;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.core.IsNot.not;
+import static org.junit.Assert.*;
+
+public class ArrayListUnitTest {
+
+ private List stringsToSearch;
+
+ @Before
+ public void setUp() {
+ List list = LongStream.range(0, 16).boxed().map(Long::toHexString).collect(toCollection(ArrayList::new));
+ stringsToSearch = new ArrayList<>(list);
+ stringsToSearch.addAll(list);
+ }
+
+ @Test
+ public void givenNewArrayList_whenCheckCapacity_thenDefaultValue() {
+ List list = new ArrayList<>();
+ assertTrue(list.isEmpty());
+ }
+
+ @Test
+ public void givenCollection_whenProvideItToArrayListCtor_thenArrayListIsPopulatedWithItsElements() {
+ Collection numbers = IntStream.range(0, 10).boxed().collect(toSet());
+
+ List list = new ArrayList<>(numbers);
+ assertEquals(10, list.size());
+ assertTrue(numbers.containsAll(list));
+ }
+
+ @Test
+ public void givenElement_whenAddToArrayList_thenIsAdded() {
+ List list = new ArrayList<>();
+
+ list.add(1L);
+ list.add(2L);
+ list.add(1, 3L);
+
+ assertThat(Arrays.asList(1L, 3L, 2L), equalTo(list));
+ }
+
+ @Test
+ public void givenCollection_whenAddToArrayList_thenIsAdded() {
+ List list = new ArrayList<>(Arrays.asList(1L, 2L, 3L));
+ LongStream.range(4, 10).boxed().collect(collectingAndThen(toCollection(ArrayList::new), ys -> list.addAll(0, ys)));
+
+ assertThat(Arrays.asList(4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L), equalTo(list));
+ }
+
+ @Test
+ public void givenExistingElement_whenCallIndexOf_thenReturnCorrectIndex() {
+ assertEquals(10, stringsToSearch.indexOf("a"));
+ assertEquals(26, stringsToSearch.lastIndexOf("a"));
+ }
+
+ @Test
+ public void givenCondition_whenIterateArrayList_thenFindAllElementsSatisfyingCondition() {
+ Iterator it = stringsToSearch.iterator();
+ Set matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9"));
+
+ List result = new ArrayList<>();
+ while (it.hasNext()) {
+ String s = it.next();
+ if (matchingStrings.contains(s)) {
+ result.add(s);
+ }
+ }
+
+ assertEquals(6, result.size());
+ }
+
+ @Test
+ public void givenPredicate_whenIterateArrayList_thenFindAllElementsSatisfyingPredicate() {
+ Set matchingStrings = new HashSet<>(Arrays.asList("a", "c", "9"));
+
+ List result = stringsToSearch.stream().filter(matchingStrings::contains).collect(toCollection(ArrayList::new));
+
+ assertEquals(6, result.size());
+ }
+
+ @Test
+ public void givenSortedArray_whenUseBinarySearch_thenFindElement() {
+ List copy = new ArrayList<>(stringsToSearch);
+ Collections.sort(copy);
+ int index = Collections.binarySearch(copy, "f");
+ assertThat(index, not(equalTo(-1)));
+ }
+
+ @Test
+ public void givenIndex_whenRemove_thenCorrectElementRemoved() {
+ List list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
+ Collections.reverse(list);
+
+ list.remove(0);
+ assertThat(list.get(0), equalTo(8));
+
+ list.remove(Integer.valueOf(0));
+ assertFalse(list.contains(0));
+ }
+
+ @Test
+ public void givenListIterator_whenReverseTraversal_thenRetrieveElementsInOppositeOrder() {
+ List list = IntStream.range(0, 10).boxed().collect(toCollection(ArrayList::new));
+ ListIterator it = list.listIterator(list.size());
+ List result = new ArrayList<>(list.size());
+ while (it.hasPrevious()) {
+ result.add(it.previous());
+ }
+
+ Collections.reverse(list);
+ assertThat(result, equalTo(list));
+ }
+
+ @Test
+ public void givenCondition_whenIterateArrayList_thenRemoveAllElementsSatisfyingCondition() {
+ Set matchingStrings = Sets.newHashSet("a", "b", "c", "d", "e", "f");
+
+ Iterator it = stringsToSearch.iterator();
+ while (it.hasNext()) {
+ if (matchingStrings.contains(it.next())) {
+ it.remove();
+ }
+ }
+
+ assertEquals(20, stringsToSearch.size());
+ }
+}
diff --git a/core-java/src/test/java/org/baeldung/java/collections/CollectionsJoinAndSplitJUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/CollectionsJoinAndSplitJUnitTest.java
new file mode 100644
index 0000000000..c288cf499d
--- /dev/null
+++ b/core-java/src/test/java/org/baeldung/java/collections/CollectionsJoinAndSplitJUnitTest.java
@@ -0,0 +1,62 @@
+package org.baeldung.java.collections;
+
+import java.util.ArrayList;
+import java.util.Collections;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class CollectionsJoinAndSplitJUnitTest {
+
+ private ArrayList sauces = new ArrayList<>();
+ private ArrayList cheeses = new ArrayList<>();
+ private ArrayList vegetables = new ArrayList<>();
+
+ private ArrayList> ingredients = new ArrayList<>();
+
+ @Before
+ public void init() {
+ sauces.add("Olive Oil");
+ sauces.add("Marinara");
+
+ cheeses.add("Mozzarella");
+ cheeses.add("Feta");
+ cheeses.add("Parmesan");
+
+ vegetables.add("Olives");
+ vegetables.add("Spinach");
+ vegetables.add("Green Peppers");
+
+ ingredients.add(sauces);
+ ingredients.add(cheeses);
+ ingredients.add(vegetables);
+ }
+
+ @Test
+ public void givenThreeArrayLists_whenJoiningIntoOneArrayList_shouldSucceed() {
+ ArrayList> toppings = new ArrayList<>();
+
+ toppings.add(sauces);
+ toppings.add(cheeses);
+ toppings.add(vegetables);
+
+ Assert.assertTrue(toppings.size() == 3);
+ Assert.assertTrue(toppings.contains(sauces));
+ Assert.assertTrue(toppings.contains(cheeses));
+ Assert.assertTrue(toppings.contains(vegetables));
+ }
+
+ @Test
+ public void givenOneArrayList_whenSplittingIntoTwoArrayLists_shouldSucceed() {
+
+ ArrayList> removedToppings = new ArrayList<>();
+ removedToppings.add(ingredients.remove(ingredients.indexOf(vegetables)));
+
+ Assert.assertTrue(removedToppings.contains(vegetables));
+ Assert.assertTrue(removedToppings.size() == 1);
+ Assert.assertTrue(ingredients.size() == 2);
+ Assert.assertTrue(ingredients.contains(sauces));
+ Assert.assertTrue(ingredients.contains(cheeses));
+ }
+}
diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java
similarity index 60%
rename from core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java
rename to core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java
index a6814ee600..bb3abff28d 100644
--- a/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java
+++ b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java
@@ -1,21 +1,21 @@
package org.baeldung.java.enums;
-
-import com.baeldung.enums.Pizza;
-import org.junit.Test;
+import static junit.framework.TestCase.assertTrue;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
-import static junit.framework.TestCase.assertTrue;
+import org.junit.Test;
+import com.baeldung.enums.Pizza;
+
+public class PizzaUnitTest {
-public class PizzaTest {
@Test
public void givenPizaOrder_whenReady_thenDeliverable() {
Pizza testPz = new Pizza();
- testPz.setStatus(Pizza.PizzaStatus.READY);
+ testPz.setStatus(Pizza.PizzaStatusEnum.READY);
assertTrue(testPz.isDeliverable());
}
@@ -23,16 +23,16 @@ public class PizzaTest {
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
List pzList = new ArrayList<>();
Pizza pz1 = new Pizza();
- pz1.setStatus(Pizza.PizzaStatus.DELIVERED);
+ pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
Pizza pz2 = new Pizza();
- pz2.setStatus(Pizza.PizzaStatus.ORDERED);
+ pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz3 = new Pizza();
- pz3.setStatus(Pizza.PizzaStatus.ORDERED);
+ pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz4 = new Pizza();
- pz4.setStatus(Pizza.PizzaStatus.READY);
+ pz4.setStatus(Pizza.PizzaStatusEnum.READY);
pzList.add(pz1);
pzList.add(pz2);
@@ -48,33 +48,34 @@ public class PizzaTest {
List pzList = new ArrayList<>();
Pizza pz1 = new Pizza();
- pz1.setStatus(Pizza.PizzaStatus.DELIVERED);
+ pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
Pizza pz2 = new Pizza();
- pz2.setStatus(Pizza.PizzaStatus.ORDERED);
+ pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz3 = new Pizza();
- pz3.setStatus(Pizza.PizzaStatus.ORDERED);
+ pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
Pizza pz4 = new Pizza();
- pz4.setStatus(Pizza.PizzaStatus.READY);
+ 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.PizzaStatus.DELIVERED).size() == 1);
- assertTrue(map.get(Pizza.PizzaStatus.ORDERED).size() == 2);
- assertTrue(map.get(Pizza.PizzaStatus.READY).size() == 1);
+ EnumMap