diff --git a/.gitignore b/.gitignore
index 30f0f0cbc2..319eb5ca2d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,8 +7,11 @@
# Eclipse
.settings/
+*.project
+*.classpath
.prefs
*.prefs
+.metadata/
# Intellij
.idea/
@@ -21,3 +24,7 @@
# Maven
log/
target/
+
+spring-openid/src/main/resources/application.properties
+.recommenders/
+
diff --git a/.project b/.project
index 2d04570bfe..594b00d611 100644
--- a/.project
+++ b/.project
@@ -1,11 +1,17 @@
- parent
-
-
-
-
-
-
-
+ parent-modules
+
+
+
+
+
+ org.eclipse.m2e.core.maven2Builder
+
+
+
+
+
+ org.eclipse.m2e.core.maven2Nature
+
diff --git a/README.md b/README.md
index 3e88f0c017..f0d3d29da7 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,8 @@
The "REST with Spring" Classes
==============================
-This is what I'm working on:
-**[>> THE REST WITH SPRING CLASSES](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=25off)**
+After 5 months of work, here's the Master Class of REST With Spring:
+**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
Spring Tutorials
@@ -19,3 +19,8 @@ Any IDE can be used to work with the projects, but if you're using Eclipse, cons
- import the included **formatter** in Eclipse:
`https://github.com/eugenp/tutorials/tree/master/eclipse`
+
+
+CI - Jenkins
+================================
+This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials/)**
diff --git a/apache-fop/pom.xml b/apache-fop/pom.xml
index 13fc2257cf..658d567a90 100644
--- a/apache-fop/pom.xml
+++ b/apache-fop/pom.xml
@@ -1,6 +1,6 @@
4.0.0
- org.baeldung
+ com.baeldung
apache-fop
0.1-SNAPSHOT
@@ -37,7 +37,7 @@
junit
- junit-dep
+ junit
${junit.version}
test
@@ -142,16 +142,12 @@
-
- 4.1.5.RELEASE
- 3.2.5.RELEASE
-
- 4.3.8.Final
- 5.1.34
+ 4.3.11.Final
+ 5.1.38
- 2.4.4
+ 2.7.2
1.7.9
@@ -161,25 +157,25 @@
5.1.3.Final
- 17.0
+ 19.0
3.3.2
1.3
- 4.11
+ 4.12
1.10.19
4.4
4.4
- 2.4.0
+ 2.9.0
- 3.2
+ 3.5.1
2.6
- 2.18.1
+ 2.19.1
2.7
- 1.4.12
+ 1.4.18
diff --git a/assertj/pom.xml b/assertj/pom.xml
new file mode 100644
index 0000000000..ce97278a97
--- /dev/null
+++ b/assertj/pom.xml
@@ -0,0 +1,38 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ assertj
+ 1.0.0-SNAPSHOT
+
+
+
+ junit
+ junit
+ 4.12
+
+
+ org.assertj
+ assertj-core
+ 3.4.1
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.3
+
+ 1.8
+ 1.8
+
+
+
+
+
\ No newline at end of file
diff --git a/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Dog.java b/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Dog.java
new file mode 100644
index 0000000000..623f71214c
--- /dev/null
+++ b/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Dog.java
@@ -0,0 +1,19 @@
+package com.baeldung.assertj.introduction.domain;
+
+public class Dog {
+ private String name;
+ private Float weight;
+
+ public Dog(String name, Float weight) {
+ this.name = name;
+ this.weight = weight;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Float getWeight() {
+ return weight;
+ }
+}
diff --git a/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Person.java b/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Person.java
new file mode 100644
index 0000000000..90ef787ebe
--- /dev/null
+++ b/assertj/src/main/java/com/baeldung/assertj/introduction/domain/Person.java
@@ -0,0 +1,19 @@
+package com.baeldung.assertj.introduction.domain;
+
+public class Person {
+ private String name;
+ private Integer age;
+
+ public Person(String name, Integer age) {
+ this.name = name;
+ this.age = age;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Integer getAge() {
+ return age;
+ }
+}
diff --git a/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java
new file mode 100644
index 0000000000..21bc40ae9f
--- /dev/null
+++ b/assertj/src/test/java/com/baeldung/assertj/introduction/AssertJCoreTest.java
@@ -0,0 +1,143 @@
+package com.baeldung.assertj.introduction;
+
+import com.baeldung.assertj.introduction.domain.Dog;
+import com.baeldung.assertj.introduction.domain.Person;
+import org.assertj.core.util.Maps;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.NoSuchElementException;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.entry;
+import static org.assertj.core.api.Assertions.withPrecision;
+
+public class AssertJCoreTest {
+
+ @Test
+ public void whenComparingReferences_thenNotEqual() throws Exception {
+ Dog fido = new Dog("Fido", 5.15f);
+ Dog fidosClone = new Dog("Fido", 5.15f);
+
+ assertThat(fido).isNotEqualTo(fidosClone);
+ }
+
+ @Test
+ public void whenComparingFields_thenEqual() throws Exception {
+ Dog fido = new Dog("Fido", 5.15f);
+ Dog fidosClone = new Dog("Fido", 5.15f);
+
+ assertThat(fido).isEqualToComparingFieldByFieldRecursively(fidosClone);
+ }
+
+ @Test
+ public void whenCheckingForElement_thenContains() throws Exception {
+ List list = Arrays.asList("1", "2", "3");
+
+ assertThat(list)
+ .contains("1");
+ }
+
+ @Test
+ public void whenCheckingForElement_thenMultipleAssertions() throws Exception {
+ List list = Arrays.asList("1", "2", "3");
+
+ assertThat(list).isNotEmpty();
+ assertThat(list).startsWith("1");
+ assertThat(list).doesNotContainNull();
+
+ assertThat(list)
+ .isNotEmpty()
+ .contains("1")
+ .startsWith("1")
+ .doesNotContainNull()
+ .containsSequence("2", "3");
+ }
+
+ @Test
+ public void whenCheckingRunnable_thenIsInterface() throws Exception {
+ assertThat(Runnable.class).isInterface();
+ }
+
+ @Test
+ public void whenCheckingCharacter_thenIsUnicode() throws Exception {
+ char someCharacter = 'c';
+
+ assertThat(someCharacter)
+ .isNotEqualTo('a')
+ .inUnicode()
+ .isGreaterThanOrEqualTo('b')
+ .isLowerCase();
+ }
+
+ @Test
+ public void whenAssigningNSEExToException_thenIsAssignable() throws Exception {
+ assertThat(Exception.class).isAssignableFrom(NoSuchElementException.class);
+ }
+
+ @Test
+ public void whenComparingWithOffset_thenEquals() throws Exception {
+ assertThat(5.1).isEqualTo(5, withPrecision(1d));
+ }
+
+ @Test
+ public void whenCheckingString_then() throws Exception {
+ assertThat("".isEmpty()).isTrue();
+ }
+
+ @Test
+ public void whenCheckingFile_then() throws Exception {
+ final File someFile = File.createTempFile("aaa", "bbb");
+ someFile.deleteOnExit();
+
+ assertThat(someFile)
+ .exists()
+ .isFile()
+ .canRead()
+ .canWrite();
+ }
+
+ @Test
+ public void whenCheckingIS_then() throws Exception {
+ InputStream given = new ByteArrayInputStream("foo".getBytes());
+ InputStream expected = new ByteArrayInputStream("foo".getBytes());
+
+ assertThat(given).hasSameContentAs(expected);
+ }
+
+ @Test
+ public void whenGivenMap_then() throws Exception {
+ Map map = Maps.newHashMap(2, "a");
+
+ assertThat(map)
+ .isNotEmpty()
+ .containsKey(2)
+ .doesNotContainKeys(10)
+ .contains(entry(2, "a"));
+ }
+
+ @Test
+ public void whenGivenException_then() throws Exception {
+ Exception ex = new Exception("abc");
+
+ assertThat(ex)
+ .hasNoCause()
+ .hasMessageEndingWith("c");
+ }
+
+ @Ignore // IN ORDER TO TEST, REMOVE THIS LINE
+ @Test
+ public void whenRunningAssertion_thenDescribed() throws Exception {
+ Person person = new Person("Alex", 34);
+
+ assertThat(person.getAge())
+ .as("%s's age should be equal to 100")
+ .isEqualTo(100);
+ }
+}
diff --git a/core-java-8/.project b/core-java-8/.project
index 235c555abb..a23ff42ae0 100644
--- a/core-java-8/.project
+++ b/core-java-8/.project
@@ -1,15 +1,10 @@
- core-java-8
+ core-java8
-
- org.eclipse.jdt.core.javabuilder
-
-
-
org.eclipse.m2e.core.maven2Builder
@@ -17,8 +12,6 @@
- org.eclipse.jem.workbench.JavaEMFNature
- org.eclipse.jdt.core.javanature
org.eclipse.m2e.core.maven2Nature
diff --git a/core-java-8/.settings/.jsdtscope b/core-java-8/.settings/.jsdtscope
deleted file mode 100644
index 7b3f0c8b9f..0000000000
--- a/core-java-8/.settings/.jsdtscope
+++ /dev/null
@@ -1,5 +0,0 @@
-
-
-
-
-
diff --git a/core-java-8/.settings/org.eclipse.jdt.core.prefs b/core-java-8/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index c57289fc09..0000000000
--- a/core-java-8/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,96 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.8
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=error
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=error
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.8
diff --git a/core-java-8/.settings/org.eclipse.jdt.ui.prefs b/core-java-8/.settings/org.eclipse.jdt.ui.prefs
deleted file mode 100644
index d84d2a7f8c..0000000000
--- a/core-java-8/.settings/org.eclipse.jdt.ui.prefs
+++ /dev/null
@@ -1,57 +0,0 @@
-eclipse.preferences.version=1
-editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
-sp_cleanup.add_default_serial_version_id=true
-sp_cleanup.add_generated_serial_version_id=false
-sp_cleanup.add_missing_annotations=true
-sp_cleanup.add_missing_deprecated_annotations=true
-sp_cleanup.add_missing_methods=false
-sp_cleanup.add_missing_nls_tags=false
-sp_cleanup.add_missing_override_annotations=true
-sp_cleanup.add_missing_override_annotations_interface_methods=true
-sp_cleanup.add_serial_version_id=false
-sp_cleanup.always_use_blocks=true
-sp_cleanup.always_use_parentheses_in_expressions=true
-sp_cleanup.always_use_this_for_non_static_field_access=false
-sp_cleanup.always_use_this_for_non_static_method_access=false
-sp_cleanup.convert_functional_interfaces=false
-sp_cleanup.convert_to_enhanced_for_loop=true
-sp_cleanup.correct_indentation=true
-sp_cleanup.format_source_code=true
-sp_cleanup.format_source_code_changes_only=true
-sp_cleanup.make_local_variable_final=true
-sp_cleanup.make_parameters_final=true
-sp_cleanup.make_private_fields_final=false
-sp_cleanup.make_type_abstract_if_missing_method=false
-sp_cleanup.make_variable_declarations_final=true
-sp_cleanup.never_use_blocks=false
-sp_cleanup.never_use_parentheses_in_expressions=false
-sp_cleanup.on_save_use_additional_actions=true
-sp_cleanup.organize_imports=true
-sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
-sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
-sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
-sp_cleanup.qualify_static_member_accesses_with_declaring_class=true
-sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
-sp_cleanup.remove_private_constructors=true
-sp_cleanup.remove_trailing_whitespaces=true
-sp_cleanup.remove_trailing_whitespaces_all=true
-sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
-sp_cleanup.remove_unnecessary_casts=true
-sp_cleanup.remove_unnecessary_nls_tags=false
-sp_cleanup.remove_unused_imports=true
-sp_cleanup.remove_unused_local_variables=false
-sp_cleanup.remove_unused_private_fields=true
-sp_cleanup.remove_unused_private_members=false
-sp_cleanup.remove_unused_private_methods=true
-sp_cleanup.remove_unused_private_types=true
-sp_cleanup.sort_members=false
-sp_cleanup.sort_members_all=false
-sp_cleanup.use_anonymous_class_creation=false
-sp_cleanup.use_blocks=true
-sp_cleanup.use_blocks_only_for_return_and_throw=false
-sp_cleanup.use_lambda=false
-sp_cleanup.use_parentheses_in_expressions=false
-sp_cleanup.use_this_for_non_static_field_access=true
-sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
-sp_cleanup.use_this_for_non_static_method_access=true
-sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
diff --git a/core-java-8/.settings/org.eclipse.m2e.core.prefs b/core-java-8/.settings/org.eclipse.m2e.core.prefs
deleted file mode 100644
index f897a7f1cb..0000000000
--- a/core-java-8/.settings/org.eclipse.m2e.core.prefs
+++ /dev/null
@@ -1,4 +0,0 @@
-activeProfiles=
-eclipse.preferences.version=1
-resolveWorkspaceProjects=true
-version=1
diff --git a/core-java-8/.springBeans b/core-java-8/.springBeans
deleted file mode 100644
index a79097f40d..0000000000
--- a/core-java-8/.springBeans
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
- 1
-
-
-
-
-
-
- src/main/webapp/WEB-INF/api-servlet.xml
-
-
-
-
diff --git a/core-java-8/README.md b/core-java-8/README.md
index 9bb6bb811c..b03d24c34e 100644
--- a/core-java-8/README.md
+++ b/core-java-8/README.md
@@ -3,4 +3,9 @@
## Core Java 8 Cookbooks and Examples
### Relevant Articles:
-// - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
+// - [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
+- [Java – Directory Size](http://www.baeldung.com/java-folder-size)
+- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
+- [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)
+- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml
index 9db2562fb4..8c9bb36f7d 100644
--- a/core-java-8/pom.xml
+++ b/core-java-8/pom.xml
@@ -1,10 +1,11 @@
-
+
4.0.0
- org.baeldung
- spring-rest
+ com.baeldung
+ core-java8
0.1-SNAPSHOT
- spring-rest
+ core-java8
@@ -40,6 +41,12 @@
3.3.2
+
+ org.slf4j
+ slf4j-api
+ ${org.slf4j.version}
+
+
@@ -56,6 +63,12 @@
test
+
+ org.assertj
+ assertj-core
+ 3.4.1
+
+
org.mockito
mockito-core
@@ -98,14 +111,14 @@
- 1.7.12
+ 1.7.13
1.0.13
5.1.3.Final
- 18.0
+ 19.0
3.4
@@ -114,9 +127,9 @@
1.10.19
- 3.3
+ 3.5.1
2.6
- 2.18.1
+ 2.19.1
2.7
diff --git a/core-java-8/src/main/java/com/baeldung/Adder.java b/core-java-8/src/main/java/com/baeldung/Adder.java
new file mode 100644
index 0000000000..e3e100f121
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/Adder.java
@@ -0,0 +1,12 @@
+package com.baeldung;
+
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+public interface Adder {
+
+ String addWithFunction(Function f);
+
+ void addWithConsumer(Consumer f);
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/AdderImpl.java b/core-java-8/src/main/java/com/baeldung/AdderImpl.java
new file mode 100644
index 0000000000..f67cdc26b3
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/AdderImpl.java
@@ -0,0 +1,17 @@
+package com.baeldung;
+
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+public class AdderImpl implements Adder {
+
+ @Override
+ public String addWithFunction(final Function f) {
+ return f.apply("Something ");
+ }
+
+ @Override
+ public void addWithConsumer(final Consumer f) {
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/Bar.java b/core-java-8/src/main/java/com/baeldung/Bar.java
new file mode 100644
index 0000000000..f9b6f2773e
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/Bar.java
@@ -0,0 +1,12 @@
+package com.baeldung;
+
+@FunctionalInterface
+public interface Bar {
+
+ String method(String string);
+
+ default String defaultMethod() {
+ return "String from Bar";
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/Baz.java b/core-java-8/src/main/java/com/baeldung/Baz.java
new file mode 100644
index 0000000000..6d03f74198
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/Baz.java
@@ -0,0 +1,11 @@
+package com.baeldung;
+
+@FunctionalInterface
+public interface Baz {
+
+ String method(String string);
+
+ default String defaultMethod() {
+ return "String from Baz";
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/Foo.java b/core-java-8/src/main/java/com/baeldung/Foo.java
new file mode 100644
index 0000000000..90ebdfeed3
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/Foo.java
@@ -0,0 +1,10 @@
+package com.baeldung;
+
+@FunctionalInterface
+public interface Foo {
+
+ String method(String string);
+
+ default void defaultMethod() {
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/FooExtended.java b/core-java-8/src/main/java/com/baeldung/FooExtended.java
new file mode 100644
index 0000000000..c8ed0c35dd
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/FooExtended.java
@@ -0,0 +1,11 @@
+package com.baeldung;
+
+@FunctionalInterface
+public interface FooExtended extends Baz, Bar {
+
+ @Override
+ default String defaultMethod() {
+ return Bar.super.defaultMethod();
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/UseFoo.java b/core-java-8/src/main/java/com/baeldung/UseFoo.java
new file mode 100644
index 0000000000..a91404ebaf
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/UseFoo.java
@@ -0,0 +1,37 @@
+package com.baeldung;
+
+import java.util.function.Function;
+
+public class UseFoo {
+
+ private String value = "Enclosing scope value";
+
+ public String add(final String string, final Foo foo) {
+ return foo.method(string);
+ }
+
+ public String addWithStandardFI(final String string, final Function fn) {
+ return fn.apply(string);
+ }
+
+ public String scopeExperiment() {
+ final Foo fooIC = new Foo() {
+ String value = "Inner class value";
+
+ @Override
+ public String method(final String string) {
+ return value;
+ }
+ };
+ final String resultIC = fooIC.method("");
+
+ final Foo fooLambda = parameter -> {
+ final String value = "Lambda value";
+ return this.value;
+ };
+ final String resultLambda = fooLambda.method("");
+
+ return "Results: resultIC = " + resultIC + ", resultLambda = " + resultLambda;
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java b/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java
new file mode 100644
index 0000000000..125b6fbe38
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseDuration.java
@@ -0,0 +1,16 @@
+package com.baeldung.datetime;
+
+import java.time.Duration;
+import java.time.LocalTime;
+import java.time.Period;
+
+public class UseDuration {
+
+ public LocalTime modifyDates(LocalTime localTime,Duration duration){
+ return localTime.plus(duration);
+ }
+
+ public Duration getDifferenceBetweenDates(LocalTime localTime1,LocalTime localTime2){
+ return Duration.between(localTime1, localTime2);
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java
new file mode 100644
index 0000000000..47b1b3f67d
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDate.java
@@ -0,0 +1,46 @@
+package com.baeldung.datetime;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.temporal.ChronoUnit;
+import java.time.temporal.TemporalAdjusters;
+
+public class UseLocalDate {
+
+ public LocalDate getLocalDateUsingFactoryOfMethod(int year, int month, int dayOfMonth){
+ return LocalDate.of(year, month, dayOfMonth);
+ }
+
+ public LocalDate getLocalDateUsingParseMethod(String representation){
+ return LocalDate.parse(representation);
+ }
+
+ public LocalDate getLocalDateFromClock(){
+ LocalDate localDate = LocalDate.now();
+ return localDate;
+ }
+
+ public LocalDate getNextDay(LocalDate localDate){
+ return localDate.plusDays(1);
+ }
+
+ public LocalDate getPreviousDay(LocalDate localDate){
+ return localDate.minus(1, ChronoUnit.DAYS);
+ }
+
+ public DayOfWeek getDayOfWeek(LocalDate localDate){
+ DayOfWeek day = localDate.getDayOfWeek();
+ return day;
+ }
+
+ public LocalDate getFirstDayOfMonth(){
+ LocalDate firstDayOfMonth = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
+ return firstDayOfMonth;
+ }
+
+ public LocalDateTime getStartOfDay(LocalDate localDate){
+ LocalDateTime startofDay = localDate.atStartOfDay();
+ return startofDay;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
new file mode 100644
index 0000000000..7aa1eaa276
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalDateTime.java
@@ -0,0 +1,11 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDateTime;
+
+public class UseLocalDateTime {
+
+ public LocalDateTime getLocalDateTimeUsingParseMethod(String representation){
+ return LocalDateTime.parse(representation);
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java
new file mode 100644
index 0000000000..e13fd10d6f
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseLocalTime.java
@@ -0,0 +1,35 @@
+package com.baeldung.datetime;
+
+import java.time.LocalTime;
+import java.time.temporal.ChronoUnit;
+
+public class UseLocalTime {
+
+ public LocalTime getLocalTimeUsingFactoryOfMethod(int hour, int min, int seconds){
+ LocalTime localTime = LocalTime.of(hour, min, seconds);
+ return localTime;
+ }
+
+ public LocalTime getLocalTimeUsingParseMethod(String timeRepresentation){
+ LocalTime localTime = LocalTime.parse(timeRepresentation);
+ return localTime;
+ }
+
+ public LocalTime getLocalTimeFromClock(){
+ LocalTime localTime = LocalTime.now();
+ return localTime;
+ }
+
+ public LocalTime addAnHour(LocalTime localTime){
+ LocalTime newTime = localTime.plus(1,ChronoUnit.HOURS);
+ return newTime;
+ }
+
+ public int getHourFromLocalTime(LocalTime localTime){
+ return localTime.getHour();
+ }
+
+ public LocalTime getLocalTimeWithMinuteSetToValue(LocalTime localTime, int minute){
+ return localTime.withMinute(minute);
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java b/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java
new file mode 100644
index 0000000000..326cfad650
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UsePeriod.java
@@ -0,0 +1,15 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDate;
+import java.time.Period;
+
+public class UsePeriod {
+
+ public LocalDate modifyDates(LocalDate localDate,Period period){
+ return localDate.plus(period);
+ }
+
+ public Period getDifferenceBetweenDates(LocalDate localDate1,LocalDate localDate2){
+ return Period.between(localDate1, localDate2);
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java b/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java
new file mode 100644
index 0000000000..1ddb096cf6
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseToInstant.java
@@ -0,0 +1,19 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.util.Calendar;
+import java.util.Date;
+
+public class UseToInstant {
+
+ public LocalDateTime convertDateToLocalDate(Date date){
+ LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
+ return localDateTime;
+ }
+
+ public LocalDateTime convertDateToLocalDate(Calendar calendar){
+ LocalDateTime localDateTime = LocalDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault());
+ return localDateTime;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java b/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
new file mode 100644
index 0000000000..0369de9835
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/datetime/UseZonedDateTime.java
@@ -0,0 +1,13 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+
+public class UseZonedDateTime {
+
+ public ZonedDateTime getZonedDateTime(LocalDateTime localDateTime,ZoneId zoneId){
+ ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
+ return zonedDateTime;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/Computer.java b/core-java-8/src/main/java/com/baeldung/doublecolon/Computer.java
new file mode 100644
index 0000000000..b5d2e70abd
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/doublecolon/Computer.java
@@ -0,0 +1,88 @@
+package com.baeldung.doublecolon;
+
+public class Computer {
+
+ private Integer age;
+ private String color;
+ private Integer healty;
+
+ public Computer(final int age, final String color) {
+ this.age = age;
+ this.color = color;
+ }
+
+ public Computer(final Integer age, final String color, final Integer healty) {
+ this.age = age;
+ this.color = color;
+ this.healty = healty;
+ }
+
+ public Computer() {
+ }
+
+ public Integer getAge() {
+ return age;
+ }
+
+ public void setAge(final Integer age) {
+ this.age = age;
+ }
+
+ public String getColor() {
+ return color;
+ }
+
+ public void setColor(final String color) {
+ this.color = color;
+ }
+
+ public Integer getHealty() {
+ return healty;
+ }
+
+ public void setHealty(final Integer healty) {
+ this.healty = healty;
+ }
+
+ public void turnOnPc() {
+ System.out.println("Computer turned on");
+ }
+
+ public void turnOffPc() {
+ System.out.println("Computer turned off");
+ }
+
+ public Double calculateValue(Double initialValue) {
+ return initialValue / 1.50;
+ }
+
+ @Override
+ public String toString() {
+ return "Computer{" + "age=" + age + ", color='" + color + '\'' + ", healty=" + healty + '}';
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ final Computer computer = (Computer) o;
+
+ if (age != null ? !age.equals(computer.age) : computer.age != null) {
+ return false;
+ }
+ return color != null ? color.equals(computer.color) : computer.color == null;
+
+ }
+
+ @Override
+ public int hashCode() {
+ int result = age != null ? age.hashCode() : 0;
+ result = 31 * result + (color != null ? color.hashCode() : 0);
+ return result;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/ComputerUtils.java b/core-java-8/src/main/java/com/baeldung/doublecolon/ComputerUtils.java
new file mode 100644
index 0000000000..d181dfcdf7
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/doublecolon/ComputerUtils.java
@@ -0,0 +1,27 @@
+package com.baeldung.doublecolon;
+
+import com.baeldung.doublecolon.function.ComputerPredicate;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ComputerUtils {
+
+ public static final ComputerPredicate after2010Predicate = (c) -> (c.getAge() > 2010);
+ public static final ComputerPredicate blackPredicate = (c) -> "black".equals(c.getColor());
+
+ public static List filter(final List inventory, final ComputerPredicate p) {
+
+ final List result = new ArrayList<>();
+ inventory.stream().filter(p::filter).forEach(result::add);
+
+ return result;
+ }
+
+ public static void repair(final Computer computer) {
+ if (computer.getHealty() < 50) {
+ computer.setHealty(100);
+ }
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/MacbookPro.java b/core-java-8/src/main/java/com/baeldung/doublecolon/MacbookPro.java
new file mode 100644
index 0000000000..3fc459c681
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/doublecolon/MacbookPro.java
@@ -0,0 +1,34 @@
+package com.baeldung.doublecolon;
+
+import java.util.function.Function;
+
+public class MacbookPro extends Computer {
+
+ public MacbookPro(int age, String color) {
+ super(age, color);
+ }
+
+ public MacbookPro(Integer age, String color, Integer healty) {
+ super(age, color, healty);
+ }
+
+ @Override
+ public void turnOnPc() {
+ System.out.println("MacbookPro turned on");
+ }
+
+ @Override
+ public void turnOffPc() {
+ System.out.println("MacbookPro turned off");
+ }
+
+ @Override
+ public Double calculateValue(Double initialValue) {
+
+ Function function = super::calculateValue;
+ final Double pcValue = function.apply(initialValue);
+ System.out.println("First value is:" + pcValue);
+ return pcValue + (initialValue / 10);
+
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java b/core-java-8/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java
new file mode 100644
index 0000000000..5ce491e86a
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java
@@ -0,0 +1,10 @@
+package com.baeldung.doublecolon.function;
+
+import com.baeldung.doublecolon.Computer;
+
+@FunctionalInterface
+public interface ComputerPredicate {
+
+ boolean filter(Computer c);
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/function/TriFunction.java b/core-java-8/src/main/java/com/baeldung/doublecolon/function/TriFunction.java
new file mode 100644
index 0000000000..d0d6299479
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/doublecolon/function/TriFunction.java
@@ -0,0 +1,15 @@
+package com.baeldung.doublecolon.function;
+
+import java.util.Objects;
+import java.util.function.Function;
+
+@FunctionalInterface
+public interface TriFunction {
+
+ R apply(A a, B b, C c);
+
+ default TriFunction andThen(final Function super R, ? extends V> after) {
+ Objects.requireNonNull(after);
+ return (final A a, final B b, final C c) -> after.apply(apply(a, b, c));
+ }
+}
\ 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
new file mode 100644
index 0000000000..5bc2d9a9eb
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/enums/Pizza.java
@@ -0,0 +1,91 @@
+package com.baeldung.enums;
+
+import java.util.EnumMap;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class Pizza {
+
+ private static EnumSet deliveredPizzaStatuses =
+ EnumSet.of(PizzaStatusEnum.DELIVERED);
+
+ private PizzaStatusEnum status;
+
+ public enum PizzaStatusEnum {
+ ORDERED(5) {
+ @Override
+ public boolean isOrdered() {
+ return true;
+ }
+ },
+ READY(2) {
+ @Override
+ public boolean isReady() {
+ return true;
+ }
+ },
+ DELIVERED(0) {
+ @Override
+ public boolean isDelivered() {
+ return true;
+ }
+ };
+
+ private int timeToDelivery;
+
+ public boolean isOrdered() {
+ return false;
+ }
+
+ public boolean isReady() {
+ return false;
+ }
+
+ public boolean isDelivered() {
+ return false;
+ }
+
+ public int getTimeToDelivery() {
+ return timeToDelivery;
+ }
+
+ PizzaStatusEnum(int timeToDelivery) {
+ this.timeToDelivery = timeToDelivery;
+ }
+ }
+
+ public PizzaStatusEnum getStatus() {
+ return status;
+ }
+
+ public void setStatus(PizzaStatusEnum status) {
+ this.status = status;
+ }
+
+ public boolean isDeliverable() {
+ return this.status.isReady();
+ }
+
+ public void printTimeToDeliver() {
+ System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
+ }
+
+ public static List getAllUndeliveredPizzas(List input) {
+ return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
+ }
+
+ public static EnumMap> groupPizzaByStatus(List pzList) {
+ return pzList.stream().collect(
+ Collectors.groupingBy(Pizza::getStatus,
+ () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
+ }
+
+ public void deliver() {
+ if (isDeliverable()) {
+ PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
+ this.setStatus(PizzaStatusEnum.DELIVERED);
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java
new file mode 100644
index 0000000000..ed65919387
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java
@@ -0,0 +1,18 @@
+package com.baeldung.enums;
+
+public enum PizzaDeliveryStrategy {
+ EXPRESS {
+ @Override
+ public void deliver(Pizza pz) {
+ System.out.println("Pizza will be delivered in express mode");
+ }
+ },
+ NORMAL {
+ @Override
+ public void deliver(Pizza pz) {
+ System.out.println("Pizza will be delivered in normal mode");
+ }
+ };
+
+ public abstract void deliver(Pizza pz);
+}
diff --git a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java
new file mode 100644
index 0000000000..5ccff5e959
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java
@@ -0,0 +1,22 @@
+package com.baeldung.enums;
+
+
+public enum PizzaDeliverySystemConfiguration {
+ INSTANCE;
+
+ PizzaDeliverySystemConfiguration() {
+ // Do the configuration initialization which
+ // involves overriding defaults like delivery strategy
+ }
+
+ private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
+
+ public static PizzaDeliverySystemConfiguration getInstance() {
+ return INSTANCE;
+ }
+
+ public PizzaDeliveryStrategy getDeliveryStrategy() {
+ return deliveryStrategy;
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java b/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java
new file mode 100644
index 0000000000..f1ab2d8d09
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java
@@ -0,0 +1,49 @@
+package com.baeldung.forkjoin;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.ForkJoinTask;
+import java.util.concurrent.RecursiveAction;
+import java.util.logging.Logger;
+
+public class CustomRecursiveAction extends RecursiveAction {
+
+ private String workLoad = "";
+ private static final int THRESHOLD = 4;
+
+ private static Logger logger = Logger.getAnonymousLogger();
+
+ public CustomRecursiveAction(String workLoad) {
+ this.workLoad = workLoad;
+ }
+
+ @Override
+ protected void compute() {
+
+ if (workLoad.length() > THRESHOLD) {
+ ForkJoinTask.invokeAll(createSubtasks());
+ } else {
+ processing(workLoad);
+ }
+ }
+
+ private Collection createSubtasks() {
+
+ List subtasks =
+ new ArrayList<>();
+
+ String partOne = workLoad.substring(0, workLoad.length() / 2);
+ String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length());
+
+ subtasks.add(new CustomRecursiveAction(partOne));
+ subtasks.add(new CustomRecursiveAction(partTwo));
+
+ return subtasks;
+ }
+
+ private void processing(String work) {
+ String result = work.toUpperCase();
+ logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread().getName());
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java b/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java
new file mode 100644
index 0000000000..5d4d97b805
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java
@@ -0,0 +1,51 @@
+package com.baeldung.forkjoin;
+
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.ForkJoinTask;
+import java.util.concurrent.RecursiveTask;
+
+public class CustomRecursiveTask extends RecursiveTask {
+
+ private int[] arr;
+
+ private static final int THRESHOLD = 20;
+
+ public CustomRecursiveTask(int[] arr) {
+ this.arr = arr;
+ }
+
+ @Override
+ protected Integer compute() {
+
+ if (arr.length > THRESHOLD) {
+
+ return ForkJoinTask.invokeAll(createSubtasks())
+ .stream()
+ .mapToInt(ForkJoinTask::join)
+ .sum();
+
+ } else {
+ return processing(arr);
+ }
+ }
+
+ private Collection createSubtasks() {
+ List dividedTasks = new ArrayList<>();
+ dividedTasks.add(new CustomRecursiveTask(
+ Arrays.copyOfRange(arr, 0, arr.length / 2)));
+ dividedTasks.add(new CustomRecursiveTask(
+ Arrays.copyOfRange(arr, arr.length / 2, arr.length)));
+ return dividedTasks;
+ }
+
+ private Integer processing(int[] arr) {
+ return Arrays.stream(arr)
+ .filter(a -> a > 10 && a < 27)
+ .map(a -> a * 10)
+ .sum();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java b/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java
new file mode 100644
index 0000000000..521616600f
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java
@@ -0,0 +1,10 @@
+package com.baeldung.forkjoin.util;
+
+
+import java.util.concurrent.ForkJoinPool;
+
+public class PoolUtil {
+
+ public static ForkJoinPool forkJoinPool = new ForkJoinPool(2);
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java b/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java
new file mode 100644
index 0000000000..1f89503288
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java
@@ -0,0 +1,14 @@
+package com.baeldung.java_8_features;
+
+public class Address {
+
+ private String street;
+
+ public String getStreet() {
+ return street;
+ }
+
+ public void setStreet(String street) {
+ this.street = street;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java b/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java
new file mode 100644
index 0000000000..ff9be6ab06
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java
@@ -0,0 +1,4 @@
+package com.baeldung.java_8_features;
+
+public class CustomException extends RuntimeException {
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java b/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java
new file mode 100644
index 0000000000..811937dba7
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java
@@ -0,0 +1,13 @@
+package com.baeldung.java_8_features;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class Detail {
+
+ private static final List PARTS = Arrays.asList("turbine", "pump");
+
+ public List getParts() {
+ return PARTS;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java b/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java
new file mode 100644
index 0000000000..8d6c517ac5
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java
@@ -0,0 +1,16 @@
+package com.baeldung.java_8_features;
+
+import java.util.Optional;
+
+public class OptionalAddress {
+
+ private String street;
+
+ public Optional getStreet() {
+ return Optional.ofNullable(street);
+ }
+
+ public void setStreet(String street) {
+ this.street = street;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java b/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java
new file mode 100644
index 0000000000..ff06cd21d6
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java
@@ -0,0 +1,16 @@
+package com.baeldung.java_8_features;
+
+import java.util.Optional;
+
+public class OptionalUser {
+
+ private OptionalAddress address;
+
+ public Optional getAddress() {
+ return Optional.of(address);
+ }
+
+ public void setAddress(OptionalAddress address) {
+ this.address = address;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/User.java b/core-java-8/src/main/java/com/baeldung/java_8_features/User.java
new file mode 100644
index 0000000000..3708d276c8
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/User.java
@@ -0,0 +1,40 @@
+package com.baeldung.java_8_features;
+
+import java.util.Optional;
+
+public class User {
+
+ private String name;
+
+ private Address address;
+
+ public Address getAddress() {
+ return address;
+ }
+
+ public void setAddress(Address address) {
+ this.address = address;
+ }
+
+ public User() {
+ }
+
+ public User(String name) {
+ this.name = name;
+ }
+
+ public static boolean isRealUser(User user) {
+ return true;
+ }
+
+ public String getOrThrow() {
+ String value = null;
+ Optional valueOpt = Optional.ofNullable(value);
+ String result = valueOpt.orElseThrow(CustomException::new).toUpperCase();
+ return result;
+ }
+
+ public boolean isLegalName(String name) {
+ return name.length() > 3 && name.length() < 16;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java b/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java
new file mode 100644
index 0000000000..011173bcaf
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java
@@ -0,0 +1,18 @@
+package com.baeldung.java_8_features;
+
+public interface Vehicle {
+
+ void moveTo(long altitude, long longitude);
+
+ static String producer() {
+ return "N&F Vehicles";
+ }
+
+ default long[] startPosition() {
+ return new long[]{23, 15};
+ }
+
+ default String getOverview() {
+ return "ATV made by " + producer();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java b/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java
new file mode 100644
index 0000000000..83e55f5f4d
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java
@@ -0,0 +1,9 @@
+package com.baeldung.java_8_features;
+
+public class VehicleImpl implements Vehicle {
+
+ @Override
+ public void moveTo(long altitude, long longitude) {
+ //do nothing
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/streamApi/Product.java b/core-java-8/src/main/java/com/baeldung/streamApi/Product.java
new file mode 100644
index 0000000000..18f3a61904
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/streamApi/Product.java
@@ -0,0 +1,51 @@
+package com.baeldung.streamApi;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+/**
+ * Created by Alex Vengr
+ */
+public class Product {
+
+ private int price;
+
+ private String name;
+
+ private boolean utilize;
+
+ public Product(int price, String name) {
+ this(price);
+ this.name = name;
+ }
+
+ public Product(int price) {
+ this.price = price;
+ }
+
+ public Product() {
+ }
+
+ public int getPrice() {
+ return price;
+ }
+
+ public void setPrice(int price) {
+ this.price = price;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+
+ public static Stream streamOf(List list) {
+ return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java
new file mode 100644
index 0000000000..6648d5f926
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java
@@ -0,0 +1,30 @@
+package com.baeldung.unzip;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipInputStream;
+
+public class UnzipFile {
+ public static void main(final String[] args) throws IOException {
+ final String fileZip = "src/main/resources/compressed.zip";
+ final byte[] buffer = new byte[1024];
+ final ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
+ ZipEntry zipEntry = zis.getNextEntry();
+ while (zipEntry != null) {
+ final String fileName = zipEntry.getName();
+ final File newFile = new File("src/main/resources/unzipTest/" + fileName);
+ final FileOutputStream fos = new FileOutputStream(newFile);
+ int len;
+ while ((len = zis.read(buffer)) > 0) {
+ fos.write(buffer, 0, len);
+ }
+ fos.close();
+ zipEntry = zis.getNextEntry();
+ }
+ zis.closeEntry();
+ zis.close();
+ }
+}
\ No newline at end of file
diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java b/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java
new file mode 100644
index 0000000000..7da71a093d
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/zip/ZipDirectory.java
@@ -0,0 +1,43 @@
+package com.baeldung.zip;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+public class ZipDirectory {
+ public static void main(final String[] args) throws IOException {
+ final String sourceFile = "src/main/resources/zipTest";
+ final FileOutputStream fos = new FileOutputStream("src/main/resources/dirCompressed.zip");
+ final ZipOutputStream zipOut = new ZipOutputStream(fos);
+ final File fileToZip = new File(sourceFile);
+
+ zipFile(fileToZip, fileToZip.getName(), zipOut);
+ zipOut.close();
+ fos.close();
+ }
+
+ private static void zipFile(final File fileToZip, final String fileName, final ZipOutputStream zipOut) throws IOException {
+ if (fileToZip.isHidden()) {
+ return;
+ }
+ if (fileToZip.isDirectory()) {
+ final File[] children = fileToZip.listFiles();
+ for (final File childFile : children) {
+ zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
+ }
+ return;
+ }
+ final FileInputStream fis = new FileInputStream(fileToZip);
+ final ZipEntry zipEntry = new ZipEntry(fileName);
+ zipOut.putNextEntry(zipEntry);
+ final byte[] bytes = new byte[1024];
+ int length;
+ while ((length = fis.read(bytes)) >= 0) {
+ zipOut.write(bytes, 0, length);
+ }
+ fis.close();
+ }
+}
\ No newline at end of file
diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java
new file mode 100644
index 0000000000..f9ccac9713
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java
@@ -0,0 +1,28 @@
+package com.baeldung.zip;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+public class ZipFile {
+ public static void main(final String[] args) throws IOException {
+ final String sourceFile = "src/main/resources/zipTest/test1.txt";
+ final FileOutputStream fos = new FileOutputStream("src/main/resources/compressed.zip");
+ final ZipOutputStream zipOut = new ZipOutputStream(fos);
+ final File fileToZip = new File(sourceFile);
+ final FileInputStream fis = new FileInputStream(fileToZip);
+ final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
+ zipOut.putNextEntry(zipEntry);
+ final byte[] bytes = new byte[1024];
+ int length;
+ while ((length = fis.read(bytes)) >= 0) {
+ zipOut.write(bytes, 0, length);
+ }
+ zipOut.close();
+ fis.close();
+ fos.close();
+ }
+}
\ No newline at end of file
diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java b/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java
new file mode 100644
index 0000000000..fc86147e43
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java
@@ -0,0 +1,33 @@
+package com.baeldung.zip;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+public class ZipMultipleFiles {
+ public static void main(final String[] args) throws IOException {
+ final List srcFiles = Arrays.asList("src/main/resources/zipTest/test1.txt", "src/main/resources/zipTest/test2.txt");
+ final FileOutputStream fos = new FileOutputStream("src/main/resources/multiCompressed.zip");
+ final ZipOutputStream zipOut = new ZipOutputStream(fos);
+ for (final String srcFile : srcFiles) {
+ final File fileToZip = new File(srcFile);
+ final FileInputStream fis = new FileInputStream(fileToZip);
+ final ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
+ zipOut.putNextEntry(zipEntry);
+
+ final byte[] bytes = new byte[1024];
+ int length;
+ while ((length = fis.read(bytes)) >= 0) {
+ zipOut.write(bytes, 0, length);
+ }
+ fis.close();
+ }
+ zipOut.close();
+ fos.close();
+ }
+}
\ No newline at end of file
diff --git a/core-java-8/src/main/resources/compressed.zip b/core-java-8/src/main/resources/compressed.zip
new file mode 100644
index 0000000000..03f840ae2b
Binary files /dev/null and b/core-java-8/src/main/resources/compressed.zip differ
diff --git a/core-java-8/src/main/resources/dirCompressed.zip b/core-java-8/src/main/resources/dirCompressed.zip
new file mode 100644
index 0000000000..f42d3aa5c6
Binary files /dev/null and b/core-java-8/src/main/resources/dirCompressed.zip differ
diff --git a/core-java-8/src/main/resources/logback.xml b/core-java-8/src/main/resources/logback.xml
index 62d0ea5037..eefdc7a337 100644
--- a/core-java-8/src/main/resources/logback.xml
+++ b/core-java-8/src/main/resources/logback.xml
@@ -10,7 +10,7 @@
-
+
\ No newline at end of file
diff --git a/core-java-8/src/main/resources/multiCompressed.zip b/core-java-8/src/main/resources/multiCompressed.zip
new file mode 100644
index 0000000000..002e70ef81
Binary files /dev/null and b/core-java-8/src/main/resources/multiCompressed.zip differ
diff --git a/core-java-8/src/main/resources/unzipTest/test1.txt b/core-java-8/src/main/resources/unzipTest/test1.txt
new file mode 100644
index 0000000000..c57eff55eb
--- /dev/null
+++ b/core-java-8/src/main/resources/unzipTest/test1.txt
@@ -0,0 +1 @@
+Hello World!
\ No newline at end of file
diff --git a/core-java-8/src/main/resources/zipTest/test1.txt b/core-java-8/src/main/resources/zipTest/test1.txt
new file mode 100644
index 0000000000..c57eff55eb
--- /dev/null
+++ b/core-java-8/src/main/resources/zipTest/test1.txt
@@ -0,0 +1 @@
+Hello World!
\ No newline at end of file
diff --git a/core-java-8/src/main/resources/zipTest/test2.txt b/core-java-8/src/main/resources/zipTest/test2.txt
new file mode 100644
index 0000000000..f0fb0f14d1
--- /dev/null
+++ b/core-java-8/src/main/resources/zipTest/test2.txt
@@ -0,0 +1 @@
+My Name is John
\ No newline at end of file
diff --git a/core-java-8/src/main/resources/zipTest/testFolder/test3.txt b/core-java-8/src/main/resources/zipTest/testFolder/test3.txt
new file mode 100644
index 0000000000..882edb168e
--- /dev/null
+++ b/core-java-8/src/main/resources/zipTest/testFolder/test3.txt
@@ -0,0 +1 @@
+My Name is Tom
\ No newline at end of file
diff --git a/core-java-8/src/main/resources/zipTest/testFolder/test4.txt b/core-java-8/src/main/resources/zipTest/testFolder/test4.txt
new file mode 100644
index 0000000000..a78c3fadc8
--- /dev/null
+++ b/core-java-8/src/main/resources/zipTest/testFolder/test4.txt
@@ -0,0 +1 @@
+My Name is Jane
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java b/core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java
new file mode 100644
index 0000000000..a543c80eaf
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/dateapi/ConversionExample.java
@@ -0,0 +1,19 @@
+package com.baeldung.dateapi;
+
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.TimeZone;
+
+public class ConversionExample {
+ public static void main(String[] args) {
+ Instant instantFromCalendar = GregorianCalendar.getInstance().toInstant();
+ ZonedDateTime zonedDateTimeFromCalendar = new GregorianCalendar().toZonedDateTime();
+ Date dateFromInstant = Date.from(Instant.now());
+ GregorianCalendar calendarFromZonedDateTime = GregorianCalendar.from(ZonedDateTime.now());
+ Instant instantFromDate = new Date().toInstant();
+ ZoneId zoneIdFromTimeZone = TimeZone.getTimeZone("PST").toZoneId();
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java b/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java
new file mode 100644
index 0000000000..4bce40c2d9
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/dateapi/JavaUtilTimeTest.java
@@ -0,0 +1,89 @@
+package com.baeldung.dateapi;
+
+import org.junit.Test;
+
+import java.text.ParseException;
+import java.time.Duration;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.Month;
+import java.time.YearMonth;
+import java.time.format.DateTimeFormatter;
+import java.time.temporal.ChronoUnit;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class JavaUtilTimeTest {
+
+ @Test
+ public void currentTime() {
+ final LocalDate now = LocalDate.now();
+
+ System.out.println(now);
+ // there is not much to test here
+ }
+
+ @Test
+ public void specificTime() {
+ LocalDate birthDay = LocalDate.of(1990, Month.DECEMBER, 15);
+
+ System.out.println(birthDay);
+ // there is not much to test here
+ }
+
+ @Test
+ public void extractMonth() {
+ Month month = LocalDate.of(1990, Month.DECEMBER, 15).getMonth();
+
+ assertThat(month).isEqualTo(Month.DECEMBER);
+ }
+
+ @Test
+ public void subtractTime() {
+ LocalDateTime fiveHoursBefore = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).minusHours(5);
+
+ assertThat(fiveHoursBefore.getHour()).isEqualTo(10);
+ }
+
+ @Test
+ public void alterField() {
+ LocalDateTime inJune = LocalDateTime.of(1990, Month.DECEMBER, 15, 15, 0).with(Month.JUNE);
+
+ assertThat(inJune.getMonth()).isEqualTo(Month.JUNE);
+ }
+
+ @Test
+ public void truncate() {
+ LocalTime truncated = LocalTime.of(15, 12, 34).truncatedTo(ChronoUnit.HOURS);
+
+ assertThat(truncated).isEqualTo(LocalTime.of(15, 0, 0));
+ }
+
+ @Test
+ public void getTimeSpan() {
+ LocalDateTime now = LocalDateTime.now();
+ LocalDateTime hourLater = now.plusHours(1);
+ Duration span = Duration.between(now, hourLater);
+
+ assertThat(span).isEqualTo(Duration.ofHours(1));
+ }
+
+ @Test
+ public void formatAndParse() throws ParseException {
+ LocalDate someDate = LocalDate.of(2016, 12, 7);
+ DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
+ String formattedDate = someDate.format(formatter);
+ LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);
+
+ assertThat(formattedDate).isEqualTo("2016-12-07");
+ assertThat(parsedDate).isEqualTo(someDate);
+ }
+
+ @Test
+ public void daysInMonth() {
+ int daysInMonth = YearMonth.of(1990, 2).lengthOfMonth();
+
+ assertThat(daysInMonth).isEqualTo(28);
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java
new file mode 100644
index 0000000000..8af33393be
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTest.java
@@ -0,0 +1,55 @@
+package com.baeldung.datetime;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.Month;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseLocalDateTest {
+
+ UseLocalDate useLocalDate = new UseLocalDate();
+
+ @Test
+ public void givenValues_whenUsingFactoryOf_thenLocalDate(){
+ Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingFactoryOfMethod(2016,5,10).toString());
+ }
+
+ @Test
+ public void givenString_whenUsingParse_thenLocalDate(){
+ Assert.assertEquals("2016-05-10",useLocalDate.getLocalDateUsingParseMethod("2016-05-10").toString());
+ }
+
+ @Test
+ public void whenUsingClock_thenLocalDate(){
+ Assert.assertEquals(LocalDate.now(),useLocalDate.getLocalDateFromClock());
+ }
+
+ @Test
+ public void givenDate_whenUsingPlus_thenNextDay(){
+ Assert.assertEquals(LocalDate.now().plusDays(1),useLocalDate.getNextDay(LocalDate.now()));
+ }
+
+ @Test
+ public void givenDate_whenUsingMinus_thenPreviousDay(){
+ Assert.assertEquals(LocalDate.now().minusDays(1),useLocalDate.getPreviousDay(LocalDate.now()));
+ }
+
+ @Test
+ public void givenToday_whenUsingGetDayOfWeek_thenDayOfWeek(){
+ Assert.assertEquals(DayOfWeek.SUNDAY,useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")));
+ }
+
+ @Test
+ public void givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth(){
+ Assert.assertEquals(1,useLocalDate.getFirstDayOfMonth().getDayOfMonth());
+ }
+
+ @Test
+ public void givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight(){
+ Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"),useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")));
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java
new file mode 100644
index 0000000000..69a289fd02
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalDateTimeTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDate;
+import java.time.LocalTime;
+import java.time.Month;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseLocalDateTimeTest {
+
+ UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
+
+ @Test
+ public void givenString_whenUsingParse_thenLocalDateTime(){
+ Assert.assertEquals(LocalDate.of(2016, Month.MAY, 10),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalDate());
+ Assert.assertEquals(LocalTime.of(6,30),useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30").toLocalTime());
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java
new file mode 100644
index 0000000000..7776fad363
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UseLocalTimeTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.datetime;
+
+import java.time.LocalTime;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseLocalTimeTest {
+
+ UseLocalTime useLocalTime = new UseLocalTime();
+
+ @Test
+ public void givenValues_whenUsingFactoryOf_thenLocalTime(){
+ Assert.assertEquals("07:07:07",useLocalTime.getLocalTimeUsingFactoryOfMethod(7,7,7).toString());
+ }
+
+ @Test
+ public void givenString_whenUsingParse_thenLocalTime(){
+ Assert.assertEquals("06:30",useLocalTime.getLocalTimeUsingParseMethod("06:30").toString());
+ }
+
+ @Test
+ public void givenTime_whenAddHour_thenLocalTime(){
+ Assert.assertEquals("07:30",useLocalTime.addAnHour(LocalTime.of(6,30)).toString());
+ }
+
+ @Test
+ public void getHourFromLocalTime(){
+ Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1,1)));
+ }
+
+ @Test
+ public void getLocalTimeWithMinuteSetToValue(){
+ Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10,10), 20));
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java
new file mode 100644
index 0000000000..8a3228aaa5
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UsePeriodTest.java
@@ -0,0 +1,29 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.Period;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UsePeriodTest {
+ UsePeriod usingPeriod=new UsePeriod();
+
+ @Test
+ public void givenPeriodAndLocalDate_thenCalculateModifiedDate(){
+ Period period = Period.ofDays(1);
+ LocalDate localDate = LocalDate.parse("2007-05-10");
+ Assert.assertEquals(localDate.plusDays(1),usingPeriod.modifyDates(localDate, period));
+ }
+
+ @Test
+ public void givenDates_thenGetPeriod(){
+ LocalDate localDate1 = LocalDate.parse("2007-05-10");
+ LocalDate localDate2 = LocalDate.parse("2007-05-15");
+
+ Assert.assertEquals(Period.ofDays(5), usingPeriod.getDifferenceBetweenDates(localDate1, localDate2));
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java b/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java
new file mode 100644
index 0000000000..5af01ad678
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/datetime/UseZonedDateTimeTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.datetime;
+
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class UseZonedDateTimeTest {
+
+ UseZonedDateTime zonedDateTime=new UseZonedDateTime();
+
+ @Test
+ public void givenZoneId_thenZonedDateTime(){
+ ZoneId zoneId=ZoneId.of("Europe/Paris");
+ ZonedDateTime zonedDatetime=zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId);
+ Assert.assertEquals(zoneId,ZoneId.from(zonedDatetime));
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java b/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java
new file mode 100644
index 0000000000..85194f5aa6
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java
@@ -0,0 +1,91 @@
+package com.baeldung.doublecolon;
+
+import com.baeldung.doublecolon.function.TriFunction;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.List;
+import java.util.function.BiFunction;
+
+import static com.baeldung.doublecolon.ComputerUtils.*;
+
+public class TestComputerUtils {
+
+ @Before
+ public void setup() {
+ }
+
+ @After
+ public void tearDown() {
+ }
+
+ @Test
+ public void testConstructorReference() {
+
+ Computer c1 = new Computer(2015, "white");
+ Computer c2 = new Computer(2009, "black");
+ Computer c3 = new Computer(2014, "black");
+
+ BiFunction c4Function = Computer::new;
+ Computer c4 = c4Function.apply(2013, "white");
+ BiFunction c5Function = Computer::new;
+ Computer c5 = c5Function.apply(2010, "black");
+ BiFunction c6Function = Computer::new;
+ Computer c6 = c6Function.apply(2008, "black");
+
+ List inventory = Arrays.asList(c1, c2, c3, c4, c5, c6);
+
+ List blackComputer = filter(inventory, blackPredicate);
+ Assert.assertEquals("The black Computers are: ", blackComputer.size(), 4);
+
+ List after2010Computer = filter(inventory, after2010Predicate);
+ Assert.assertEquals("The Computer bought after 2010 are: ", after2010Computer.size(), 3);
+
+ List before2011Computer = filter(inventory, c -> c.getAge() < 2011);
+ Assert.assertEquals("The Computer bought before 2011 are: ", before2011Computer.size(), 3);
+
+ inventory.sort(Comparator.comparing(Computer::getAge));
+
+ Assert.assertEquals("Oldest Computer in inventory", c6, inventory.get(0));
+
+ }
+
+ @Test
+ public void testStaticMethodReference() {
+
+ Computer c1 = new Computer(2015, "white", 35);
+ Computer c2 = new Computer(2009, "black", 65);
+ TriFunction c6Function = Computer::new;
+ Computer c3 = c6Function.apply(2008, "black", 90);
+
+ List inventory = Arrays.asList(c1, c2, c3);
+ inventory.forEach(ComputerUtils::repair);
+
+ Assert.assertEquals("Computer repaired", new Integer(100), c1.getHealty());
+ }
+
+ @Test
+ public void testInstanceMethodArbitraryObjectParticularType() {
+
+ Computer c1 = new Computer(2015, "white", 35);
+ Computer c2 = new MacbookPro(2009, "black", 65);
+ List inventory = Arrays.asList(c1, c2);
+ inventory.forEach(Computer::turnOnPc);
+
+ }
+
+ @Test
+ public void testSuperMethodReference() {
+
+ final TriFunction integerStringIntegerObjectTriFunction = MacbookPro::new;
+ final MacbookPro macbookPro = integerStringIntegerObjectTriFunction.apply(2010, "black", 100);
+ Double initialValue = new Double(999.99);
+ final Double actualValue = macbookPro.calculateValue(initialValue);
+ Assert.assertEquals(766.659, actualValue, 0.0);
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java b/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java
new file mode 100644
index 0000000000..deeebaa240
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java
@@ -0,0 +1,80 @@
+package com.baeldung.enums;
+
+
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.List;
+
+import static junit.framework.TestCase.assertTrue;
+
+public class PizzaTest {
+
+ @Test
+ public void givenPizaOrder_whenReady_thenDeliverable() {
+ Pizza testPz = new Pizza();
+ testPz.setStatus(Pizza.PizzaStatusEnum.READY);
+ assertTrue(testPz.isDeliverable());
+ }
+
+ @Test
+ public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
+ List pzList = new ArrayList<>();
+ Pizza pz1 = new Pizza();
+ pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
+
+ Pizza pz2 = new Pizza();
+ pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
+
+ Pizza pz3 = new Pizza();
+ pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
+
+ Pizza pz4 = new Pizza();
+ pz4.setStatus(Pizza.PizzaStatusEnum.READY);
+
+ pzList.add(pz1);
+ pzList.add(pz2);
+ pzList.add(pz3);
+ pzList.add(pz4);
+
+ List undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
+ assertTrue(undeliveredPzs.size() == 3);
+ }
+
+ @Test
+ public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
+
+ List pzList = new ArrayList<>();
+ Pizza pz1 = new Pizza();
+ pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
+
+ Pizza pz2 = new Pizza();
+ pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
+
+ Pizza pz3 = new Pizza();
+ pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
+
+ Pizza pz4 = new Pizza();
+ pz4.setStatus(Pizza.PizzaStatusEnum.READY);
+
+ pzList.add(pz1);
+ pzList.add(pz2);
+ pzList.add(pz3);
+ pzList.add(pz4);
+
+ EnumMap> map = Pizza.groupPizzaByStatus(pzList);
+ assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
+ assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
+ assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
+ }
+
+ @Test
+ public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
+ Pizza pz = new Pizza();
+ pz.setStatus(Pizza.PizzaStatusEnum.READY);
+ pz.deliver();
+ assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
+ }
+
+}
diff --git a/core-java-8/src/test/java/org/baeldung/java8/Java8CollectionCleanupUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java
similarity index 80%
rename from core-java-8/src/test/java/org/baeldung/java8/Java8CollectionCleanupUnitTest.java
rename to core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java
index acca829b78..ef4b80c6e8 100644
--- a/core-java-8/src/test/java/org/baeldung/java8/Java8CollectionCleanupUnitTest.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java
@@ -1,14 +1,13 @@
-package org.baeldung.java8;
+package com.baeldung.java8;
-import static org.hamcrest.Matchers.hasSize;
-import static org.junit.Assert.assertThat;
+import com.google.common.collect.Lists;
+import org.junit.Test;
import java.util.List;
import java.util.stream.Collectors;
-import org.junit.Test;
-
-import com.google.common.collect.Lists;
+import static org.hamcrest.Matchers.hasSize;
+import static org.junit.Assert.assertThat;
public class Java8CollectionCleanupUnitTest {
@@ -30,6 +29,14 @@ public class Java8CollectionCleanupUnitTest {
assertThat(listWithoutNulls, hasSize(3));
}
+ @Test
+ public void givenListContainsNulls_whenRemovingNullsWithRemoveIf_thenCorrect() {
+ final List listWithoutNulls = Lists.newArrayList(null, 1, 2, null, 3, null);
+ listWithoutNulls.removeIf(p -> p == null);
+
+ assertThat(listWithoutNulls, hasSize(3));
+ }
+
@Test
public void givenListContainsDuplicates_whenRemovingDuplicatesWithJava8_thenCorrect() {
final List listWithDuplicates = Lists.newArrayList(1, 1, 2, 2, 3, 3);
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java
new file mode 100644
index 0000000000..21a5e34b9b
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java
@@ -0,0 +1,27 @@
+package com.baeldung.java8;
+
+import com.baeldung.java_8_features.Vehicle;
+import com.baeldung.java_8_features.VehicleImpl;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class Java8DefaultStaticIntefaceMethodsTest {
+
+ @Test
+ public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() {
+ Vehicle vehicle = new VehicleImpl();
+ String overview = vehicle.getOverview();
+ long[] startPosition = vehicle.startPosition();
+
+ assertEquals(overview, "ATV made by N&F Vehicles");
+ assertEquals(startPosition[0], 23);
+ assertEquals(startPosition[1], 15);
+ }
+
+ @Test
+ public void callDefaultInterfaceMethods_whenExpectedResults_thenCorrect() {
+ String producer = Vehicle.producer();
+ assertEquals(producer, "N&F Vehicles");
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java
new file mode 100644
index 0000000000..581ccec182
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java
@@ -0,0 +1,156 @@
+package com.baeldung.java8;
+
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.*;
+
+import static org.junit.Assert.*;
+
+
+public class Java8ExecutorServiceTest {
+
+ private Runnable runnableTask;
+ private Callable callableTask;
+ private List> callableTasks;
+
+ @Before
+ public void init() {
+
+ runnableTask = () -> {
+ try {
+ TimeUnit.MILLISECONDS.sleep(300);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ };
+
+ callableTask = () -> {
+ TimeUnit.MILLISECONDS.sleep(300);
+ return "Task's execution";
+ };
+
+ callableTasks = new ArrayList<>();
+ callableTasks.add(callableTask);
+ callableTasks.add(callableTask);
+ callableTasks.add(callableTask);
+ }
+
+ @Test
+ public void creationSubmittingTaskShuttingDown_whenShutDown_thenCorrect() {
+
+ ExecutorService executorService = Executors.newFixedThreadPool(10);
+ executorService.submit(runnableTask);
+ executorService.submit(callableTask);
+ executorService.shutdown();
+
+ assertTrue(executorService.isShutdown());
+ }
+
+ @Test
+ public void creationSubmittingTasksShuttingDownNow_whenShutDownAfterAwating_thenCorrect() {
+
+ ExecutorService threadPoolExecutor =
+ new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
+ new LinkedBlockingQueue<>());
+
+ for (int i = 0; i < 100; i++) {
+ threadPoolExecutor.submit(callableTask);
+ }
+
+ List notExecutedTasks = smartShutdown(threadPoolExecutor);
+
+ assertTrue(threadPoolExecutor.isShutdown());
+ assertFalse(notExecutedTasks.isEmpty());
+ assertTrue(notExecutedTasks.size() > 0 && notExecutedTasks.size() < 98);
+ }
+
+ private List smartShutdown(ExecutorService executorService) {
+
+ List notExecutedTasks = new ArrayList<>();
+ executorService.shutdown();
+ try {
+ if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) {
+ notExecutedTasks = executorService.shutdownNow();
+ }
+ } catch (InterruptedException e) {
+ notExecutedTasks = executorService.shutdownNow();
+ }
+ return notExecutedTasks;
+ }
+
+ @Test
+ public void submittingTasks_whenExecutedOneAndAll_thenCorrect() {
+
+ ExecutorService executorService = Executors.newFixedThreadPool(10);
+
+ String result = null;
+ List> futures = new ArrayList<>();
+ try {
+ result = executorService.invokeAny(callableTasks);
+ futures = executorService.invokeAll(callableTasks);
+ } catch (InterruptedException | ExecutionException e) {
+ e.printStackTrace();
+ }
+
+ assertEquals("Task's execution", result);
+ assertTrue(futures.size() == 3);
+ }
+
+ @Test
+ public void submittingTaskShuttingDown_whenGetExpectedResult_thenCorrect() {
+
+ ExecutorService executorService = Executors.newFixedThreadPool(10);
+
+ Future future = executorService.submit(callableTask);
+ String result = null;
+ try {
+ result = future.get();
+ result = future.get(200, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException | ExecutionException | TimeoutException e) {
+ e.printStackTrace();
+ }
+
+ executorService.shutdown();
+
+ assertEquals("Task's execution", result);
+ }
+
+ @Test
+ public void submittingTask_whenCanceled_thenCorrect() {
+
+ ExecutorService executorService = Executors.newFixedThreadPool(10);
+
+ Future future = executorService.submit(callableTask);
+
+ boolean canceled = future.cancel(true);
+ boolean isCancelled = future.isCancelled();
+
+ executorService.shutdown();
+
+ assertTrue(canceled);
+ assertTrue(isCancelled);
+ }
+
+ @Test
+ public void submittingTaskScheduling_whenExecuted_thenCorrect() {
+
+ ScheduledExecutorService executorService = Executors
+ .newSingleThreadScheduledExecutor();
+
+ Future resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS);
+ String result = null;
+ try {
+ result = resultFuture.get();
+ } catch (InterruptedException | ExecutionException e) {
+ e.printStackTrace();
+ }
+
+ executorService.shutdown();
+
+ assertEquals("Task's execution", result);
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java
new file mode 100644
index 0000000000..273b2d78db
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java
@@ -0,0 +1,100 @@
+package com.baeldung.java8;
+
+
+import com.baeldung.forkjoin.CustomRecursiveAction;
+import com.baeldung.forkjoin.CustomRecursiveTask;
+import com.baeldung.forkjoin.util.PoolUtil;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Random;
+import java.util.concurrent.ForkJoinPool;
+
+import static org.junit.Assert.*;
+
+public class Java8ForkJoinTest {
+
+ private int[] arr;
+ private CustomRecursiveTask customRecursiveTask;
+
+ @Before
+ public void init() {
+ Random random = new Random();
+ arr = new int[50];
+ for (int i = 0; i < arr.length; i++) {
+ arr[i] = random.nextInt(35);
+ }
+ customRecursiveTask = new CustomRecursiveTask(arr);
+ }
+
+
+ @Test
+ public void callPoolUtil_whenExistsAndExpectedType_thenCorrect() {
+
+ ForkJoinPool forkJoinPool = PoolUtil.forkJoinPool;
+ ForkJoinPool forkJoinPoolTwo = PoolUtil.forkJoinPool;
+
+ assertNotNull(forkJoinPool);
+ assertEquals(2, forkJoinPool.getParallelism());
+ assertEquals(forkJoinPool, forkJoinPoolTwo);
+
+ }
+
+ @Test
+ public void callCommonPool_whenExistsAndExpectedType_thenCorrect() {
+
+ ForkJoinPool commonPool = ForkJoinPool.commonPool();
+ ForkJoinPool commonPoolTwo = ForkJoinPool.commonPool();
+
+ assertNotNull(commonPool);
+ assertEquals(commonPool, commonPoolTwo);
+
+ }
+
+ @Test
+ public void executeRecursiveAction_whenExecuted_thenCorrect() {
+
+ CustomRecursiveAction myRecursiveAction = new CustomRecursiveAction("ddddffffgggghhhh");
+ ForkJoinPool.commonPool().invoke(myRecursiveAction);
+
+ assertTrue(myRecursiveAction.isDone());
+
+ }
+
+ @Test
+ public void executeRecursiveTask_whenExecuted_thenCorrect() {
+
+ ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
+
+ forkJoinPool.execute(customRecursiveTask);
+ int result = customRecursiveTask.join();
+ assertTrue(customRecursiveTask.isDone());
+
+ forkJoinPool.submit(customRecursiveTask);
+ int resultTwo = customRecursiveTask.join();
+ assertTrue(customRecursiveTask.isDone());
+
+ }
+
+ @Test
+ public void executeRecursiveTaskWithFJ_whenExecuted_thenCorrect() {
+
+ CustomRecursiveTask customRecursiveTaskFirst = new CustomRecursiveTask(arr);
+ CustomRecursiveTask customRecursiveTaskSecond = new CustomRecursiveTask(arr);
+ CustomRecursiveTask customRecursiveTaskLast = new CustomRecursiveTask(arr);
+
+ customRecursiveTaskFirst.fork();
+ customRecursiveTaskSecond.fork();
+ customRecursiveTaskLast.fork();
+ int result = 0;
+ result += customRecursiveTaskLast.join();
+ result += customRecursiveTaskSecond.join();
+ result += customRecursiveTaskFirst.join();
+
+ assertTrue(customRecursiveTaskFirst.isDone());
+ assertTrue(customRecursiveTaskSecond.isDone());
+ assertTrue(customRecursiveTaskLast.isDone());
+ assertTrue(result != 0);
+
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java
new file mode 100644
index 0000000000..faaf3ae407
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java
@@ -0,0 +1,94 @@
+package com.baeldung.java8;
+
+import com.baeldung.Foo;
+import com.baeldung.FooExtended;
+import com.baeldung.UseFoo;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.function.Function;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+
+public class Java8FunctionalInteracesLambdasTest {
+
+ private UseFoo useFoo;
+
+ @Before
+ public void init() {
+ useFoo = new UseFoo();
+ }
+
+ @Test
+ public void functionalInterfaceInstantiation_whenReturnDefiniteString_thenCorrect() {
+ final Foo foo = parameter -> parameter + "from lambda";
+ final String result = useFoo.add("Message ", foo);
+
+ assertEquals("Message from lambda", result);
+ }
+
+ @Test
+ public void standardFIParameter_whenReturnDefiniteString_thenCorrect() {
+ final Function fn = parameter -> parameter + "from lambda";
+ final String result = useFoo.addWithStandardFI("Message ", fn);
+
+ assertEquals("Message from lambda", result);
+ }
+
+ @Test
+ public void defaultMethodFromExtendedInterface_whenReturnDefiniteString_thenCorrect() {
+ final FooExtended fooExtended = string -> string;
+ final String result = fooExtended.defaultMethod();
+
+ assertEquals("String from Bar", result);
+ }
+
+ @Test
+ public void lambdaAndInnerClassInstantiation_whenReturnSameString_thenCorrect() {
+ final Foo foo = parameter -> parameter + "from Foo";
+
+ final Foo fooByIC = new Foo() {
+ @Override
+ public String method(final String string) {
+ return string + "from Foo";
+ }
+ };
+
+ assertEquals(foo.method("Something "), fooByIC.method("Something "));
+ }
+
+ @Test
+ public void accessVariablesFromDifferentScopes_whenReturnPredefinedString_thenCorrect() {
+ assertEquals("Results: resultIC = Inner class value, resultLambda = Enclosing scope value", useFoo.scopeExperiment());
+ }
+
+ @Test
+ public void shorteningLambdas_whenReturnEqualsResults_thenCorrect() {
+ final Foo foo = parameter -> buildString(parameter);
+
+ final Foo fooHuge = parameter -> {
+ final String result = "Something " + parameter;
+ // many lines of code
+ return result;
+ };
+
+ assertEquals(foo.method("Something"), fooHuge.method("Something"));
+ }
+
+ private String buildString(final String parameter) {
+ final String result = "Something " + parameter;
+ // many lines of code
+ return result;
+ }
+
+ @Test
+ public void mutatingOfEffectivelyFinalVariable_whenNotEquals_thenCorrect() {
+ final int[] total = new int[1];
+ final Runnable r = () -> total[0]++;
+ r.run();
+
+ assertNotEquals(0, total[0]);
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java
new file mode 100644
index 0000000000..d9d88c5052
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java
@@ -0,0 +1,67 @@
+package com.baeldung.java8;
+
+import com.baeldung.java_8_features.User;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class Java8MethodReferenceTest {
+
+ private List list;
+
+ @Before
+ public void init() {
+ list = new ArrayList<>();
+ list.add("One");
+ list.add("OneAndOnly");
+ list.add("Derek");
+ list.add("Change");
+ list.add("factory");
+ list.add("justBefore");
+ list.add("Italy");
+ list.add("Italy");
+ list.add("Thursday");
+ list.add("");
+ list.add("");
+ }
+
+ @Test
+ public void checkStaticMethodReferences_whenWork_thenCorrect() {
+
+ List users = new ArrayList<>();
+ users.add(new User());
+ users.add(new User());
+ boolean isReal = users.stream().anyMatch(u -> User.isRealUser(u));
+ boolean isRealRef = users.stream().anyMatch(User::isRealUser);
+ assertTrue(isReal);
+ assertTrue(isRealRef);
+ }
+
+ @Test
+ public void checkInstanceMethodReferences_whenWork_thenCorrect() {
+ User user = new User();
+ boolean isLegalName = list.stream().anyMatch(user::isLegalName);
+ assertTrue(isLegalName);
+ }
+
+ @Test
+ public void checkParticularTypeReferences_whenWork_thenCorrect() {
+ long count = list.stream().filter(String::isEmpty).count();
+ assertEquals(count, 2);
+ }
+
+ @Test
+ public void checkConstructorReferences_whenWork_thenCorrect() {
+ Stream stream = list.stream().map(User::new);
+ List userList = stream.collect(Collectors.toList());
+ assertEquals(userList.size(), list.size());
+ assertTrue(userList.get(0) instanceof User);
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java
new file mode 100644
index 0000000000..26de39bc0e
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java
@@ -0,0 +1,118 @@
+package com.baeldung.java8;
+
+import com.baeldung.java_8_features.*;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+import static org.junit.Assert.*;
+
+public class Java8OptionalTest {
+
+ private List list;
+
+ @Before
+ public void init() {
+ list = new ArrayList<>();
+ list.add("One");
+ list.add("OneAndOnly");
+ list.add("Derek");
+ list.add("Change");
+ list.add("factory");
+ list.add("justBefore");
+ list.add("Italy");
+ list.add("Italy");
+ list.add("Thursday");
+ list.add("");
+ list.add("");
+ }
+
+ @Test
+ public void checkOptional_whenAsExpected_thenCorrect() {
+
+ Optional optionalEmpty = Optional.empty();
+ assertFalse(optionalEmpty.isPresent());
+
+ String str = "value";
+ Optional optional = Optional.of(str);
+ assertEquals(optional.get(), "value");
+
+ Optional optionalNullable = Optional.ofNullable(str);
+ Optional optionalNull = Optional.ofNullable(null);
+ assertEquals(optionalNullable.get(), "value");
+ assertFalse(optionalNull.isPresent());
+
+ List listOpt = Optional.of(list).orElse(new ArrayList<>());
+ List listNull = null;
+ List listOptNull = Optional.ofNullable(listNull).orElse(new ArrayList<>());
+ assertTrue(listOpt == list);
+ assertTrue(listOptNull.isEmpty());
+
+ Optional user = Optional.ofNullable(getUser());
+ String result = user.map(User::getAddress)
+ .map(Address::getStreet)
+ .orElse("not specified");
+ assertEquals(result, "1st Avenue");
+
+ Optional optionalUser = Optional.ofNullable(getOptionalUser());
+ String resultOpt = optionalUser.flatMap(OptionalUser::getAddress)
+ .flatMap(OptionalAddress::getStreet)
+ .orElse("not specified");
+ assertEquals(resultOpt, "1st Avenue");
+
+ Optional userNull = Optional.ofNullable(getUserNull());
+ String resultNull = userNull.map(User::getAddress)
+ .map(Address::getStreet)
+ .orElse("not specified");
+ assertEquals(resultNull, "not specified");
+
+ Optional optionalUserNull = Optional.ofNullable(getOptionalUserNull());
+ String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress)
+ .flatMap(OptionalAddress::getStreet)
+ .orElse("not specified");
+ assertEquals(resultOptNull, "not specified");
+
+ }
+
+ @Test(expected = CustomException.class)
+ public void callMethod_whenCustomException_thenCorrect() {
+ User user = new User();
+ String result = user.getOrThrow();
+ }
+
+ private User getUser() {
+ User user = new User();
+ Address address = new Address();
+ address.setStreet("1st Avenue");
+ user.setAddress(address);
+ return user;
+ }
+
+ private OptionalUser getOptionalUser() {
+ OptionalUser user = new OptionalUser();
+ OptionalAddress address = new OptionalAddress();
+ address.setStreet("1st Avenue");
+ user.setAddress(address);
+ return user;
+ }
+
+ private OptionalUser getOptionalUserNull() {
+ OptionalUser user = new OptionalUser();
+ OptionalAddress address = new OptionalAddress();
+ address.setStreet(null);
+ user.setAddress(address);
+ return user;
+ }
+
+ private User getUserNull() {
+ User user = new User();
+ Address address = new Address();
+ address.setStreet(null);
+ user.setAddress(address);
+ return user;
+ }
+
+}
diff --git a/core-java-8/src/test/java/org/baeldung/java8/Java8SortUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
similarity index 98%
rename from core-java-8/src/test/java/org/baeldung/java8/Java8SortUnitTest.java
rename to core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
index 8ed7828de0..f371c0d7da 100644
--- a/core-java-8/src/test/java/org/baeldung/java8/Java8SortUnitTest.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
@@ -1,17 +1,16 @@
-package org.baeldung.java8;
+package com.baeldung.java8;
-import static org.hamcrest.Matchers.equalTo;
+import com.baeldung.java8.entity.Human;
+import com.google.common.collect.Lists;
+import com.google.common.primitives.Ints;
+import org.junit.Assert;
+import org.junit.Test;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
-import org.baeldung.java8.entity.Human;
-import org.junit.Assert;
-import org.junit.Test;
-
-import com.google.common.collect.Lists;
-import com.google.common.primitives.Ints;
+import static org.hamcrest.Matchers.equalTo;
public class Java8SortUnitTest {
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java
new file mode 100644
index 0000000000..37326c6d26
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamApiTest.java
@@ -0,0 +1,263 @@
+package com.baeldung.java8;
+
+import com.baeldung.streamApi.Product;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.*;
+import java.util.regex.Pattern;
+import java.util.stream.*;
+
+import static org.junit.Assert.*;
+
+public class Java8StreamApiTest {
+
+ private long counter;
+
+ private static Logger log = LoggerFactory.getLogger(Java8StreamApiTest.class);
+
+ private List productList;
+
+ @Before
+ public void init() {
+ productList = Arrays.asList(
+ new Product(23, "potatoes"), new Product(14, "orange"),
+ new Product(13, "lemon"), new Product(23, "bread"),
+ new Product(13, "sugar"));
+ }
+
+ @Test
+ public void checkPipeline_whenStreamOneElementShorter_thenCorrect() {
+
+ List list = Arrays.asList("abc1", "abc2", "abc3");
+ long size = list.stream().skip(1)
+ .map(element -> element.substring(0, 3)).count();
+ assertEquals(list.size() - 1, size);
+ }
+
+ @Test
+ public void checkOrder_whenChangeQuantityOfMethodCalls_thenCorrect() {
+
+ List list = Arrays.asList("abc1", "abc2", "abc3");
+
+ counter = 0;
+ long sizeFirst = list.stream()
+ .skip(2).map(element -> {
+ wasCalled();
+ return element.substring(0, 3);
+ }).count();
+ assertEquals(1, counter);
+
+ counter = 0;
+ long sizeSecond = list.stream().map(element -> {
+ wasCalled();
+ return element.substring(0, 3);
+ }).skip(2).count();
+ assertEquals(3, counter);
+ }
+
+ @Test
+ public void createEmptyStream_whenEmpty_thenCorrect() {
+
+ Stream streamEmpty = Stream.empty();
+ assertEquals(0, streamEmpty.count());
+
+ List names = Collections.emptyList();
+ Stream streamOf = Product.streamOf(names);
+ assertTrue(streamOf.count() == 0);
+ }
+
+ @Test
+ public void createStream_whenCreated_thenCorrect() {
+
+ Collection collection = Arrays.asList("a", "b", "c");
+ Stream streamOfCollection = collection.stream();
+ assertEquals(3, streamOfCollection.count());
+
+ Stream streamOfArray = Stream.of("a", "b", "c");
+ assertEquals(3, streamOfArray.count());
+
+ String[] arr = new String[]{"a", "b", "c"};
+ Stream streamOfArrayPart = Arrays.stream(arr, 1, 3);
+ assertEquals(2, streamOfArrayPart.count());
+
+ IntStream intStream = IntStream.range(1, 3);
+ LongStream longStream = LongStream.rangeClosed(1, 3);
+ Random random = new Random();
+ DoubleStream doubleStream = random.doubles(3);
+ assertEquals(2, intStream.count());
+ assertEquals(3, longStream.count());
+ assertEquals(3, doubleStream.count());
+
+ IntStream streamOfChars = "abc".chars();
+ IntStream str = "".chars();
+ assertEquals(3, streamOfChars.count());
+
+ Stream streamOfString = Pattern.compile(", ").splitAsStream("a, b, c");
+ assertEquals("a", streamOfString.findFirst().get());
+
+ Path path = getPath();
+ Stream streamOfStrings = null;
+ try {
+ streamOfStrings = Files.lines(path, Charset.forName("UTF-8"));
+ } catch (IOException e) {
+ log.error("Error creating streams from paths {}", path, e.getMessage(), e);
+ }
+ assertEquals("a", streamOfStrings.findFirst().get());
+
+ Stream streamBuilder = Stream.builder().add("a").add("b").add("c").build();
+ assertEquals(3, streamBuilder.count());
+
+ Stream streamGenerated = Stream.generate(() -> "element").limit(10);
+ assertEquals(10, streamGenerated.count());
+
+ Stream streamIterated = Stream.iterate(40, n -> n + 2).limit(20);
+ assertTrue(40 <= streamIterated.findAny().get());
+ }
+
+ @Test
+ public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
+
+ List list = Arrays.asList("abc1", "abc2", "abc3");
+ Optional stream = list.stream()
+ .filter(element -> {
+ log.info("filter() was called");
+ return element.contains("2");
+ }).map(element -> {
+ log.info("map() was called");
+ return element.toUpperCase();
+ }).findFirst();
+ }
+
+ @Test
+ public void reduce_whenExpected_thenCorrect() {
+
+ OptionalInt reduced = IntStream.range(1, 4).reduce((a, b) -> a + b);
+ assertEquals(6, reduced.getAsInt());
+
+ int reducedTwoParams = IntStream.range(1, 4).reduce(10, (a, b) -> a + b);
+ assertEquals(16, reducedTwoParams);
+
+ int reducedThreeParams = Stream.of(1, 2, 3)
+ .reduce(10, (a, b) -> a + b, (a, b) -> {
+ log.info("combiner was called");
+ return a + b;
+ });
+ assertEquals(16, reducedThreeParams);
+
+ int reducedThreeParamsParallel = Arrays.asList(1, 2, 3).parallelStream()
+ .reduce(10, (a, b) -> a + b, (a, b) -> {
+ log.info("combiner was called");
+ return a + b;
+ });
+ assertEquals(36, reducedThreeParamsParallel);
+ }
+
+ @Test
+ public void collecting_whenAsExpected_thenCorrect() {
+
+ List collectorCollection = productList.stream()
+ .map(Product::getName).collect(Collectors.toList());
+
+ assertTrue(collectorCollection instanceof List);
+ assertEquals(5, collectorCollection.size());
+
+ String listToString = productList.stream().map(Product::getName)
+ .collect(Collectors.joining(", ", "[", "]"));
+
+ assertTrue(listToString.contains(",") && listToString.contains("[") && listToString.contains("]"));
+
+ double averagePrice = productList.stream().collect(Collectors.averagingInt(Product::getPrice));
+ assertTrue(17.2 == averagePrice);
+
+ int summingPrice = productList.stream().collect(Collectors.summingInt(Product::getPrice));
+ assertEquals(86, summingPrice);
+
+ IntSummaryStatistics statistics = productList.stream()
+ .collect(Collectors.summarizingInt(Product::getPrice));
+ assertEquals(23, statistics.getMax());
+
+ Map> collectorMapOfLists = productList.stream()
+ .collect(Collectors.groupingBy(Product::getPrice));
+ assertEquals(3, collectorMapOfLists.keySet().size());
+
+ Map> mapPartioned = productList.stream()
+ .collect(Collectors.partitioningBy(element -> element.getPrice() > 15));
+ assertEquals(2, mapPartioned.keySet().size());
+
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void collect_whenThrows_thenCorrect() {
+ Set unmodifiableSet = productList.stream()
+ .collect(Collectors.collectingAndThen(Collectors.toSet(),
+ Collections::unmodifiableSet));
+ unmodifiableSet.add(new Product(4, "tea"));
+ }
+
+ @Test
+ public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
+ Collector> toLinkedList =
+ Collector.of(LinkedList::new, LinkedList::add,
+ (first, second) -> {
+ first.addAll(second);
+ return first;
+ });
+
+ LinkedList linkedListOfPersons = productList.stream().collect(toLinkedList);
+ assertTrue(linkedListOfPersons.containsAll(productList));
+ }
+
+ @Test
+ public void parallelStream_whenWorks_thenCorrect() {
+ Stream streamOfCollection = productList.parallelStream();
+ boolean isParallel = streamOfCollection.isParallel();
+ boolean haveBigPrice = streamOfCollection.map(product -> product.getPrice() * 12)
+ .anyMatch(price -> price > 200);
+ assertTrue(isParallel && haveBigPrice);
+ }
+
+ @Test
+ public void parallel_whenIsParallel_thenCorrect() {
+ IntStream intStreamParallel =
+ IntStream.range(1, 150).parallel().map(element -> element * 34);
+ boolean isParallel = intStreamParallel.isParallel();
+ assertTrue(isParallel);
+ }
+
+ @Test
+ public void parallel_whenIsSequential_thenCorrect() {
+ IntStream intStreamParallel =
+ IntStream.range(1, 150).parallel().map(element -> element * 34);
+ IntStream intStreamSequential = intStreamParallel.sequential();
+ boolean isParallel = intStreamParallel.isParallel();
+ assertFalse(isParallel);
+ }
+
+ private Path getPath() {
+ Path path = null;
+ try {
+ path = Files.createTempFile(null, ".txt");
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+
+ try (BufferedWriter writer = Files.newBufferedWriter(path)) {
+ writer.write("a\nb\nc");
+ } catch (IOException e) {
+ log.error(e.getMessage());
+ }
+ return path;
+ }
+
+ private void wasCalled() {
+ counter++;
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java
new file mode 100644
index 0000000000..1f1dda49ce
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java
@@ -0,0 +1,113 @@
+package com.baeldung.java8;
+
+import com.baeldung.java_8_features.Detail;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.*;
+
+public class Java8StreamsTest {
+
+ private List list;
+
+ @Before
+ public void init() {
+ list = new ArrayList<>();
+ list.add("One");
+ list.add("OneAndOnly");
+ list.add("Derek");
+ list.add("Change");
+ list.add("factory");
+ list.add("justBefore");
+ list.add("Italy");
+ list.add("Italy");
+ list.add("Thursday");
+ list.add("");
+ list.add("");
+ }
+
+ @Test
+ public void checkStreamCount_whenCreating_givenDifferentSources() {
+ String[] arr = new String[]{"a", "b", "c"};
+ Stream streamArr = Arrays.stream(arr);
+ assertEquals(streamArr.count(), 3);
+
+ Stream streamOf = Stream.of("a", "b", "c");
+ assertEquals(streamOf.count(), 3);
+
+ long count = list.stream().distinct().count();
+ assertEquals(count, 9);
+ }
+
+
+ @Test
+ public void checkStreamCount_whenOperationFilter_thanCorrect() {
+ Stream streamFilter = list.stream().filter(element -> element.isEmpty());
+ assertEquals(streamFilter.count(), 2);
+ }
+
+
+ @Test
+ public void checkStreamCount_whenOperationMap_thanCorrect() {
+ List uris = new ArrayList<>();
+ uris.add("C:\\My.txt");
+ Stream streamMap = uris.stream().map(uri -> Paths.get(uri));
+ assertEquals(streamMap.count(), 1);
+
+ List details = new ArrayList<>();
+ details.add(new Detail());
+ details.add(new Detail());
+ Stream streamFlatMap = details.stream()
+ .flatMap(detail -> detail.getParts().stream());
+ assertEquals(streamFlatMap.count(), 4);
+ }
+
+
+ @Test
+ public void checkStreamCount_whenOperationMatch_thenCorrect() {
+ boolean isValid = list.stream().anyMatch(element -> element.contains("h"));
+ boolean isValidOne = list.stream().allMatch(element -> element.contains("h"));
+ boolean isValidTwo = list.stream().noneMatch(element -> element.contains("h"));
+ assertTrue(isValid);
+ assertFalse(isValidOne);
+ assertFalse(isValidTwo);
+ }
+
+
+ @Test
+ public void checkStreamReducedValue_whenOperationReduce_thenCorrect() {
+ List integers = new ArrayList<>();
+ integers.add(1);
+ integers.add(1);
+ integers.add(1);
+ Integer reduced = integers.stream().reduce(23, (a, b) -> a + b);
+ assertTrue(reduced == 26);
+ }
+
+ @Test
+ public void checkStreamContains_whenOperationCollect_thenCorrect() {
+ List resultList = list.stream()
+ .map(element -> element.toUpperCase())
+ .collect(Collectors.toList());
+ assertEquals(resultList.size(), list.size());
+ assertTrue(resultList.contains(""));
+ }
+
+
+ @Test
+ public void checkParallelStream_whenDoWork() {
+ list.parallelStream().forEach(element -> doWork(element));
+ }
+
+ private void doWork(String string) {
+ assertTrue(true); //just imitate an amount of work
+ }
+}
diff --git a/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java
similarity index 82%
rename from core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java
rename to core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java
index baa41511de..efd548a4b1 100644
--- a/core-java-8/src/test/java/org/baeldung/java8/JavaFolderSizeTest.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java
@@ -1,29 +1,34 @@
-package org.baeldung.java8;
+package com.baeldung.java8;
-import static org.junit.Assert.assertEquals;
+import org.apache.commons.io.FileUtils;
+import org.junit.Before;
+import org.junit.Test;
import java.io.File;
import java.io.IOException;
-import java.nio.file.FileVisitResult;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.SimpleFileVisitor;
+import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.DecimalFormat;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.StreamSupport;
-import org.apache.commons.io.FileUtils;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
public class JavaFolderSizeTest {
+ private String path;
+
+ @Before
+ public void init() {
+ final String separator = File.separator;
+ path = "src" + separator + "test" + separator + "resources";
+ }
+
@Test
public void whenGetFolderSizeRecursive_thenCorrect() {
final long expectedSize = 136;
- final File folder = new File("src/test/resources");
+ final File folder = new File(path);
final long size = getFolderSize(folder);
assertEquals(expectedSize, size);
@@ -34,7 +39,7 @@ public class JavaFolderSizeTest {
final long expectedSize = 136;
final AtomicLong size = new AtomicLong(0);
- final Path folder = Paths.get("src/test/resources");
+ final Path folder = Paths.get(path);
Files.walkFileTree(folder, new SimpleFileVisitor() {
@Override
@@ -51,7 +56,7 @@ public class JavaFolderSizeTest {
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
final long expectedSize = 136;
- final Path folder = Paths.get("src/test/resources");
+ 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);
@@ -61,7 +66,7 @@ public class JavaFolderSizeTest {
public void whenGetFolderSizeUsingApacheCommonsIO_thenCorrect() {
final long expectedSize = 136;
- final File folder = new File("src/test/resources");
+ final File folder = new File(path);
final long size = FileUtils.sizeOfDirectory(folder);
assertEquals(expectedSize, size);
@@ -71,7 +76,7 @@ public class JavaFolderSizeTest {
public void whenGetFolderSizeUsingGuava_thenCorrect() {
final long expectedSize = 136;
- final File folder = new File("src/test/resources");
+ 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();
@@ -81,10 +86,10 @@ public class JavaFolderSizeTest {
@Test
public void whenGetReadableSize_thenCorrect() {
- final File folder = new File("src/test/resources");
+ 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);
diff --git a/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java
new file mode 100644
index 0000000000..224c4e9d6a
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java
@@ -0,0 +1,86 @@
+package com.baeldung.java8;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.Date;
+import java.util.Scanner;
+
+public class JavaTryWithResourcesTest {
+
+ private static final String TEST_STRING_HELLO_WORLD = "Hello World";
+ private Date resource1Date, resource2Date;
+
+ // tests
+
+ /* Example for using Try_with_resources */
+ @Test
+ public void whenWritingToStringWriter_thenCorrectlyWritten() {
+ final StringWriter sw = new StringWriter();
+ try (PrintWriter pw = new PrintWriter(sw, true)) {
+ pw.print(TEST_STRING_HELLO_WORLD);
+ }
+
+ Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD);
+ }
+
+ /* Example for using multiple resources */
+ @Test
+ public void givenStringToScanner_whenWritingToStringWriter_thenCorrectlyWritten() {
+
+ final StringWriter sw = new StringWriter();
+ try (Scanner sc = new Scanner(TEST_STRING_HELLO_WORLD); PrintWriter pw = new PrintWriter(sw, true)) {
+ while (sc.hasNext()) {
+ pw.print(sc.nextLine());
+ }
+ }
+
+ Assert.assertEquals(sw.getBuffer().toString(), TEST_STRING_HELLO_WORLD);
+ }
+
+ /* Example to show order in which the resources are closed */
+ @Test
+ public void whenFirstAutoClosableResourceIsinitializedFirst_thenFirstAutoClosableResourceIsReleasedFirst() throws Exception {
+ try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst(); AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {
+ af.doSomething();
+ as.doSomething();
+ }
+ Assert.assertTrue(resource1Date.after(resource2Date));
+ }
+
+ class AutoCloseableResourcesFirst implements AutoCloseable {
+ public AutoCloseableResourcesFirst() {
+ System.out.println("Constructor -> AutoCloseableResources_First");
+ }
+
+ public void doSomething() {
+ System.out.println("Something -> AutoCloseableResources_First");
+ }
+
+ @Override
+ public void close() throws Exception {
+ System.out.println("Closed AutoCloseableResources_First");
+ resource1Date = new Date();
+ }
+ }
+
+ class AutoCloseableResourcesSecond implements AutoCloseable {
+ public AutoCloseableResourcesSecond() {
+ System.out.println("Constructor -> AutoCloseableResources_Second");
+ }
+
+ public void doSomething() {
+ System.out.println("Something -> AutoCloseableResources_Second");
+ }
+
+ @Override
+ public void close() throws Exception {
+ System.out.println("Closed AutoCloseableResources_Second");
+ resource2Date = new Date();
+ Thread.sleep(10000);
+ }
+ }
+
+}
diff --git a/core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java b/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java
similarity index 91%
rename from core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java
rename to core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java
index 9745655d8a..164a571817 100644
--- a/core-java-8/src/test/java/org/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java
@@ -1,14 +1,12 @@
-package org.baeldung.java8.base64;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.io.UnsupportedEncodingException;
+package com.baeldung.java8.base64;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
+import java.io.UnsupportedEncodingException;
+
+import static org.junit.Assert.*;
+
public class ApacheCommonsEncodeDecodeTest {
// tests
diff --git a/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java b/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java
similarity index 95%
rename from core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java
rename to core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java
index 7b7a0be26a..18dccf71ba 100644
--- a/core-java-8/src/test/java/org/baeldung/java8/base64/Java8EncodeDecodeTest.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java
@@ -1,14 +1,12 @@
-package org.baeldung.java8.base64;
+package com.baeldung.java8.base64;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.UUID;
-import org.junit.Test;
+import static org.junit.Assert.*;
public class Java8EncodeDecodeTest {
diff --git a/core-java-8/src/test/java/org/baeldung/java8/entity/Human.java b/core-java-8/src/test/java/com/baeldung/java8/entity/Human.java
similarity index 98%
rename from core-java-8/src/test/java/org/baeldung/java8/entity/Human.java
rename to core-java-8/src/test/java/com/baeldung/java8/entity/Human.java
index ac58b301b7..cab8546129 100644
--- a/core-java-8/src/test/java/org/baeldung/java8/entity/Human.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/entity/Human.java
@@ -1,4 +1,4 @@
-package org.baeldung.java8.entity;
+package com.baeldung.java8.entity;
public class Human {
private String name;
diff --git a/core-java/.classpath b/core-java/.classpath
index f9b079e8c9..ca829f1262 100644
--- a/core-java/.classpath
+++ b/core-java/.classpath
@@ -27,7 +27,7 @@
-
+
diff --git a/core-java/.settings/org.eclipse.jdt.core.prefs b/core-java/.settings/org.eclipse.jdt.core.prefs
index 046168cf24..1882edb712 100644
--- a/core-java/.settings/org.eclipse.jdt.core.prefs
+++ b/core-java/.settings/org.eclipse.jdt.core.prefs
@@ -6,8 +6,13 @@ org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annota
org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
-org.eclipse.jdt.core.compiler.compliance=1.7
+org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
+org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
+org.eclipse.jdt.core.compiler.compliance=1.8
+org.eclipse.jdt.core.compiler.debug.lineNumber=generate
+org.eclipse.jdt.core.compiler.debug.localVariable=generate
+org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
@@ -92,4 +97,4 @@ org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.7
+org.eclipse.jdt.core.compiler.source=1.8
diff --git a/core-java/.settings/org.eclipse.wst.common.project.facet.core.xml b/core-java/.settings/org.eclipse.wst.common.project.facet.core.xml
index bc0009a455..f4ef8aa0a5 100644
--- a/core-java/.settings/org.eclipse.wst.common.project.facet.core.xml
+++ b/core-java/.settings/org.eclipse.wst.common.project.facet.core.xml
@@ -1,4 +1,4 @@
-
+
diff --git a/core-java/README.md b/core-java/README.md
index 772681ad57..23fe12465f 100644
--- a/core-java/README.md
+++ b/core-java/README.md
@@ -6,4 +6,10 @@
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
- [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file)
- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string)
-
+- [Converting between an Array and a List in Java](http://www.baeldung.com/convert-array-to-list-and-list-to-array)
+- [Converting between an Array and a Set in Java](http://www.baeldung.com/convert-array-to-set-and-set-to-array)
+- [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list)
+- [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set)
+- [Java – Write to File](http://www.baeldung.com/java-write-to-file)
+- [Java Scanner](http://www.baeldung.com/java-scanner)
+- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
diff --git a/core-java/pom.xml b/core-java/pom.xml
index c6f2b32cd8..cb194a6d9f 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -1,15 +1,19 @@
4.0.0
- org.baeldung
+ com.baeldung
core-java
- 0.1-SNAPSHOT
+ 0.1.0-SNAPSHOT
core-java
-
+
+ net.sourceforge.collections
+ collections-generic
+ 4.01
+
com.google.guava
guava
@@ -79,7 +83,7 @@
junit
- junit-dep
+ junit
${junit.version}
test
@@ -122,8 +126,8 @@
maven-compiler-plugin
${maven-compiler-plugin.version}
- 1.7
- 1.7
+ 1.8
+ 1.8
@@ -143,44 +147,40 @@
-
- 4.1.5.RELEASE
- 3.2.5.RELEASE
-
- 4.3.10.Final
- 5.1.35
+ 4.3.11.Final
+ 5.1.38
- 2.4.4
+ 2.7.2
- 1.7.12
+ 1.7.13
1.1.3
5.1.3.Final
- 18.0
+ 19.0
3.4
1.3
- 4.11
+ 4.12
1.10.19
4.4.1
4.5
- 2.4.1
+ 2.9.0
- 3.3
+ 3.5.1
2.6
- 2.18.1
+ 2.19.1
2.7
- 1.4.14
+ 1.4.18
diff --git a/core-java/src/main/java/com/baeldung/enums/Pizza.java b/core-java/src/main/java/com/baeldung/enums/Pizza.java
new file mode 100644
index 0000000000..7742781081
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/enums/Pizza.java
@@ -0,0 +1,110 @@
+package com.baeldung.enums;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.collections15.Predicate;
+
+import java.io.IOException;
+import java.util.EnumMap;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class Pizza {
+
+ private static EnumSet undeliveredPizzaStatuses =
+ EnumSet.of(PizzaStatus.ORDERED, PizzaStatus.READY);
+
+ private PizzaStatus status;
+
+ @JsonFormat(shape = JsonFormat.Shape.OBJECT)
+ public enum PizzaStatus {
+ ORDERED(5) {
+ @Override
+ public boolean isOrdered() {
+ return true;
+ }
+ },
+ READY(2) {
+ @Override
+ public boolean isReady() {
+ return true;
+ }
+ },
+ DELIVERED(0) {
+ @Override
+ public boolean isDelivered() {
+ return true;
+ }
+ };
+
+ private int timeToDelivery;
+
+ public boolean isOrdered() {
+ return false;
+ }
+
+ public boolean isReady() {
+ return false;
+ }
+
+ public boolean isDelivered() {
+ return false;
+ }
+
+ @JsonProperty("timeToDelivery")
+ public int getTimeToDelivery() {
+ return timeToDelivery;
+ }
+
+ PizzaStatus(int timeToDelivery) {
+ this.timeToDelivery = timeToDelivery;
+ }
+ }
+
+ public PizzaStatus getStatus() {
+ return status;
+ }
+
+ public void setStatus(PizzaStatus status) {
+ this.status = status;
+ }
+
+ public boolean isDeliverable() {
+ return this.status.isReady();
+ }
+
+ public void printTimeToDeliver() {
+ System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
+ }
+
+ public static List getAllUndeliveredPizzas(List input) {
+ return input.stream().filter(
+ (s) -> undeliveredPizzaStatuses.contains(s.getStatus()))
+ .collect(Collectors.toList());
+ }
+
+ public static EnumMap>
+ groupPizzaByStatus(List pzList) {
+ return pzList.stream().collect(
+ Collectors.groupingBy(Pizza::getStatus,
+ () -> new EnumMap<>(PizzaStatus.class), Collectors.toList()));
+ }
+
+ public void deliver() {
+ if (isDeliverable()) {
+ PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
+ this.setStatus(PizzaStatus.DELIVERED);
+ }
+ }
+
+ public static String getJsonString(Pizza pz) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pz);
+ }
+
+ private static Predicate thatAreNotDelivered() {
+ return entry -> undeliveredPizzaStatuses.contains(entry.getStatus());
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java b/core-java/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java
new file mode 100644
index 0000000000..ed65919387
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java
@@ -0,0 +1,18 @@
+package com.baeldung.enums;
+
+public enum PizzaDeliveryStrategy {
+ EXPRESS {
+ @Override
+ public void deliver(Pizza pz) {
+ System.out.println("Pizza will be delivered in express mode");
+ }
+ },
+ NORMAL {
+ @Override
+ public void deliver(Pizza pz) {
+ System.out.println("Pizza will be delivered in normal mode");
+ }
+ };
+
+ public abstract void deliver(Pizza pz);
+}
diff --git a/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java b/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java
new file mode 100644
index 0000000000..a276b3c000
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java
@@ -0,0 +1,21 @@
+package com.baeldung.enums;
+
+public enum PizzaDeliverySystemConfiguration {
+ INSTANCE;
+
+ PizzaDeliverySystemConfiguration() {
+ // Do the configuration initialization which
+ // involves overriding defaults like delivery strategy
+ }
+
+ private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
+
+ public static PizzaDeliverySystemConfiguration getInstance() {
+ return INSTANCE;
+ }
+
+ public PizzaDeliveryStrategy getDeliveryStrategy() {
+ return deliveryStrategy;
+ }
+
+}
diff --git a/core-java/src/main/webapp/WEB-INF/api-servlet.xml b/core-java/src/main/webapp/WEB-INF/api-servlet.xml
deleted file mode 100644
index 4c74be8912..0000000000
--- a/core-java/src/main/webapp/WEB-INF/api-servlet.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/core-java/src/main/webapp/WEB-INF/web.xml b/core-java/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 935beae648..0000000000
--- a/core-java/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-
-
-
- Spring MVC Application
-
-
-
- contextClass
-
- org.springframework.web.context.support.AnnotationConfigWebApplicationContext
-
-
-
- contextConfigLocation
- org.baeldung.config
-
-
-
- org.springframework.web.context.ContextLoaderListener
-
-
-
-
- api
- org.springframework.web.servlet.DispatcherServlet
- 1
-
-
- api
- /
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/core-java/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java b/core-java/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java
index 95b79810cd..a5f684a141 100644
--- a/core-java/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java
+++ b/core-java/src/test/java/org/baeldung/java/collections/JavaCollectionConversionUnitTest.java
@@ -31,7 +31,7 @@ public class JavaCollectionConversionUnitTest {
@Test
public final void givenUsingCoreJava_whenListConvertedToArray_thenCorrect() {
- final List sourceList = Lists. newArrayList(0, 1, 2, 3, 4, 5);
+ final List sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
final Integer[] targetArray = sourceList.toArray(new Integer[sourceList.size()]);
}
diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java
new file mode 100644
index 0000000000..a6814ee600
--- /dev/null
+++ b/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java
@@ -0,0 +1,80 @@
+package org.baeldung.java.enums;
+
+
+import com.baeldung.enums.Pizza;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.EnumMap;
+import java.util.List;
+
+import static junit.framework.TestCase.assertTrue;
+
+
+public class PizzaTest {
+ @Test
+ public void givenPizaOrder_whenReady_thenDeliverable() {
+ Pizza testPz = new Pizza();
+ testPz.setStatus(Pizza.PizzaStatus.READY);
+ assertTrue(testPz.isDeliverable());
+ }
+
+ @Test
+ public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
+ List pzList = new ArrayList<>();
+ Pizza pz1 = new Pizza();
+ pz1.setStatus(Pizza.PizzaStatus.DELIVERED);
+
+ Pizza pz2 = new Pizza();
+ pz2.setStatus(Pizza.PizzaStatus.ORDERED);
+
+ Pizza pz3 = new Pizza();
+ pz3.setStatus(Pizza.PizzaStatus.ORDERED);
+
+ Pizza pz4 = new Pizza();
+ pz4.setStatus(Pizza.PizzaStatus.READY);
+
+ pzList.add(pz1);
+ pzList.add(pz2);
+ pzList.add(pz3);
+ pzList.add(pz4);
+
+ List undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
+ assertTrue(undeliveredPzs.size() == 3);
+ }
+
+ @Test
+ public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
+
+ List pzList = new ArrayList<>();
+ Pizza pz1 = new Pizza();
+ pz1.setStatus(Pizza.PizzaStatus.DELIVERED);
+
+ Pizza pz2 = new Pizza();
+ pz2.setStatus(Pizza.PizzaStatus.ORDERED);
+
+ Pizza pz3 = new Pizza();
+ pz3.setStatus(Pizza.PizzaStatus.ORDERED);
+
+ Pizza pz4 = new Pizza();
+ pz4.setStatus(Pizza.PizzaStatus.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);
+ }
+
+ @Test
+ public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
+ Pizza pz = new Pizza();
+ pz.setStatus(Pizza.PizzaStatus.READY);
+ pz.deliver();
+ assertTrue(pz.getStatus() == Pizza.PizzaStatus.DELIVERED);
+ }
+}
diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java
index c139e34afb..24213ba869 100644
--- a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java
+++ b/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java
@@ -1,5 +1,6 @@
package org.baeldung.java.io;
+import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.Assert.assertTrue;
import java.io.File;
@@ -57,9 +58,8 @@ public class JavaFileIntegrationTest {
@Test
public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException {
- final Path fileToMovePath = Files.createFile(Paths.get("src/test/resources/fileToMove.txt"));
- final Path dirPath = Paths.get("src/test/resources/");
- final Path targetPath = Files.createDirectory(dirPath);
+ final Path fileToMovePath = Files.createFile(Paths.get("src/test/resources/" + randomAlphabetic(5) + ".txt"));
+ final Path targetPath = Paths.get("src/main/resources/");
Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName()));
}
diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java
index 35ec15df16..eb393668bd 100644
--- a/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java
+++ b/core-java/src/test/java/org/baeldung/java/io/JavaXToWriterUnitTest.java
@@ -1,5 +1,7 @@
package org.baeldung.java.io;
+import static org.junit.Assert.assertEquals;
+
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
@@ -23,6 +25,8 @@ public class JavaXToWriterUnitTest {
final Writer targetWriter = new StringWriter().append(new String(initialArray));
targetWriter.close();
+
+ assertEquals("With Java", targetWriter.toString());
}
@Test
@@ -40,6 +44,8 @@ public class JavaXToWriterUnitTest {
charSink.write(buffer);
stringWriter.close();
+
+ assertEquals("With Guava", stringWriter.toString());
}
@Test
@@ -48,6 +54,8 @@ public class JavaXToWriterUnitTest {
final Writer targetWriter = new StringBuilderWriter(new StringBuilder(new String(initialArray)));
targetWriter.close();
+
+ assertEquals("With Commons IO", targetWriter.toString());
}
}
diff --git a/dependency-injection/.gitignore b/dependency-injection/.gitignore
new file mode 100644
index 0000000000..6531dfc93f
--- /dev/null
+++ b/dependency-injection/.gitignore
@@ -0,0 +1,12 @@
+RemoteSystemsTempFiles/
+.classpath
+.project
+.settings/
+bin/
+.metadata/
+docs/*.autosave
+docs/*.autosave
+.recommenders/
+build/
+.gradle/
+.DS_Store
diff --git a/dependency-injection/build.gradle b/dependency-injection/build.gradle
new file mode 100644
index 0000000000..968636154d
--- /dev/null
+++ b/dependency-injection/build.gradle
@@ -0,0 +1,43 @@
+apply plugin: 'java'
+apply plugin: 'eclipse'
+
+allprojects {
+ apply plugin: 'java'
+ sourceCompatibility = 1.6
+ targetCompatibility = 1.6
+}
+
+repositories {
+ mavenCentral()
+}
+
+sourceSets {
+ main {
+ resources.srcDirs = ["src/main/java","src/main/resources"]
+ }
+ test {
+ resources.srcDirs = ["src/main/java", "src/main/resources", "src/test/resources"]
+ }
+}
+
+configurations {
+ compile
+}
+
+test {
+ testLogging {
+ events 'started', 'passed'
+ }
+}
+
+dependencies {
+ testCompile('junit:junit:4.11')
+ testCompile('org.mockito:mockito-all:1.10.19')
+ testCompile group: 'org.springframework', name: 'spring-test', version: '4.2.6.RELEASE'
+ testCompile group: 'org.springframework', name: 'spring-core', version: '4.2.6.RELEASE'
+ testCompile group: 'org.springframework', name: 'spring-beans', version: '4.2.6.RELEASE'
+ testCompile group: 'org.springframework', name: 'spring-context', version: '4.2.6.RELEASE'
+ testCompile group: 'javax.inject', name: 'javax.inject', version: '1'
+
+ testRuntime('junit:junit:4.11')
+}
diff --git a/dependency-injection/docs/autowired-name-demo-classdiagram.png b/dependency-injection/docs/autowired-name-demo-classdiagram.png
new file mode 100644
index 0000000000..f367fdbf41
Binary files /dev/null and b/dependency-injection/docs/autowired-name-demo-classdiagram.png differ
diff --git a/dependency-injection/docs/autowired-type-demo-classdiagram.png b/dependency-injection/docs/autowired-type-demo-classdiagram.png
new file mode 100644
index 0000000000..5f3f341556
Binary files /dev/null and b/dependency-injection/docs/autowired-type-demo-classdiagram.png differ
diff --git a/dependency-injection/docs/autowired-type-demo-classdiagram.xml b/dependency-injection/docs/autowired-type-demo-classdiagram.xml
new file mode 100644
index 0000000000..71dc839457
--- /dev/null
+++ b/dependency-injection/docs/autowired-type-demo-classdiagram.xml
@@ -0,0 +1 @@
+7Vjvb+I4EP1rkO4+7KkhhW0/8qt3J3V1Velq7z5VbmKIb50M55hS9q/fGXtMEgLXrprthwqEEH6ZOJ5573nAvXiSP/1uxCr7BKnUvf5Z+tSLp71+/6If4ycBWw8MBpceWBqVeiiqgLn6Jhk8Y3StUlk2Ai2AtmrVBBMoCpnYBiaMgU0zbAG6+dSVWIYnVsA8EbqNflGpzUJawwr/Q6plFp4cDTm/B5F8XRpYF/y8Xj9euJe/nIswFydaZiKFTQ2KZ1hWA4Az07f8aSI1lTaUzd93deTqbt1GFry2Z24I67DbkLtMsRQ8BGMzWEIh9KxCxy4/STOc4SizucavEX7Fh5rt34y7wT80+G3ghumImKFZV7K4y1Th0SuFK/K3/Cut3bIaxNoCQtUKrgFW/By/Zlro0bQZKmFtEo7CsROSMEvJUR93JUclS8glLhlDjNTCqsfm7II1tdzF8a2YlqC7QsAKVGHL2sw3BGAAuyO6HPgZ2Rz9yC0jcIRf/IxhVFtaBTkeD3PKeT4KveYMrpTU6QgLulFGplOZQ4v1cqNyLQqit0boAgobtEBjodUSaZsmWGdpEHiUxir0zYgvWOJonGRKp9diC2uqc2nRFGE0zsCobzitCM/Ay8Yy6WiwesSc7mRtGFlizE2gmO700LUoCaCYBLQWq1I97BacI9mqGIO1kHNQyJR0NwENmAYWINg0iIsSk4GwI/JqC4dvCO5mgmNmZFNtJfGAQ7LaNnJ5cVxpNXX8L/m88dbI/0AbIAlgKtF3qSwSXNYIwZF5UNYIs61d2JcF1sCRVkmitAa+ylC4ApxkFrVaMhSkouWCZjgslHIlElUsr13M9LxCbrkqBG0yZeUccVrTBvsNbQs430K73SRTKa7dbUtWWOG5J6LZh5jHYIxvLPiEtqIB5jXBMVIYxvimcGMnUGB+guwaTyUKayNJXC/ThGO5rYngcu4dz4kgxL1GBOctEbSI1Wrf657Y0O6c+3+Y1Ry5cC2CabxzW/YHN32D6rhNNUH7FGrxIPUNlMoqoPmNj92j9g3YG7zQwh04mJtDgzxMYd/D958+z+/ux7P70ee7v778eTub3k/AGPw1pNnfj4BTngz9syQxZPrfwtA8RU0TL9m8Tz29w54+PG829egje73GfxQ00ejqjL2Gf/8Dcb+ru93Re31uDZrs5PZXuN157Efa90G2u3A7C+vUvjtj70D7PsheB+2bDwJa7duC9+gvv54c+yacH+jPP82xEa+uxvqt/G+N/7bdOcAzDLued7SOVCo6DKG+uNeyX0I1e5h47aALRhfNLrj7q1ur8sEid9AEo/bBRjjleSfVHfJJ0O43xiWPa9UNley8uu2Tg3dW3eiCBRSqG/Nfre6ri8PqDNcf4VXn5PHsOw==
\ No newline at end of file
diff --git a/dependency-injection/docs/inject-demo-classdiagram.png b/dependency-injection/docs/inject-demo-classdiagram.png
new file mode 100644
index 0000000000..9996fdc733
Binary files /dev/null and b/dependency-injection/docs/inject-demo-classdiagram.png differ
diff --git a/dependency-injection/docs/inject-field-demo-classdiagram.png b/dependency-injection/docs/inject-field-demo-classdiagram.png
new file mode 100644
index 0000000000..e63b6e5f42
Binary files /dev/null and b/dependency-injection/docs/inject-field-demo-classdiagram.png differ
diff --git a/dependency-injection/docs/inject-field-demo-classdiagram.xml b/dependency-injection/docs/inject-field-demo-classdiagram.xml
new file mode 100644
index 0000000000..147c545a2d
--- /dev/null
+++ b/dependency-injection/docs/inject-field-demo-classdiagram.xml
@@ -0,0 +1 @@
+7Vhdb9s4EPw1fuwhtqK0eYw/ctdDeijqHO7uyWAkWmJLcX0UFcf99d2llpZkKUiKOHkobBiGOVx+zcxybY2iWfHwuxWb/BOkUo8mZ+nDKJqPJpMPkwg/CdjVQBxf1kBmVVpD4wZYqu+SwTNGK5XKshPoALRTmy6YgDEycR1MWAvbbtgadHfVjcjCig2wTITuo/+o1OXhWBcN/odUWR5WHl/w+e5E8i2zUBlebzSJ1v5VdxcizMUHLXORwrYFRQuk1QLgzPSteJhJTdQG2upx14/07vdtpeG9PTEg7MPtwtllilRwE6zLIQMj9KJBp/58kmY4w1buCo1fx/gVF7W7fxn3jf+o8Vvsm+kVKUOzbqS5zZWp0WuFO6qHfJXO7dgNonKAULODG4ANr1PvmTb66LEZKqGyCUdh2xtJ2Exy1Ps95ehkCYXELWOIlVo4dd+dXbCnsn1cwyt+YWqHaeal74WueNJrJXX60XxF985lAT0Vyq0qtDBEd4vgNRgXtKG20CpDGucJnltaBO6ldQp9fMUdjjibJrnS6Y3YQUXnLh2aNLSmOVj1HacVYQ3sto5FQMO3I5Y0krWyssSYz4FyGllDN6IkgGIS0FpsSnW333CB5CszBeeg4KBwUvLBDDTgMZCAkDZBbDqY5OvlMbn7QoYB7HK+jUJz26R2FDOWt9P6gsGXSM83YUv6d9TrlR/PJaZCKk2CO7tC+MreKWeF3bU6Dp2BNHjdGleUzsI3Gbgz4F2zbtHJUHCLlmuaYdgr5UYkymQ3PmZ+3iBfmBiCtrlycok47WmLJYAyFedba5/guUpx7/6mcMKJWn7SegPKOE9mPMU30juj2yHGc82wjSqGNr4p3LoZGDyfwHE4TKK3tpL89Txb+Lzr24J9EK7zp3wQ4l5ig/OeDXrCanWY7rWwoQL5C+CnVS1QC39rs4y3/hZ956fvSB31pSboUEIt7qT+DKVyCmh+W8ceSPsG6sXM4FPqfXi5ePGAeHiEszVd4k2qrj79vbxdTRerj3/9uZjdLuarZZUksizXldac4feAk55S+rVMEW7st0hpnqLliudc36fCfsTCHr/vVvaIk70l/76It+W/PEJh978de4XdX491qi+dxRw7JfsLkt2n2M/U70G1j5HsbKxT/T6aegP1e1C9I9Rv/nPeq98OOEdP+foWig8U51fL1zHvrqX5F/l/pbCUPUNhX/Ae5ZGooscTVBQP6vVzpOYMJl2PUALPw88bJvmS/3C2SB7k+AgVcNx/rBEeu/wi5EYHvy8u+hUnEHl0cvsPDn4xcuMD58avRi42m0eqvq/12Dpa/AA=
\ No newline at end of file
diff --git a/dependency-injection/docs/inject-name-demo-classdiagram.png b/dependency-injection/docs/inject-name-demo-classdiagram.png
new file mode 100644
index 0000000000..96a6a3425e
Binary files /dev/null and b/dependency-injection/docs/inject-name-demo-classdiagram.png differ
diff --git a/dependency-injection/docs/inject-name-demo-classdiagram.xml b/dependency-injection/docs/inject-name-demo-classdiagram.xml
new file mode 100644
index 0000000000..5a8bb9f8c4
--- /dev/null
+++ b/dependency-injection/docs/inject-name-demo-classdiagram.xml
@@ -0,0 +1 @@
+7VhZbxs3EP41AtqHFDqydvOoy20KJwgiF2meDHp3pGXC5ahcyrLy6zPkDrWnYQVe5yGQIAjit8Njvm8OiYPJPHv4y4ht+g4TUIPxMHkYTBaD8fjP8YQ+HXAogCh6UwAbI5MCGpXASn4DBoeM7mQCec3QIiort3UwRq0htjVMGIP7utkaVX3XrdiEHUtgFQvVRj/JxKbBrYsS/xvkJg07jy7YvzsRf90Y3GnebzCerP2reJyJsBY7mqciwX0FmiyJVoNIK7tv2cMclKM20FbMu3rk6fHcBjSf7YkJ4Rz2EHyHhKjgIRqb4ga1UMsSnXn/wK0wpFFqM0VfR/SVNjWH/xj3g89u8Efkh8nUKeNW3YK+SaUu0CtJJyqmfAFrDxwNYmeRoPIE14hb3qc4szvoo24zlOPOxGxFYx9IwmyArS6PlFMkA2ZARyYTA0pYeV9fXXBMbY52Ja/0hantppm3vhdqx4teSVDJ7PBeZPBWf6EYXkCGLS3yvcyU0I70Cs1r1DYo5MZCyQ2RuYjJezAE3IOxkqJ5yg+sY24Wp1Il1+KAO+d9bilUw2iWopHfaFkR9qDHxrIUFPZVi5WbyYoZyMnmQyDezSyga5E7wNnEqJTY5vLueOCMJJB6htZixkbBUxcNc1RIbhABIXmC5M4x4CLzmOhtOUNVKiZwSQqRvy/ze3LJOqWV3H7Dds+Rn6thRf5XNNSkfbIASoYEdEzHmhI4NXfSGmEOlQfNqCAKvGZlROTW4FcIvGn0EbOuUMlQiBQFa7dCd5zkWxFLvbn2NovXJfKRWXHQPpUWVoS7M+2pCbhcpfXWyqd4KhM6u68VVlhRSO903qLU1lMZzehN5M5dfYjIrzmNScEwprczN3aOmvwTNI+mAcXVHlxsnRYSXtF2SHAQhIL+VBAEu+cEwetWELSEVbKZ6oWwoQf55P9hVTPSwtdtlvHG19FXfvma1JO21A5qSqjEHagPmEsr0a1vCtuGtD9BvYgZfEo9TvzniBd1iEcuNHP49t2/q5vb2fL27ft/lvOb5eJ2jsZQdVec3itriN1zRr9YTFycWNb7yGheohIUn8FONdoUzCl1/Nzde+zuUWjUob+P2rX9+LO71uC5Oz8nEvzvyFaD94XynPc95b2X80c6eafafeQ995NzJ+9NvY5O3qleD52c/6i3OrnFIkd/+/2csT9F845O/WIZO+LTVVT/CP/vJHWzExT2Pe9RHh1V7rLC9cVGyz5Fas5hp2sPXXDU7IIRp0yF5UB8jeQe/uWO2rcc4RbmF2E3umywe9FRt16K3fYlwi/G7njYYHfY0dP7YZeG5R2rf1a5x54svwM=
\ No newline at end of file
diff --git a/dependency-injection/docs/inject-qualifier-demo-classdiagram.png b/dependency-injection/docs/inject-qualifier-demo-classdiagram.png
new file mode 100644
index 0000000000..1ffe6453cb
Binary files /dev/null and b/dependency-injection/docs/inject-qualifier-demo-classdiagram.png differ
diff --git a/dependency-injection/docs/inject-qualifier-demo-classdiagram.xml b/dependency-injection/docs/inject-qualifier-demo-classdiagram.xml
new file mode 100644
index 0000000000..ec122afe71
--- /dev/null
+++ b/dependency-injection/docs/inject-qualifier-demo-classdiagram.xml
@@ -0,0 +1 @@
+7Vptb+I4EP41le4+bEUIUPZjeenenrqn3tLT3X6qTGIS7zox5zil7K/fcTLTvHbhFOAkBEKAx87EM88zL7G4cqfRywfN1uEn5XN51e/5L1fu7KrfH/dd+LSCbS4Y9VAQaOHnIqcQLMR3jsIeSlPh86Sy0CgljVhXhZ6KY+6ZioxprTbVZSslq3dds4DuWAgWHpNN6d/CNyGZNSrkv3ERhHRnZ/Q+n1ky71ugVRrj/a767ip75dMRI11oaBIyX21KIncObtVKgWb7K3qZcmldS27Lr7t7Y/Z135rHuLcdF9A+zJZs5z64AodKm1AFKmZyXkgnmX3caujBKDSRhJ8O/ISb6u0/KM8GX+zgepgN/VuLjNW65vFjKOJceidgR/klX7kxW2QDS40CUbGDe6XWeJ+mlWh4olLtoR0wznjDdMBx1U0ushaWLkPPfOAq4rBlWKC5ZEY8V8nAkFPB67rCr/ADXdvuZtzLM5MpKr0TXPp/pkyKleD6Y/wVaDzjkWrAkWxEJFls/V7y9ErFhkCyY9ATgD9nHniEaxA8c20EEPoWJ4x13sQLhfTv2Val1iOJAbbSaBIqLb6DWkb3gGltEA1gfnnFwl6JoGmewJoHAsNemYvuWWIFdo2npGTrRCxfNxwBLCKeKGNUhIvIUkuIqZIKzAAHUPz8BHVrK8fU8waiNIt0x7REw00R4+4NysJKfKOwCwcwA5Y48M5mSL5iqQToISZ8Hnuws1sQ3+qlMJrpbWmiP5IWJ188w8/A/gQFIxZZYONlkn2xiPs1XdUVP1EMBpR0N4gILs5oUpAwMVp94wRVrDKSrkrooYjIKfnKaminZrJmnoiD+2zNbFBIPiMOVrQJheELkNs9baD02AwB+lYySyyh8MGiLEMZZljONkuttRKxybAbTuANaE5tVhqCXVMYA2loDG+7XJupisE+BtfBZRyovOGWzi0spODezUKkHZWRXbQbDLqzDlWUWNcAVop6dsmBpcqX5Zv/jGoEWGTVAmF8zLL3u0x9BWq3CbUV1SGUbMnlg0qEEcrq1/naGrQnQI+Q2oXeuDt4DhLlDKvzsFmdHYTi9OUZN1MJEjCjB6VZltLp06e/Fo9Pk/nTxz9+n08f57OnRep5PElWqZTbX37NU/ezArWX5Lln+HUt4WPs6XZFo4vltwtNMBpLNGmtppcG7ngN3IgenKiDQ1hL8DujFvjfH6CBQ6bVGrisLuWRvzAaQu4S+/vGPsVTl8apFW1a1wVtLN+Xxulg6A3Rg7vQO0DjhKcxjYJuVB6jVKsvEXtkzAnfU0Ssg23cobvl6xuoMqWO2bnuuWMSPHAtYKe2ZGNf/dpIL6WyNfaYXbRDh6OlNhq5f/oumjZT7o9iZUKuL23Siduk4bjaJrmDZhz2e20nXSTsRITmceelU+r2lLQ/A95ulVoBP0jibR5tXnqljvi1NEut+B3ilKntjPDSLf0fUdvSLh0vapvPs5/5v6mAorYHxFnpe9OR1le2ubHlsVa598Eaw9gCe4BiOKgXw2Zotbakh6iEzafIM/XxsObj8Qmd3Hzao1b5TLzr0vEVpYnmoSc58tDOJR3n69xhzbkt6eFozm0+MZ0bc2u516FgPYV3m48h50ZdSqlE3eHRvAvD4l9J2Vzpn1/u/Ac=
\ No newline at end of file
diff --git a/dependency-injection/docs/resource-demo-classdiagram.png b/dependency-injection/docs/resource-demo-classdiagram.png
new file mode 100644
index 0000000000..1f0a41a19e
Binary files /dev/null and b/dependency-injection/docs/resource-demo-classdiagram.png differ
diff --git a/dependency-injection/docs/resource-field-demo-classdiagram.png b/dependency-injection/docs/resource-field-demo-classdiagram.png
new file mode 100644
index 0000000000..0d6207d09a
Binary files /dev/null and b/dependency-injection/docs/resource-field-demo-classdiagram.png differ
diff --git a/dependency-injection/docs/resource-field-demo-classdiagram.xml b/dependency-injection/docs/resource-field-demo-classdiagram.xml
new file mode 100644
index 0000000000..44c742f2bc
--- /dev/null
+++ b/dependency-injection/docs/resource-field-demo-classdiagram.xml
@@ -0,0 +1 @@
+7Vhtb+I4EP41SHcftgICtP1YoN1bqXtalZ7u7lPlJiZx1/HkHANlf/3OOGOSEPpyonfaOxUhFD8ejz3zzItDL5rljx+tKLLPkEjdG/aTx1407w2HZ8MIfwnYVsB4fF4BqVVJBQ1qYKG+SQb7jK5UIsuWoAPQThVtMAZjZOxamLAWNm2xJej2roVIw441sIiF7qK/q8RlwaxJjf8iVZqFnQcTtu9exF9TCyvD+/WG0dJ/qulcBF1saJmJBDYNKLpEt1oA1ExP+eNManJtcFu17uqJ2d25rTR8tucX4BQtWAu9YtN7w4nGpdMCH1J6uFJSJzeyhJWN5SfzgP5WYOYyhyCK6nfSbJbbBleWG5VrYXA0zVyuERzg4xKMW7AQjYVWqcHnGM8tLQJraZ1CQi54wkGBaJwpnVyLLazIutKht8NomoFV31CtCHvgtHUcW6PzlsSCViLcR9TKEmW+BJfRygq6FiUBJBOD1qIo1f3uwLmwqTJTcA5yFgqWXimtZ6ABzUAHBP6Da5rcMF1kq+TU8RBz9VFCLp3dokiY5bDhtBpxmm3qGI1GLJI14/OUBQXnRbrTXMcGPnB4HA4VVtEIlQ+U4XIpVtqhzQheIPAg1uJEwYlH9oMBzfRU1YFQOgtfZXCXAR8oy4YHGQoBouWSNBwOj7IQsTLptZeZj2rkhn1B0CZTTi4QpzNtsHwhBqhvqX0iZipJJKqcWnDCiYpxorcAZZz333iKX3TzrH8y7o3RrhmOkbgwxi+JWzcDg/YJXIfLJIbTRlJIHYiEkIcvR0KgngvOS9RHXLKOYX50oEjsEavVfoZXxIbq6XP+b7OaIxe0Q6Dxllief/DqW1RHXaoJ2qdQi3upv0CpqIIhZivZPWr/BfbOxq9j7+x48ninFnloQr/QaFko6xfGkKvQK3eff1vc3l19+nV+N69T+6efq+ReA6p9T+p/KizOX1nPx4wdExennbh4tnL/GG0cL2A/SBvvkHqgsz/Zxk/77T4+CNfBBvGDyaF6wCF1DPHcON6reTNtX6DTJ8uTaRteC15ib8SN9KhbGJ+uwZZM8N2Fh2hoBikYoS9rFD2HLySSNJDfGrSigXb7B+N+8CcNsOLRMLmgVynSWkhzmykqoIhSYvCSB+nclnNTrBxQ1d2d4Bo8wbRPdWY66PMZg3b5ftS6cWL+p/J5IqzU2L3Wbe1Hubn7YnQj/1opLCmv6H++8DzZZSgiyVlUnPbq5msaIacNdb03KEXjvVeKwaQbzIdiOVSso5zcfaXoRvd/2rtR6NTh3te9tQdHvrlzu7f2/5lzJ6fszRC6I1bx9t7FYf2fjJ9r/O8VXX4H
\ No newline at end of file
diff --git a/dependency-injection/docs/resource-method-byname-demo-classdiagram.png b/dependency-injection/docs/resource-method-byname-demo-classdiagram.png
new file mode 100644
index 0000000000..c5cd0c0fcb
Binary files /dev/null and b/dependency-injection/docs/resource-method-byname-demo-classdiagram.png differ
diff --git a/dependency-injection/docs/resource-method-demo-classdiagram.png b/dependency-injection/docs/resource-method-demo-classdiagram.png
new file mode 100644
index 0000000000..6be7dbbeea
Binary files /dev/null and b/dependency-injection/docs/resource-method-demo-classdiagram.png differ
diff --git a/dependency-injection/docs/resource-method-demo-classdiagram.xml b/dependency-injection/docs/resource-method-demo-classdiagram.xml
new file mode 100644
index 0000000000..94b39279fc
--- /dev/null
+++ b/dependency-injection/docs/resource-method-demo-classdiagram.xml
@@ -0,0 +1 @@
+3Vhbb+I6EP41SN0HECGQbh8boNuutkerltXZ84QMcRL3OHFqHAr99R0749y4qCpdqV0eQvx5PJ755mJDxx0nm2+SZPGtCCjvDPrBpuNOOoPB14ELTw1sC2A0uiiASLKggJwKuGfPFME+ojkL6KohqITgimVNcCnSlC5VAyNSiqemWCh4c9eMRHbHCrhfEr6L/ssCFVu3vAq/piyK7c6Oh/4tyPL/SIo8xf06Azc0n2I6IVYXOrqKSSCeapA7BVqlEKBZvyWbMeWaWktbse7qwGxpt6Qp2nZ8ATq0UlvrOg2ACRwKqWIRiZTwaYX6xj2qFfRhFKuEw6sDr7Cn3P5G3Az+04PeyAyDSx0YrTWj6SxmaYFeMTCoWPJAldpiMpBcCYAqC34IkeE+hc3a0INeI7QSuVyiFKakIjKiKDUqGYdEpiKhYDKISMqJYuumdoIpFZVyFa3wgsweCAtGe014jlrv6GPOJOR4m39FN2BdnVaQYs9kYQQ0TZlgqTLWjPzOaAII4SwCOidL8J9KANZUKgbpfIkTCQsCEztOFpT7ZZKOBRcgD/vaNLXsag0Uy7lZbGhJlcN13k0+7TKKivo9DAK2he6wGL6acNT8UzNQqe2CeE2r01IgwnAFEW/HqzTvVSFEw2sR7Aw8riOVNeLnPea6dv0E0kyn+CXM9rMNPA210AE03lU6mfXcsDanQ9/FWOo5DGepE94i/DY7LyxwS6FKgjtapPtN+gBhYiKd0ERYWfCvFC/Xa90NBKTAnSYWg1QfMrDpH3B8yKw3EcJpCFIlI23dXX2Y0JDkXEHDAM1a8oGsSY+JnkHe2QMLaIwkECw/Xaz0l5VZZSTd6yhnKe3GeDpoM52ezpXWVjVn5re/7mdzfzq/+ef7dDybTuZjISWEkEPOl14V+zXtPNGGsy/F5FpAlh/faR+tO8CJ5hwh+6j/BQYlPqk4PavnxlvdbHXmdlM1NVz23iKBfQFSITfnXGhONj8UqcJDzYEOZsZXJGEQXXdyTfmaaq3Nln+wB++ccQd7rWPbM3ZFF4dP1X3G7SNmQ2PWnSN4yoFnDtaP2i0PtI2d9vhhm+En7N+vNflTl5xna8xeRIa7Ned4e2ru4h1K7nyn5Owd+MS7JVzEMXv0ghb3+wMErXXJ0mhmbuxwyXsXdodavsbuBTaZGrm25dW5tdgp3OKPu7+XW8/emW3men+MXBhWP2+Li3j1F4I7fQE=
\ No newline at end of file
diff --git a/dependency-injection/pom.xml b/dependency-injection/pom.xml
new file mode 100644
index 0000000000..46f57e512e
--- /dev/null
+++ b/dependency-injection/pom.xml
@@ -0,0 +1,81 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ dependency-injection
+ 0.0.1-SNAPSHOT
+ war
+
+ @Resource vs @Inject vs @Autowired
+ Accompanying the demonstration of the use of the annotations related to injection mechanisms, namely @Resource, @Inject, and @Autowired
+
+
+
+ junit
+ junit
+ 4.11
+ test
+
+
+ org.mockito
+ mockito-all
+ 1.10.19
+
+
+ org.springframework
+ spring-test
+ 4.2.6.RELEASE
+
+
+ org.springframework
+ spring-core
+ 4.2.6.RELEASE
+
+
+ org.springframework
+ spring-beans
+ 4.2.6.RELEASE
+
+
+ org.springframework
+ spring-context
+ 4.2.6.RELEASE
+
+
+ javax.inject
+ javax.inject
+ 1
+
+
+
+
+
+
+ maven-compiler-plugin
+
+ 1.6
+ 1.6
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ **/*Demo.java
+
+
+
+
+
+
+
+
+ java.net
+ https://maven.java.net/content/repositories/releases/
+
+
+
diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredDemo.java b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredDemo.java
new file mode 100644
index 0000000000..c71365097f
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredDemo.java
@@ -0,0 +1,27 @@
+package com.baeldung.autowired;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.baeldung.dependency.ArbitraryDependency;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations={
+ "/applicationContextTest-@Autowired-Type.xml"})
+public class FieldAutowiredDemo {
+
+ @Autowired
+ private ArbitraryDependency fieldDependency;
+
+ @Test
+ public void fieldDependency_MUST_BE_AUTOWIRED_Correctly() {
+ assertNotNull(fieldDependency);
+ assertEquals("Arbitrary Dependency", fieldDependency.toString());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameDemo.java b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameDemo.java
new file mode 100644
index 0000000000..c11ed5286a
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/autowired/FieldAutowiredNameDemo.java
@@ -0,0 +1,27 @@
+package com.baeldung.autowired;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.baeldung.dependency.ArbitraryDependency;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations={
+ "/applicationContextTest-@Autowired-Name.xml"})
+public class FieldAutowiredNameDemo {
+
+ @Autowired
+ private ArbitraryDependency autowiredFieldDependency;
+
+ @Test
+ public void autowiredFieldDependency_MUST_BE_AUTOWIRED_Correctly() {
+ assertNotNull(autowiredFieldDependency);
+ assertEquals("Arbitrary Dependency", autowiredFieldDependency.toString());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredDemo.java b/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredDemo.java
new file mode 100644
index 0000000000..5afce6ab6a
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/autowired/FieldQualifierAutowiredDemo.java
@@ -0,0 +1,39 @@
+package com.baeldung.autowired;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.baeldung.dependency.ArbitraryDependency;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations={
+ "/applicationContextTest-@Autowired-Qualifier.xml"})
+public class FieldQualifierAutowiredDemo {
+
+ @Autowired
+ @Qualifier("autowiredFieldDependency")
+ private ArbitraryDependency fieldDependency1;
+
+ @Autowired
+ @Qualifier("anotherAutowiredFieldDependency")
+ private ArbitraryDependency fieldDependency2;
+
+ @Test
+ public void fieldDependency1_MUST_BE_AUTOWIRED_Correctly() {
+ assertNotNull(fieldDependency1);
+ assertEquals("Arbitrary Dependency", fieldDependency1.toString());
+ }
+
+ @Test
+ public void fieldDependency2_MUST_BE_AUTOWIRED_Correctly() {
+ assertNotNull(fieldDependency2);
+ assertEquals("Another Arbitrary Dependency", fieldDependency2.toString());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/dependency/AnotherArbitraryDependency.java b/dependency-injection/src/test/java/com/baeldung/dependency/AnotherArbitraryDependency.java
new file mode 100644
index 0000000000..27ba03f6e8
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/dependency/AnotherArbitraryDependency.java
@@ -0,0 +1,10 @@
+package com.baeldung.dependency;
+
+public class AnotherArbitraryDependency extends ArbitraryDependency {
+
+ private final String label = "Another Arbitrary Dependency";
+
+ public String toString() {
+ return label;
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/dependency/ArbitraryDependency.java b/dependency-injection/src/test/java/com/baeldung/dependency/ArbitraryDependency.java
new file mode 100644
index 0000000000..bab289777c
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/dependency/ArbitraryDependency.java
@@ -0,0 +1,10 @@
+package com.baeldung.dependency;
+
+public class ArbitraryDependency {
+
+ private final String label = "Arbitrary Dependency";
+
+ public String toString() {
+ return label;
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java b/dependency-injection/src/test/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java
new file mode 100644
index 0000000000..1f59500ec5
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/dependency/YetAnotherArbitraryDependency.java
@@ -0,0 +1,10 @@
+package com.baeldung.dependency;
+
+public class YetAnotherArbitraryDependency extends ArbitraryDependency {
+
+ private final String label = "Yet Another Arbitrary Dependency";
+
+ public String toString() {
+ return label;
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectDemo.java b/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectDemo.java
new file mode 100644
index 0000000000..a670ee8313
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/inject/FieldByNameInjectDemo.java
@@ -0,0 +1,30 @@
+package com.baeldung.inject;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.baeldung.dependency.ArbitraryDependency;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations={
+ "/applicationContextTest-@Inject-Name.xml"})
+public class FieldByNameInjectDemo {
+
+ @Inject
+ @Named("yetAnotherFieldInjectDependency")
+ private ArbitraryDependency yetAnotherFieldInjectDependency;
+
+ @Test
+ public void yetAnotherFieldInjectDependency_MUST_BE_INJECTED_Correctly() {
+ assertNotNull(yetAnotherFieldInjectDependency);
+ assertEquals("Yet Another Arbitrary Dependency", yetAnotherFieldInjectDependency.toString());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectDemo.java b/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectDemo.java
new file mode 100644
index 0000000000..df40e516ba
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/inject/FieldInjectDemo.java
@@ -0,0 +1,27 @@
+package com.baeldung.inject;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import javax.inject.Inject;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.baeldung.dependency.ArbitraryDependency;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations={
+ "/applicationContextTest-@Inject-Type.xml"})
+public class FieldInjectDemo {
+
+ @Inject
+ private ArbitraryDependency inject1Dependency;
+
+ @Test
+ public void fieldDependency_MUST_BE_INJECTED_Successfully() {
+ assertNotNull(inject1Dependency);
+ assertEquals("Arbitrary Dependency", inject1Dependency.toString());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectDemo.java b/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectDemo.java
new file mode 100644
index 0000000000..3cc9b643c7
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/inject/FieldQualifierInjectDemo.java
@@ -0,0 +1,40 @@
+package com.baeldung.inject;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import javax.inject.Inject;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+import com.baeldung.dependency.ArbitraryDependency;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations={
+ "/applicationContextTest-@Inject-Qualifier.xml"})
+public class FieldQualifierInjectDemo {
+
+ @Inject
+ @Qualifier("defaultFile")
+ private ArbitraryDependency defaultDependency;
+
+ @Inject
+ @Qualifier("namedFile")
+ private ArbitraryDependency namedDependency;
+
+ @Test
+ public void defaultDependency_MUST_BE_INJECTED_Successfully() {
+ assertNotNull(defaultDependency);
+ assertEquals("Arbitrary Dependency", defaultDependency.toString());
+ }
+
+ @Test
+ public void namedDependency_MUST_BE_INJECTED_Correctly() {
+ assertNotNull(defaultDependency);
+ assertEquals("Another Arbitrary Dependency", namedDependency.toString());
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionDemo.java b/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionDemo.java
new file mode 100644
index 0000000000..fbb378d672
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/FieldResourceInjectionDemo.java
@@ -0,0 +1,25 @@
+package com.baeldung.resource;
+import static org.junit.Assert.assertNotNull;
+
+import java.io.File;
+
+import javax.annotation.Resource;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations={
+ "/applicationContextTest-@Resource-NameType.xml"})
+public class FieldResourceInjectionDemo {
+
+ @Resource(name="namedFile")
+ private File defaultFile;
+
+ @Test
+ public void plainResourceAnnotation_MUST_FIND_DefaultFile() {
+ assertNotNull(defaultFile);
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceDemo.java b/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceDemo.java
new file mode 100644
index 0000000000..fcca34dc2f
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/MethodByQualifierResourceDemo.java
@@ -0,0 +1,43 @@
+package com.baeldung.resource;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.io.File;
+
+import javax.annotation.Resource;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations={
+ "/applicationContextTest-@Resource-Qualifier.xml"})
+public class MethodByQualifierResourceDemo {
+
+ private File arbDependency;
+ private File anotherArbDependency;
+
+ @Test
+ public void dependencies_MUST_BE_INJECTED_Correctly() {
+ assertNotNull(arbDependency);
+ assertEquals("namedFile.txt", arbDependency.getName());
+ assertNotNull(anotherArbDependency);
+ assertEquals("defaultFile.txt", anotherArbDependency.getName());
+ }
+
+ @Resource
+ @Qualifier("namedFile")
+ public void setArbDependency(File arbDependency) {
+ this.arbDependency = arbDependency;
+ }
+
+ @Resource
+ @Qualifier("defaultFile")
+ public void setAnotherArbDependency(File anotherArbDependency) {
+ this.anotherArbDependency = anotherArbDependency;
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceDemo.java b/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceDemo.java
new file mode 100644
index 0000000000..af6a805bd9
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/MethodByTypeResourceDemo.java
@@ -0,0 +1,30 @@
+package com.baeldung.resource;
+
+import static org.junit.Assert.assertNotNull;
+
+import java.io.File;
+
+import javax.annotation.Resource;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations={
+ "/applicationContextTest-@Resource-NameType.xml"})
+public class MethodByTypeResourceDemo {
+
+ private File defaultFile;
+
+ @Resource
+ protected void setDefaultFile(File defaultFile) {
+ this.defaultFile = defaultFile;
+ }
+
+ @Test
+ public void defaultFile_MUST_BE_INJECTED_Correctly() {
+ assertNotNull(defaultFile);
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionDemo.java b/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionDemo.java
new file mode 100644
index 0000000000..d746fd4d85
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/MethodResourceInjectionDemo.java
@@ -0,0 +1,29 @@
+package com.baeldung.resource;
+import static org.junit.Assert.assertNotNull;
+
+import java.io.File;
+
+import javax.annotation.Resource;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations={
+ "/applicationContextTest-@Resource-NameType.xml"})
+public class MethodResourceInjectionDemo {
+
+ private File defaultFile;
+
+ @Resource(name="namedFile")
+ protected void setDefaultFile(File defaultFile) {
+ this.defaultFile = defaultFile;
+ }
+
+ @Test
+ public void defaultFile_MUST_BE_INJECTED_Correctly() {
+ assertNotNull(defaultFile);
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java b/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java
new file mode 100644
index 0000000000..8b218dfe98
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/NamedResourceTest.java
@@ -0,0 +1,27 @@
+package com.baeldung.resource;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+
+import javax.annotation.Resource;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations={
+ "/applicationContextTest-@Resource-NameType.xml"})
+public class NamedResourceTest {
+
+ @Resource(name="namedFile")
+ private File testFile;
+
+ @Test
+ public void namedResource_MUST_FIND_SPECIFIED_File() {
+ assertNotNull(testFile);
+ assertTrue(testFile.getName().equals("namedFile.txt"));
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionDemo.java b/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionDemo.java
new file mode 100644
index 0000000000..0aaa2085d5
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/QualifierResourceInjectionDemo.java
@@ -0,0 +1,35 @@
+package com.baeldung.resource;
+import static org.junit.Assert.assertNotNull;
+
+import java.io.File;
+
+import javax.annotation.Resource;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations={
+ "/applicationContextTest-@Resource-Qualifier.xml"})
+public class QualifierResourceInjectionDemo {
+
+ @Resource
+ private File defaultFile;
+
+ @Resource
+ @Qualifier("namedFile")
+ private File namedFile;
+
+ @Test
+ public void defaultFile_MUST_BE_Valid() {
+ assertNotNull(defaultFile);
+ }
+
+ @Test
+ public void namedFile_MUST_BE_Valid() {
+ assertNotNull(namedFile);
+ }
+}
diff --git a/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionDemo.java b/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionDemo.java
new file mode 100644
index 0000000000..25dd5bb9ff
--- /dev/null
+++ b/dependency-injection/src/test/java/com/baeldung/resource/SetterResourceInjectionDemo.java
@@ -0,0 +1,29 @@
+package com.baeldung.resource;
+import static org.junit.Assert.assertNotNull;
+
+import java.io.File;
+
+import javax.annotation.Resource;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations={
+ "/applicationContextTest-@Resource-NameType.xml"})
+public class SetterResourceInjectionDemo {
+
+ private File defaultFile;
+
+ @Resource
+ protected void setDefaultFile(File defaultFile) {
+ this.defaultFile = defaultFile;
+ }
+
+ @Test
+ public void setter_MUST_INJECT_Resource() {
+ assertNotNull(defaultFile);
+ }
+}
diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Name.xml b/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Name.xml
new file mode 100644
index 0000000000..d7fe3abcb3
--- /dev/null
+++ b/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Name.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Qualifier.xml b/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Qualifier.xml
new file mode 100644
index 0000000000..d7fe3abcb3
--- /dev/null
+++ b/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Qualifier.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Type.xml b/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Type.xml
new file mode 100644
index 0000000000..c65b85ccf4
--- /dev/null
+++ b/dependency-injection/src/test/resources/applicationContextTest-@Autowired-Type.xml
@@ -0,0 +1,10 @@
+
+
+
+
diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Inject-Name.xml b/dependency-injection/src/test/resources/applicationContextTest-@Inject-Name.xml
new file mode 100644
index 0000000000..610e8687a7
--- /dev/null
+++ b/dependency-injection/src/test/resources/applicationContextTest-@Inject-Name.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Inject-Qualifier.xml b/dependency-injection/src/test/resources/applicationContextTest-@Inject-Qualifier.xml
new file mode 100644
index 0000000000..627ec37914
--- /dev/null
+++ b/dependency-injection/src/test/resources/applicationContextTest-@Inject-Qualifier.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Inject-Type.xml b/dependency-injection/src/test/resources/applicationContextTest-@Inject-Type.xml
new file mode 100644
index 0000000000..405164e603
--- /dev/null
+++ b/dependency-injection/src/test/resources/applicationContextTest-@Inject-Type.xml
@@ -0,0 +1,10 @@
+
+
+
+
diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Resource-NameType.xml b/dependency-injection/src/test/resources/applicationContextTest-@Resource-NameType.xml
new file mode 100644
index 0000000000..82cbe97157
--- /dev/null
+++ b/dependency-injection/src/test/resources/applicationContextTest-@Resource-NameType.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
diff --git a/dependency-injection/src/test/resources/applicationContextTest-@Resource-Qualifier.xml b/dependency-injection/src/test/resources/applicationContextTest-@Resource-Qualifier.xml
new file mode 100644
index 0000000000..1680a6f66a
--- /dev/null
+++ b/dependency-injection/src/test/resources/applicationContextTest-@Resource-Qualifier.xml
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/gatling/pom.xml b/gatling/pom.xml
new file mode 100644
index 0000000000..273797d76c
--- /dev/null
+++ b/gatling/pom.xml
@@ -0,0 +1,110 @@
+
+
+ 4.0.0
+ org.baeldung
+ gatling
+ 1.0-SNAPSHOT
+
+
+ 1.8
+ 1.8
+ 2.11.7
+ UTF-8
+ 2.2.0
+ 3.2.2
+
+
+
+
+
+ io.gatling
+ gatling-app
+ ${gatling.version}
+
+
+ io.gatling
+ gatling-recorder
+ ${gatling.version}
+
+
+ io.gatling.highcharts
+ gatling-charts-highcharts
+ ${gatling.version}
+
+
+ org.scala-lang
+ scala-library
+ ${scala.version}
+
+
+
+
+
+
+ io.gatling.highcharts
+ gatling-charts-highcharts
+
+
+ io.gatling
+ gatling-app
+
+
+ io.gatling
+ gatling-recorder
+
+
+ org.scala-lang
+ scala-library
+
+
+
+
+ src/test/scala
+
+
+
+ net.alchim31.maven
+ scala-maven-plugin
+ ${scala-maven-plugin.version}
+
+
+
+
+
+ net.alchim31.maven
+ scala-maven-plugin
+
+
+
+ testCompile
+
+
+
+ -Ybackend:GenBCode
+ -Ydelambdafy:method
+ -target:jvm-1.8
+ -deprecation
+ -feature
+ -unchecked
+ -language:implicitConversions
+ -language:postfixOps
+
+
+
+
+
+
+ io.gatling
+ gatling-maven-plugin
+ ${gatling.version}
+
+
+ test
+ execute
+
+
+
+
+
+
diff --git a/gatling/src/test/resources/gatling.conf b/gatling/src/test/resources/gatling.conf
new file mode 100644
index 0000000000..8bfa0ed366
--- /dev/null
+++ b/gatling/src/test/resources/gatling.conf
@@ -0,0 +1,127 @@
+#########################
+# Gatling Configuration #
+#########################
+
+# This file contains all the settings configurable for Gatling with their default values
+
+gatling {
+ core {
+ #outputDirectoryBaseName = "" # The prefix for each simulation result folder (then suffixed by the report generation timestamp)
+ #runDescription = "" # The description for this simulation run, displayed in each report
+ #encoding = "utf-8" # Encoding to use throughout Gatling for file and string manipulation
+ #simulationClass = "" # The FQCN of the simulation to run (when used in conjunction with noReports, the simulation for which assertions will be validated)
+ #mute = false # When set to true, don't ask for simulation name nor run description (currently only used by Gatling SBT plugin)
+ #elFileBodiesCacheMaxCapacity = 200 # Cache size for request body EL templates, set to 0 to disable
+ #rawFileBodiesCacheMaxCapacity = 200 # Cache size for request body Raw templates, set to 0 to disable
+ #rawFileBodiesInMemoryMaxSize = 1000 # Below this limit, raw file bodies will be cached in memory
+
+ extract {
+ regex {
+ #cacheMaxCapacity = 200 # Cache size for the compiled regexes, set to 0 to disable caching
+ }
+ xpath {
+ #cacheMaxCapacity = 200 # Cache size for the compiled XPath queries, set to 0 to disable caching
+ }
+ jsonPath {
+ #cacheMaxCapacity = 200 # Cache size for the compiled jsonPath queries, set to 0 to disable caching
+ #preferJackson = false # When set to true, prefer Jackson over Boon for JSON-related operations
+ }
+ css {
+ #cacheMaxCapacity = 200 # Cache size for the compiled CSS selectors queries, set to 0 to disable caching
+ }
+ }
+
+ directory {
+ #data = user-files/data # Folder where user's data (e.g. files used by Feeders) is located
+ #bodies = user-files/bodies # Folder where bodies are located
+ #simulations = user-files/simulations # Folder where the bundle's simulations are located
+ #reportsOnly = "" # If set, name of report folder to look for in order to generate its report
+ #binaries = "" # If set, name of the folder where compiles classes are located: Defaults to GATLING_HOME/target.
+ #results = results # Name of the folder where all reports folder are located
+ }
+ }
+ charting {
+ #noReports = false # When set to true, don't generate HTML reports
+ #maxPlotPerSeries = 1000 # Number of points per graph in Gatling reports
+ #useGroupDurationMetric = false # Switch group timings from cumulated response time to group duration.
+ indicators {
+ #lowerBound = 800 # Lower bound for the requests' response time to track in the reports and the console summary
+ #higherBound = 1200 # Higher bound for the requests' response time to track in the reports and the console summary
+ #percentile1 = 50 # Value for the 1st percentile to track in the reports, the console summary and Graphite
+ #percentile2 = 75 # Value for the 2nd percentile to track in the reports, the console summary and Graphite
+ #percentile3 = 95 # Value for the 3rd percentile to track in the reports, the console summary and Graphite
+ #percentile4 = 99 # Value for the 4th percentile to track in the reports, the console summary and Graphite
+ }
+ }
+ http {
+ #fetchedCssCacheMaxCapacity = 200 # Cache size for CSS parsed content, set to 0 to disable
+ #fetchedHtmlCacheMaxCapacity = 200 # Cache size for HTML parsed content, set to 0 to disable
+ #perUserCacheMaxCapacity = 200 # Per virtual user cache size, set to 0 to disable
+ #warmUpUrl = "http://gatling.io" # The URL to use to warm-up the HTTP stack (blank means disabled)
+ #enableGA = true # Very light Google Analytics, please support
+ ssl {
+ keyStore {
+ #type = "" # Type of SSLContext's KeyManagers store
+ #file = "" # Location of SSLContext's KeyManagers store
+ #password = "" # Password for SSLContext's KeyManagers store
+ #algorithm = "" # Algorithm used SSLContext's KeyManagers store
+ }
+ trustStore {
+ #type = "" # Type of SSLContext's TrustManagers store
+ #file = "" # Location of SSLContext's TrustManagers store
+ #password = "" # Password for SSLContext's TrustManagers store
+ #algorithm = "" # Algorithm used by SSLContext's TrustManagers store
+ }
+ }
+ ahc {
+ #keepAlive = true # Allow pooling HTTP connections (keep-alive header automatically added)
+ #connectTimeout = 60000 # Timeout when establishing a connection
+ #pooledConnectionIdleTimeout = 60000 # Timeout when a connection stays unused in the pool
+ #readTimeout = 60000 # Timeout when a used connection stays idle
+ #maxRetry = 2 # Number of times that a request should be tried again
+ #requestTimeout = 60000 # Timeout of the requests
+ #acceptAnyCertificate = true # When set to true, doesn't validate SSL certificates
+ #httpClientCodecMaxInitialLineLength = 4096 # Maximum length of the initial line of the response (e.g. "HTTP/1.0 200 OK")
+ #httpClientCodecMaxHeaderSize = 8192 # Maximum size, in bytes, of each request's headers
+ #httpClientCodecMaxChunkSize = 8192 # Maximum length of the content or each chunk
+ #webSocketMaxFrameSize = 10240000 # Maximum frame payload size
+ #sslEnabledProtocols = [TLSv1.2, TLSv1.1, TLSv1] # Array of enabled protocols for HTTPS, if empty use the JDK defaults
+ #sslEnabledCipherSuites = [] # Array of enabled cipher suites for HTTPS, if empty use the JDK defaults
+ #sslSessionCacheSize = 0 # SSLSession cache size, set to 0 to use JDK's default
+ #sslSessionTimeout = 0 # SSLSession timeout in seconds, set to 0 to use JDK's default (24h)
+ #useOpenSsl = false # if OpenSSL should be used instead of JSSE (requires tcnative jar)
+ #useNativeTransport = false # if native transport should be used instead of Java NIO (requires netty-transport-native-epoll, currently Linux only)
+ #usePooledMemory = true # if Gatling should use pooled memory
+ #tcpNoDelay = true
+ #soReuseAddress = false
+ #soLinger = -1
+ #soSndBuf = -1
+ #soRcvBuf = -1
+ }
+ dns {
+ #queryTimeout = 5000 # Timeout of each DNS query in millis
+ #maxQueriesPerResolve = 3 # Maximum allowed number of DNS queries for a given name resolution
+ }
+ }
+ data {
+ #writers = [console, file] # The list of DataWriters to which Gatling write simulation data (currently supported : console, file, graphite, jdbc)
+ console {
+ #light = false # When set to true, displays a light version without detailed request stats
+ }
+ file {
+ #bufferSize = 8192 # FileDataWriter's internal data buffer size, in bytes
+ }
+ leak {
+ #noActivityTimeout = 30 # Period, in seconds, for which Gatling may have no activity before considering a leak may be happening
+ }
+ graphite {
+ #light = false # only send the all* stats
+ #host = "localhost" # The host where the Carbon server is located
+ #port = 2003 # The port to which the Carbon server listens to (2003 is default for plaintext, 2004 is default for pickle)
+ #protocol = "tcp" # The protocol used to send data to Carbon (currently supported : "tcp", "udp")
+ #rootPathPrefix = "gatling" # The common prefix of all metrics sent to Graphite
+ #bufferSize = 8192 # GraphiteDataWriter's internal data buffer size, in bytes
+ #writeInterval = 1 # GraphiteDataWriter's write interval, in seconds
+ }
+ }
+}
diff --git a/gatling/src/test/resources/logback.xml b/gatling/src/test/resources/logback.xml
new file mode 100644
index 0000000000..b9ba6255a0
--- /dev/null
+++ b/gatling/src/test/resources/logback.xml
@@ -0,0 +1,22 @@
+
+
+
+
+
+ %d{HH:mm:ss.SSS} [%-5level] %logger{15} - %msg%n%rEx
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/gatling/src/test/resources/recorder.conf b/gatling/src/test/resources/recorder.conf
new file mode 100644
index 0000000000..969b9e8668
--- /dev/null
+++ b/gatling/src/test/resources/recorder.conf
@@ -0,0 +1,53 @@
+recorder {
+ core {
+ #mode = "Proxy"
+ #encoding = "utf-8" # The encoding used for reading/writing request bodies and the generated simulation
+ #outputFolder = "" # The folder where generated simulation will we written
+ #package = "" # The package's name of the generated simulation
+ #className = "RecordedSimulation" # The name of the generated Simulation class
+ #thresholdForPauseCreation = 100 # The minimum time, in milliseconds, that must pass between requests to trigger a pause creation
+ #saveConfig = false # When set to true, the configuration from the Recorder GUI overwrites this configuration
+ #headless = false # When set to true, run the Recorder in headless mode instead of the GUI
+ #harFilePath = "" # The path of the HAR file to convert
+ }
+ filters {
+ #filterStrategy = "Disabled" # The selected filter resources filter strategy (currently supported : "Disabled", "BlackList", "WhiteList")
+ #whitelist = [] # The list of ressources patterns that are part of the Recorder's whitelist
+ #blacklist = [] # The list of ressources patterns that are part of the Recorder's blacklist
+ }
+ http {
+ #automaticReferer = true # When set to false, write the referer + enable 'disableAutoReferer' in the generated simulation
+ #followRedirect = true # When set to false, write redirect requests + enable 'disableFollowRedirect' in the generated simulation
+ #removeCacheHeaders = true # When set to true, removes from the generated requests headers leading to request caching
+ #inferHtmlResources = true # When set to true, add inferred resources + set 'inferHtmlResources' with the configured blacklist/whitelist in the generated simulation
+ #checkResponseBodies = false # When set to true, save response bodies as files and add raw checks in the generated simulation
+ }
+ proxy {
+ #port = 8000 # Local port used by Gatling's Proxy for HTTP/HTTPS
+ https {
+ #mode = "SelfSignedCertificate" # The selected "HTTPS mode" (currently supported : "SelfSignedCertificate", "ProvidedKeyStore", "GatlingCertificateAuthority", "CustomCertificateAuthority")
+ keyStore {
+ #path = "" # The path of the custom key store
+ #password = "" # The password for this key store
+ #type = "JKS" # The type of the key store (currently supported: "JKS")
+ }
+ certificateAuthority {
+ #certificatePath = "" # The path of the custom certificate
+ #privateKeyPath = "" # The certificate's private key path
+ }
+ }
+ outgoing {
+ #host = "" # The outgoing proxy's hostname
+ #username = "" # The username to use to connect to the outgoing proxy
+ #password = "" # The password corresponding to the user to use to connect to the outgoing proxy
+ #port = 0 # The HTTP port to use to connect to the outgoing proxy
+ #sslPort = 0 # If set, The HTTPS port to use to connect to the outgoing proxy
+ }
+ }
+ netty {
+ #maxInitialLineLength = 10000 # Maximum length of the initial line of the response (e.g. "HTTP/1.0 200 OK")
+ #maxHeaderSize = 20000 # Maximum size, in bytes, of each request's headers
+ #maxChunkSize = 8192 # Maximum length of the content or each chunk
+ #maxContentLength = 100000000 # Maximum length of the aggregated content of each response
+ }
+}
diff --git a/gatling/src/test/scala/Engine.scala b/gatling/src/test/scala/Engine.scala
new file mode 100644
index 0000000000..32c85fbe45
--- /dev/null
+++ b/gatling/src/test/scala/Engine.scala
@@ -0,0 +1,13 @@
+import io.gatling.app.Gatling
+import io.gatling.core.config.GatlingPropertiesBuilder
+
+object Engine extends App {
+
+ val props = new GatlingPropertiesBuilder
+ props.dataDirectory(IDEPathHelper.dataDirectory.toString)
+ props.resultsDirectory(IDEPathHelper.resultsDirectory.toString)
+ props.bodiesDirectory(IDEPathHelper.bodiesDirectory.toString)
+ props.binariesDirectory(IDEPathHelper.mavenBinariesDirectory.toString)
+
+ Gatling.fromMap(props.build)
+}
diff --git a/gatling/src/test/scala/IDEPathHelper.scala b/gatling/src/test/scala/IDEPathHelper.scala
new file mode 100644
index 0000000000..0abf6a42ef
--- /dev/null
+++ b/gatling/src/test/scala/IDEPathHelper.scala
@@ -0,0 +1,22 @@
+import java.nio.file.Path
+
+import io.gatling.commons.util.PathHelper._
+
+object IDEPathHelper {
+
+ val gatlingConfUrl: Path = getClass.getClassLoader.getResource("gatling.conf").toURI
+ val projectRootDir = gatlingConfUrl.ancestor(3)
+
+ val mavenSourcesDirectory = projectRootDir / "src" / "test" / "scala"
+ val mavenResourcesDirectory = projectRootDir / "src" / "test" / "resources"
+ val mavenTargetDirectory = projectRootDir / "target"
+ val mavenBinariesDirectory = mavenTargetDirectory / "test-classes"
+
+ val dataDirectory = mavenResourcesDirectory / "data"
+ val bodiesDirectory = mavenResourcesDirectory / "bodies"
+
+ val recorderOutputDirectory = mavenSourcesDirectory
+ val resultsDirectory = mavenTargetDirectory / "gatling"
+
+ val recorderConfigFile = mavenResourcesDirectory / "recorder.conf"
+}
diff --git a/gatling/src/test/scala/Recorder.scala b/gatling/src/test/scala/Recorder.scala
new file mode 100644
index 0000000000..6ad320618b
--- /dev/null
+++ b/gatling/src/test/scala/Recorder.scala
@@ -0,0 +1,12 @@
+import io.gatling.recorder.GatlingRecorder
+import io.gatling.recorder.config.RecorderPropertiesBuilder
+
+object Recorder extends App {
+
+ val props = new RecorderPropertiesBuilder
+ props.simulationOutputFolder(IDEPathHelper.recorderOutputDirectory.toString)
+ props.simulationPackage("org.baeldung")
+ props.bodiesFolder(IDEPathHelper.bodiesDirectory.toString)
+
+ GatlingRecorder.fromMap(props.build, Some(IDEPathHelper.recorderConfigFile))
+}
diff --git a/gatling/src/test/scala/org/baeldung/RecordedSimulation.scala b/gatling/src/test/scala/org/baeldung/RecordedSimulation.scala
new file mode 100644
index 0000000000..cdbef1bf3c
--- /dev/null
+++ b/gatling/src/test/scala/org/baeldung/RecordedSimulation.scala
@@ -0,0 +1,46 @@
+package org.baeldung
+
+import scala.concurrent.duration._
+
+import io.gatling.core.Predef._
+import io.gatling.http.Predef._
+import io.gatling.jdbc.Predef._
+
+class RecordedSimulation extends Simulation {
+
+ val httpProtocol = http
+ .baseURL("http://computer-database.gatling.io")
+ .inferHtmlResources(BlackList(""".*\.css""", """.*\.js""", """.*\.ico"""), WhiteList())
+ .acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
+ .acceptEncodingHeader("gzip, deflate")
+ .acceptLanguageHeader("it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3")
+ .userAgentHeader("Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0")
+
+
+
+
+
+ val scn = scenario("RecordedSimulation")
+ .exec(http("request_0")
+ .get("/"))
+ .pause(5)
+ .exec(http("request_1")
+ .get("/computers?f=amstrad"))
+ .pause(4)
+ .exec(http("request_2")
+ .get("/computers/412"))
+ .pause(2)
+ .exec(http("request_3")
+ .get("/"))
+ .pause(2)
+ .exec(http("request_4")
+ .get("/computers?p=1"))
+ .pause(1)
+ .exec(http("request_5")
+ .get("/computers?p=2"))
+ .pause(2)
+ .exec(http("request_6")
+ .get("/computers?p=3"))
+
+ setUp(scn.inject(atOnceUsers(1))).protocols(httpProtocol)
+}
diff --git a/gson-jackson-performance/.classpath b/gson-jackson-performance/.classpath
new file mode 100644
index 0000000000..19b2ff18be
--- /dev/null
+++ b/gson-jackson-performance/.classpath
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/gson-jackson-performance/.project b/gson-jackson-performance/.project
new file mode 100644
index 0000000000..b3b5ccad87
--- /dev/null
+++ b/gson-jackson-performance/.project
@@ -0,0 +1,14 @@
+
+
+ gson-jackson-performance
+ NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse.
+
+
+
+ org.eclipse.jdt.core.javabuilder
+
+
+
+ org.eclipse.jdt.core.javanature
+
+
\ No newline at end of file
diff --git a/gson-jackson-performance/README.md b/gson-jackson-performance/README.md
new file mode 100644
index 0000000000..5b08f6cdec
--- /dev/null
+++ b/gson-jackson-performance/README.md
@@ -0,0 +1,3 @@
+## Performance of Gson and Jackson
+
+Standalone java programs to measure the performance of both JSON APIs based on file size and object graph complexity.
diff --git a/gson-jackson-performance/pom.xml b/gson-jackson-performance/pom.xml
new file mode 100644
index 0000000000..1ea43bd7fa
--- /dev/null
+++ b/gson-jackson-performance/pom.xml
@@ -0,0 +1,72 @@
+
+ 4.0.0
+
+ com.baeldung
+ gson-jackson-performance
+ 0.0.1-SNAPSHOT
+ jar
+
+ gson-jackson-performance
+ http://maven.apache.org
+
+
+ UTF-8
+
+
+
+ gson-jackson-performance
+
+
+ src/main/resources
+ true
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ 1.8
+ 1.8
+
+
+
+
+
+
+
+
+
+
+ com.google.code.gson
+ gson
+ 2.5
+
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ 2.7.1-1
+
+
+
+ junit
+ junit
+ 3.8.1
+ test
+
+
+
+ log4j
+ log4j
+ 1.2.17
+
+
+
+
+
+
+
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java
new file mode 100644
index 0000000000..b69d306edf
--- /dev/null
+++ b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGeneration.java
@@ -0,0 +1,63 @@
+package com.baeldung.data.complex;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.baeldung.data.utility.Utility;
+import com.baeldung.pojo.complex.AddressDetails;
+import com.baeldung.pojo.complex.ContactDetails;
+import com.baeldung.pojo.complex.CustomerAddressDetails;
+import com.baeldung.pojo.complex.CustomerPortfolioComplex;
+
+/**
+ *
+ * This class is responsible for generating data for complex type object
+ */
+
+public class ComplexDataGeneration {
+
+ public static CustomerPortfolioComplex generateData() {
+ List customerAddressDetailsList = new ArrayList();
+ for (int i = 0; i < 600000; i++) {
+ CustomerAddressDetails customerAddressDetails = new CustomerAddressDetails();
+ customerAddressDetails.setAge(20);
+ customerAddressDetails.setFirstName(Utility.generateRandomName());
+ customerAddressDetails.setLastName(Utility.generateRandomName());
+
+ List addressDetailsList = new ArrayList();
+ customerAddressDetails.setAddressDetails(addressDetailsList);
+
+ for (int j = 0; j < 2; j++) {
+ AddressDetails addressDetails = new AddressDetails();
+ addressDetails.setZipcode(Utility.generateRandomZip());
+ addressDetails.setAddress(Utility.generateRandomAddress());
+
+ List contactDetailsList = new ArrayList();
+ addressDetails.setContactDetails(contactDetailsList);
+
+ for (int k = 0; k < 2; k++) {
+ ContactDetails contactDetails = new ContactDetails();
+ contactDetails.setLandline(Utility.generateRandomPhone());
+ contactDetails.setMobile(Utility.generateRandomPhone());
+ contactDetailsList.add(contactDetails);
+ contactDetails = null;
+ }
+
+ addressDetailsList.add(addressDetails);
+ addressDetails = null;
+ contactDetailsList = null;
+ }
+ customerAddressDetailsList.add(customerAddressDetails);
+ customerAddressDetails = null;
+
+ if (i % 6000 == 0) {
+ Runtime.getRuntime().gc();
+ }
+ }
+
+ CustomerPortfolioComplex customerPortfolioComplex = new CustomerPortfolioComplex();
+ customerPortfolioComplex.setCustomerAddressDetailsList(customerAddressDetailsList);
+ customerAddressDetailsList = null;
+ return customerPortfolioComplex;
+ }
+}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java
new file mode 100644
index 0000000000..b97893e8f1
--- /dev/null
+++ b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataGson.java
@@ -0,0 +1,91 @@
+package com.baeldung.data.complex;
+
+import java.util.Map;
+
+import org.apache.log4j.Logger;
+import com.baeldung.data.utility.Utility;
+import com.baeldung.pojo.complex.CustomerPortfolioComplex;
+
+import com.google.gson.Gson;
+
+/**
+ *
+ * This class is responsible for performing functions for Complex type
+ * GSON like
+ * Java to Json
+ * Json to Map
+ * Json to Java Object
+ */
+
+public class ComplexDataGson {
+
+ private static final Logger logger = Logger.getLogger(ComplexDataGson.class);
+
+ static Gson gson = new Gson();
+
+ static long generateJsonAvgTime = 0L;
+
+ static long parseJsonToMapAvgTime = 0L;
+
+ static long parseJsonToActualObjectAvgTime = 0L;
+
+ public static void main(String[] args) {
+ CustomerPortfolioComplex customerPortfolioComplex = ComplexDataGeneration.generateData();
+ int j = 50;
+ for (int i = 0; i < j; i++) {
+ logger.info("-------Round " + (i + 1));
+ String jsonStr = generateJson(customerPortfolioComplex);
+ logger.info("Size of Complex content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length));
+ logger.info("--------------------------------------------------------------------------");
+ parseJsonToMap(jsonStr);
+ parseJsonToActualObject(jsonStr);
+ jsonStr = null;
+ }
+
+ generateJsonAvgTime = generateJsonAvgTime / j;
+ parseJsonToMapAvgTime = parseJsonToMapAvgTime / j;
+ parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j;
+
+ logger.info("--------------------------------------------------------------------------");
+ logger.info("Average Time to Generate JSON : " + generateJsonAvgTime);
+ logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime);
+ logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime);
+ logger.info("--------------------------------------------------------------------------");
+ }
+
+ private static String generateJson(CustomerPortfolioComplex customerPortfolioComplex) {
+ Runtime.getRuntime().gc();
+ long startParsTime = System.nanoTime();
+ String json = gson.toJson(customerPortfolioComplex);
+ long endParsTime = System.nanoTime();
+ long elapsedTime = endParsTime - startParsTime;
+ generateJsonAvgTime = generateJsonAvgTime + elapsedTime;
+ logger.info("Json Generation Time(ms):: " + elapsedTime);
+ return json;
+ }
+
+ private static void parseJsonToMap(String jsonStr) {
+ long startParsTime = System.nanoTime();
+ Map parsedMap = gson.fromJson(jsonStr , Map.class);
+ long endParsTime = System.nanoTime();
+ long elapsedTime = endParsTime - startParsTime;
+ parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime;
+ logger.info("Generating Map from json Time(ms):: " + elapsedTime);
+ logger.info("--------------------------------------------------------------------------");
+ parsedMap = null;
+ Runtime.getRuntime().gc();
+ }
+
+ private static void parseJsonToActualObject(String jsonStr) {
+ long startParsTime = System.nanoTime();
+ CustomerPortfolioComplex customerPortfolioComplex = gson.fromJson(jsonStr , CustomerPortfolioComplex.class);
+ long endParsTime = System.nanoTime();
+ long elapsedTime = endParsTime - startParsTime;
+ parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime;
+ logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime);
+ logger.info("--------------------------------------------------------------------------");
+ customerPortfolioComplex = null;
+ Runtime.getRuntime().gc();
+
+ }
+}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java
new file mode 100644
index 0000000000..07a210fb37
--- /dev/null
+++ b/gson-jackson-performance/src/main/java/com/baeldung/data/complex/ComplexDataJackson.java
@@ -0,0 +1,95 @@
+package com.baeldung.data.complex;
+
+import java.io.IOException;
+import java.util.Map;
+
+import com.baeldung.data.utility.Utility;
+import org.apache.log4j.Logger;
+import com.baeldung.pojo.complex.CustomerPortfolioComplex;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ *
+ * This class is responsible for performing functions for Complex type
+ * Jackson like
+ * Java to Json
+ * Json to Map
+ * Json to Java Object
+ */
+
+public class ComplexDataJackson {
+
+ private static final Logger logger = Logger.getLogger(ComplexDataJackson.class);
+
+ static ObjectMapper mapper = new ObjectMapper();
+
+ static long generateJsonAvgTime = 0L;
+
+ static long parseJsonToMapAvgTime = 0L;
+
+ static long parseJsonToActualObjectAvgTime = 0L;
+
+ public static void main(String[] args) throws IOException {
+ CustomerPortfolioComplex customerPortfolioComplex = ComplexDataGeneration.generateData();
+ int j = 50;
+ for (int i = 0; i < j; i++) {
+ logger.info("-------Round " + (i + 1));
+ String jsonStr = generateJson(customerPortfolioComplex);
+ logger.info("Size of Complex content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length));
+ logger.info("--------------------------------------------------------------------------");
+ parseJsonToMap(jsonStr);
+ parseJsonToActualObject(jsonStr);
+ jsonStr = null;
+ }
+
+ generateJsonAvgTime = generateJsonAvgTime / j;
+ parseJsonToMapAvgTime = parseJsonToMapAvgTime / j;
+ parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j;
+
+ logger.info("--------------------------------------------------------------------------");
+ logger.info("Average Time to Generate JSON : " + generateJsonAvgTime);
+ logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime);
+ logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime);
+ logger.info("--------------------------------------------------------------------------");
+ }
+
+ private static String generateJson(CustomerPortfolioComplex customerPortfolioComplex)
+ throws JsonProcessingException {
+ Runtime.getRuntime().gc();
+ long startParsTime = System.nanoTime();
+ String json = mapper.writeValueAsString(customerPortfolioComplex);
+ long endParsTime = System.nanoTime();
+ long elapsedTime = endParsTime - startParsTime;
+ generateJsonAvgTime = generateJsonAvgTime + elapsedTime;
+ logger.info("Json Generation Time(ms):: " + elapsedTime);
+ return json;
+ }
+
+ private static void parseJsonToMap(String jsonStr) throws JsonParseException , JsonMappingException , IOException {
+ long startParsTime = System.nanoTime();
+ Map parsedMap = mapper.readValue(jsonStr , Map.class);
+ long endParsTime = System.nanoTime();
+ long elapsedTime = endParsTime - startParsTime;
+ parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime;
+ logger.info("Generating Map from json Time(ms):: " + elapsedTime);
+ parsedMap = null;
+ Runtime.getRuntime().gc();
+
+ }
+
+ private static void parseJsonToActualObject(String jsonStr) throws JsonParseException , JsonMappingException ,
+ IOException {
+ long startParsTime = System.nanoTime();
+ CustomerPortfolioComplex customerPortfolioComplex = mapper.readValue(jsonStr , CustomerPortfolioComplex.class);
+ long endParsTime = System.nanoTime();
+ long elapsedTime = endParsTime - startParsTime;
+ parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime;
+ logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime);
+ customerPortfolioComplex = null;
+ Runtime.getRuntime().gc();
+ }
+}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java
new file mode 100644
index 0000000000..1e186adc72
--- /dev/null
+++ b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGeneration.java
@@ -0,0 +1,35 @@
+package com.baeldung.data.simple;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.baeldung.data.utility.Utility;
+import com.baeldung.pojo.simple.Customer;
+import com.baeldung.pojo.simple.CustomerPortfolioSimple;
+
+/**
+ *
+ * This class is responsible for generating data for simple type object
+ */
+
+public class SimpleDataGeneration {
+
+ public static CustomerPortfolioSimple generateData() {
+ List customerList = new ArrayList();
+ for (int i = 0; i < 1; i++) {
+ Customer customer = new Customer();
+ customer.setAge(20);
+ customer.setFirstName(Utility.generateRandomName());
+ customer.setLastName(Utility.generateRandomName());
+
+ customerList.add(customer);
+ customer = null;
+
+ }
+
+ CustomerPortfolioSimple customerPortfolioSimple = new CustomerPortfolioSimple();
+ customerPortfolioSimple.setCustomerLists(customerList);
+ customerList = null;
+ return customerPortfolioSimple;
+ }
+}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java
new file mode 100644
index 0000000000..b190313462
--- /dev/null
+++ b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataGson.java
@@ -0,0 +1,91 @@
+package com.baeldung.data.simple;
+
+import java.util.Map;
+
+import org.apache.log4j.Logger;
+import com.baeldung.data.utility.Utility;
+import com.baeldung.pojo.simple.CustomerPortfolioSimple;
+
+import com.google.gson.Gson;
+
+/**
+ *
+ * This class is responsible for performing functions for Simple type
+ * GSON like
+ * Java to Json
+ * Json to Map
+ * Json to Java Object
+ */
+
+public class SimpleDataGson {
+
+ private static final Logger logger = Logger.getLogger(SimpleDataGson.class);
+
+ static Gson gson = new Gson();
+
+ static long generateJsonAvgTime = 0L;
+
+ static long parseJsonToMapAvgTime = 0L;
+
+ static long parseJsonToActualObjectAvgTime = 0L;
+
+ public static void main(String[] args) {
+ CustomerPortfolioSimple customerPortfolioSimple = SimpleDataGeneration.generateData();
+ String jsonStr = null;
+ int j = 5;
+ for (int i = 0; i < j; i++) {
+ logger.info("-------Round " + (i + 1));
+ jsonStr = generateJson(customerPortfolioSimple);
+ logger.info("Size of Simple content Gson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length));
+ logger.info("--------------------------------------------------------------------------");
+ parseJsonToMap(jsonStr);
+ parseJsonToActualObject(jsonStr);
+ jsonStr = null;
+ }
+ generateJsonAvgTime = generateJsonAvgTime / j;
+ parseJsonToMapAvgTime = parseJsonToMapAvgTime / j;
+ parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j;
+
+ logger.info("--------------------------------------------------------------------------");
+ logger.info("Average Time to Generate JSON : " + generateJsonAvgTime);
+ logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime);
+ logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime);
+ logger.info("--------------------------------------------------------------------------");
+ }
+
+ private static String generateJson(CustomerPortfolioSimple customerPortfolioSimple) {
+ Runtime.getRuntime().gc();
+ long startParsTime = System.nanoTime();
+ String json = gson.toJson(customerPortfolioSimple);
+ long endParsTime = System.nanoTime();
+ long elapsedTime = endParsTime - startParsTime;
+ generateJsonAvgTime = generateJsonAvgTime + elapsedTime;
+ logger.info("Json Generation Time(ms):: " + elapsedTime);
+ return json;
+ }
+
+ private static void parseJsonToMap(String jsonStr) {
+ long startParsTime = System.nanoTime();
+ Map parsedMap = gson.fromJson(jsonStr , Map.class);
+ long endParsTime = System.nanoTime();
+ long elapsedTime = endParsTime - startParsTime;
+ parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime;
+ logger.info("Generating Map from json Time(ms):: " + elapsedTime);
+ logger.info("--------------------------------------------------------------------------");
+ parsedMap = null;
+ Runtime.getRuntime().gc();
+
+ }
+
+ private static void parseJsonToActualObject(String jsonStr) {
+ long startParsTime = System.nanoTime();
+ CustomerPortfolioSimple customerPortfolioSimple = gson.fromJson(jsonStr , CustomerPortfolioSimple.class);
+ long endParsTime = System.nanoTime();
+ long elapsedTime = endParsTime - startParsTime;
+ parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime;
+ logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime);
+ logger.info("--------------------------------------------------------------------------");
+ customerPortfolioSimple = null;
+ Runtime.getRuntime().gc();
+ }
+}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java
new file mode 100644
index 0000000000..9330333604
--- /dev/null
+++ b/gson-jackson-performance/src/main/java/com/baeldung/data/simple/SimpleDataJackson.java
@@ -0,0 +1,95 @@
+package com.baeldung.data.simple;
+
+import java.io.IOException;
+import java.util.Map;
+
+import com.baeldung.data.utility.Utility;
+import org.apache.log4j.Logger;
+import com.baeldung.pojo.simple.CustomerPortfolioSimple;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+/**
+ *
+ * This class is responsible for performing functions for Simple type
+ * Jackson like
+ * Java to Json
+ * Json to Map
+ * Json to Java Object
+ */
+
+public class SimpleDataJackson {
+
+ private static final Logger logger = Logger.getLogger(SimpleDataJackson.class);
+
+ static ObjectMapper mapper = new ObjectMapper();
+
+ static long generateJsonAvgTime = 0L;
+
+ static long parseJsonToMapAvgTime = 0L;
+
+ static long parseJsonToActualObjectAvgTime = 0L;
+
+ public static void main(String[] args) throws IOException {
+ CustomerPortfolioSimple customerPortfolioSimple = SimpleDataGeneration.generateData();
+ int j = 50;
+ for (int i = 0; i < j; i++) {
+ logger.info("-------Round " + (i + 1));
+ String jsonStr = generateJson(customerPortfolioSimple);
+ logger.info("Size of Simple content Jackson :: " + Utility.bytesIntoMB(jsonStr.getBytes().length));
+ logger.info("--------------------------------------------------------------------------");
+
+ parseJsonToMap(jsonStr);
+ parseJsonToActualObject(jsonStr);
+ jsonStr = null;
+ }
+
+ generateJsonAvgTime = generateJsonAvgTime / j;
+ parseJsonToMapAvgTime = parseJsonToMapAvgTime / j;
+ parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime / j;
+
+ logger.info("--------------------------------------------------------------------------");
+ logger.info("Average Time to Generate JSON : " + generateJsonAvgTime);
+ logger.info("Average Time to Parse JSON To Map : " + parseJsonToMapAvgTime);
+ logger.info("Average Time to Parse JSON To Actual Object : " + parseJsonToActualObjectAvgTime);
+ logger.info("--------------------------------------------------------------------------");
+ }
+
+ private static String generateJson(CustomerPortfolioSimple customerPortfolioSimple) throws JsonProcessingException {
+ Runtime.getRuntime().gc();
+ long startParsTime = System.nanoTime();
+ String json = mapper.writeValueAsString(customerPortfolioSimple);
+ long endParsTime = System.nanoTime();
+ long elapsedTime = endParsTime - startParsTime;
+ generateJsonAvgTime = generateJsonAvgTime + elapsedTime;
+ logger.info("Json Generation Time(ms):: " + elapsedTime);
+ return json;
+ }
+
+ private static void parseJsonToMap(String jsonStr) throws JsonParseException , JsonMappingException , IOException {
+ long startParsTime = System.nanoTime();
+ Map parsedMap = mapper.readValue(jsonStr , Map.class);
+ long endParsTime = System.nanoTime();
+ long elapsedTime = endParsTime - startParsTime;
+ parseJsonToMapAvgTime = parseJsonToMapAvgTime + elapsedTime;
+ logger.info("Generating Map from json Time(ms):: " + elapsedTime);
+ logger.info("--------------------------------------------------------------------------");
+ parsedMap = null;
+ Runtime.getRuntime().gc();
+ }
+
+ private static void parseJsonToActualObject(String jsonStr) throws JsonParseException , JsonMappingException ,
+ IOException {
+ long startParsTime = System.nanoTime();
+ CustomerPortfolioSimple customerPortfolioSimple = mapper.readValue(jsonStr , CustomerPortfolioSimple.class);
+ long endParsTime = System.nanoTime();
+ long elapsedTime = endParsTime - startParsTime;
+ parseJsonToActualObjectAvgTime = parseJsonToActualObjectAvgTime + elapsedTime;
+ logger.info("Generating Actual Object from json Time(ms):: " + elapsedTime);
+ customerPortfolioSimple = null;
+ Runtime.getRuntime().gc();
+ }
+}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java b/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java
new file mode 100644
index 0000000000..8b0c402e47
--- /dev/null
+++ b/gson-jackson-performance/src/main/java/com/baeldung/data/utility/Utility.java
@@ -0,0 +1,90 @@
+package com.baeldung.data.utility;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Random;
+
+public class Utility {
+
+ public static String generateRandomName() {
+ char[] chars = "abcdefghijklmnopqrstuvwxyz ".toCharArray();
+ StringBuilder sb = new StringBuilder();
+ Random random = new Random();
+ for (int i = 0; i < 8; i++) {
+ char c = chars[random.nextInt(chars.length)];
+ sb.append(c);
+ }
+ return sb.toString();
+ }
+
+ public static String generateRandomAddress() {
+ char[] chars = "abcdefghijklmnopqrstuvwxyz ".toCharArray();
+ StringBuilder sb = new StringBuilder();
+ Random random = new Random();
+ for (int i = 0; i < 30; i++) {
+ char c = chars[random.nextInt(chars.length)];
+ sb.append(c);
+ }
+ return sb.toString();
+ }
+
+ public static String generateRandomZip() {
+ char[] chars = "1234567890".toCharArray();
+ StringBuilder sb = new StringBuilder();
+ Random random = new Random();
+ for (int i = 0; i < 8; i++) {
+ char c = chars[random.nextInt(chars.length)];
+ sb.append(c);
+ }
+ return sb.toString();
+ }
+
+ public static String generateRandomPhone() {
+ char[] chars = "1234567890".toCharArray();
+ StringBuilder sb = new StringBuilder();
+ Random random = new Random();
+ for (int i = 0; i < 10; i++) {
+ char c = chars[random.nextInt(chars.length)];
+ sb.append(c);
+ }
+ return sb.toString();
+ }
+
+ public static String readFile(String fileName , Class clazz) throws IOException {
+ String dir = clazz.getResource("/").getFile();
+ dir = dir + "/" + fileName;
+
+ BufferedReader br = new BufferedReader(new FileReader(dir));
+ try {
+ StringBuilder sb = new StringBuilder();
+ String line = br.readLine();
+
+ while (line != null) {
+ sb.append(line);
+ sb.append(System.lineSeparator());
+ line = br.readLine();
+ }
+ return sb.toString();
+ } finally {
+ br.close();
+ }
+ }
+
+ public static String bytesIntoMB(long bytes) {
+ long kilobyte = 1024;
+ long megabyte = kilobyte * 1024;
+
+ if ((bytes >= 0) && (bytes < kilobyte)) {
+ return bytes + " B";
+
+ } else if ((bytes >= kilobyte) && (bytes < megabyte)) {
+ return (bytes / kilobyte) + " KB";
+
+ } else if ((bytes >= megabyte)) {
+ return (bytes / megabyte) + " MB";
+ }
+
+ return null;
+ }
+}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java
new file mode 100644
index 0000000000..79725a97bd
--- /dev/null
+++ b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/AddressDetails.java
@@ -0,0 +1,37 @@
+package com.baeldung.pojo.complex;
+
+import java.util.List;
+
+public class AddressDetails {
+
+ private String address;
+
+ private String zipcode;
+
+ private List contactDetails;
+
+ public String getZipcode() {
+ return zipcode;
+ }
+
+ public void setZipcode(String zipcode) {
+ this.zipcode = zipcode;
+ }
+
+ public List getContactDetails() {
+ return contactDetails;
+ }
+
+ public void setContactDetails(List contactDetails) {
+ this.contactDetails = contactDetails;
+ }
+
+ public String getAddress() {
+ return address;
+ }
+
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java
new file mode 100644
index 0000000000..164fe3f470
--- /dev/null
+++ b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/ContactDetails.java
@@ -0,0 +1,25 @@
+package com.baeldung.pojo.complex;
+
+public class ContactDetails {
+
+ private String mobile;
+
+ private String landline;
+
+ public String getMobile() {
+ return mobile;
+ }
+
+ public void setMobile(String mobile) {
+ this.mobile = mobile;
+ }
+
+ public String getLandline() {
+ return landline;
+ }
+
+ public void setLandline(String landline) {
+ this.landline = landline;
+ }
+
+}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java
new file mode 100644
index 0000000000..9bc5951716
--- /dev/null
+++ b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerAddressDetails.java
@@ -0,0 +1,18 @@
+package com.baeldung.pojo.complex;
+
+import java.util.List;
+
+import com.baeldung.pojo.simple.Customer;
+
+public class CustomerAddressDetails extends Customer {
+
+ private List addressDetails;
+
+ public List getAddressDetails() {
+ return addressDetails;
+ }
+
+ public void setAddressDetails(List addressDetails) {
+ this.addressDetails = addressDetails;
+ }
+}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java
new file mode 100644
index 0000000000..13f9d240b8
--- /dev/null
+++ b/gson-jackson-performance/src/main/java/com/baeldung/pojo/complex/CustomerPortfolioComplex.java
@@ -0,0 +1,17 @@
+package com.baeldung.pojo.complex;
+
+import java.util.List;
+
+public class CustomerPortfolioComplex {
+
+ private List customerAddressDetailsList;
+
+ public List getCustomerAddressDetailsList() {
+ return customerAddressDetailsList;
+ }
+
+ public void setCustomerAddressDetailsList(List customerAddressDetailsList) {
+ this.customerAddressDetailsList = customerAddressDetailsList;
+ }
+
+}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java
new file mode 100644
index 0000000000..3d5668f85a
--- /dev/null
+++ b/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/Customer.java
@@ -0,0 +1,36 @@
+package com.baeldung.pojo.simple;
+
+
+public class Customer {
+
+ private String firstName;
+
+ private String lastName;
+
+ private int age;
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public int getAge() {
+ return age;
+ }
+
+ public void setAge(int age) {
+ this.age = age;
+ }
+
+}
diff --git a/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java b/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java
new file mode 100644
index 0000000000..7cb684813c
--- /dev/null
+++ b/gson-jackson-performance/src/main/java/com/baeldung/pojo/simple/CustomerPortfolioSimple.java
@@ -0,0 +1,16 @@
+package com.baeldung.pojo.simple;
+
+import java.util.List;
+
+public class CustomerPortfolioSimple {
+
+ private List customerLists;
+
+ public List getCustomerLists() {
+ return customerLists;
+ }
+
+ public void setCustomerLists(List customerLists) {
+ this.customerLists = customerLists;
+ }
+}
diff --git a/gson-jackson-performance/src/main/resources/log4j.properties b/gson-jackson-performance/src/main/resources/log4j.properties
new file mode 100644
index 0000000000..371cbc9048
--- /dev/null
+++ b/gson-jackson-performance/src/main/resources/log4j.properties
@@ -0,0 +1,16 @@
+# Root logger option
+log4j.rootLogger=DEBUG, file
+
+# Redirect log messages to console
+# log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+# log4j.appender.stdout.Target=System.out
+# log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
+
+# Redirect log messages to a log file, support file rolling.
+log4j.appender.file=org.apache.log4j.RollingFileAppender
+log4j.appender.file.File=log4j-application.log
+log4j.appender.file.MaxFileSize=5MB
+log4j.appender.file.MaxBackupIndex=10
+log4j.appender.file.layout=org.apache.log4j.PatternLayout
+log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
\ No newline at end of file
diff --git a/gson/README.md b/gson/README.md
index 559e536d81..67651b732e 100644
--- a/gson/README.md
+++ b/gson/README.md
@@ -2,5 +2,6 @@
## GSON Cookbooks and Examples
-### Relevant Articles:
+### Relevant Articles:
+- [Gson Deserialization Cookbook](http://www.baeldung.com/gson-deserialization-guide)
diff --git a/gson/pom.xml b/gson/pom.xml
index 500d14c40c..4f331f6fd9 100644
--- a/gson/pom.xml
+++ b/gson/pom.xml
@@ -1,6 +1,6 @@
4.0.0
- org.baeldung
+ com.baeldung
gson
0.1-SNAPSHOT
@@ -53,7 +53,7 @@
junit
- junit-dep
+ junit
${junit.version}
test
@@ -112,44 +112,40 @@
-
- 4.1.5.RELEASE
- 3.2.5.RELEASE
-
- 4.3.10.Final
- 5.1.35
+ 4.3.11.Final
+ 5.1.38
2.3
- 1.7.12
+ 1.7.13
1.1.3
5.1.3.Final
- 18.0
+ 19.0
3.4
1.3
- 4.11
+ 4.12
1.10.19
4.4.1
4.5
- 2.4.1
+ 2.9.0
- 3.3
+ 3.5.1
2.6
- 2.18.1
+ 2.19.1
2.7
- 1.4.14
+ 1.4.18
diff --git a/gson/src/main/webapp/WEB-INF/api-servlet.xml b/gson/src/main/webapp/WEB-INF/api-servlet.xml
deleted file mode 100644
index 4c74be8912..0000000000
--- a/gson/src/main/webapp/WEB-INF/api-servlet.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/gson/src/main/webapp/WEB-INF/web.xml b/gson/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 935beae648..0000000000
--- a/gson/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-
-
-
- Spring MVC Application
-
-
-
- contextClass
-
- org.springframework.web.context.support.AnnotationConfigWebApplicationContext
-
-
-
- contextConfigLocation
- org.baeldung.config
-
-
-
- org.springframework.web.context.ContextLoaderListener
-
-
-
-
- api
- org.springframework.web.servlet.DispatcherServlet
- 1
-
-
- api
- /
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/Foo.java b/gson/src/test/java/org/baeldung/gson/deserialization/Foo.java
index 64720f63f9..84f8aaef13 100644
--- a/gson/src/test/java/org/baeldung/gson/deserialization/Foo.java
+++ b/gson/src/test/java/org/baeldung/gson/deserialization/Foo.java
@@ -9,6 +9,10 @@ public class Foo {
this.stringValue = stringValue;
}
+ public Foo(final String stringValue) {
+ this.stringValue = stringValue;
+ }
+
public Foo() {
super();
}
@@ -19,27 +23,33 @@ public class Foo {
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result + intValue;
- result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode());
+ result = (prime * result) + intValue;
+ result = (prime * result) + ((stringValue == null) ? 0 : stringValue.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
- if (this == obj)
+ if (this == obj) {
return true;
- if (obj == null)
+ }
+ if (obj == null) {
return false;
- if (getClass() != obj.getClass())
+ }
+ if (getClass() != obj.getClass()) {
return false;
+ }
final Foo other = (Foo) obj;
- if (intValue != other.intValue)
+ if (intValue != other.intValue) {
return false;
+ }
if (stringValue == null) {
- if (other.stringValue != null)
+ if (other.stringValue != null) {
return false;
- } else if (!stringValue.equals(other.stringValue))
+ }
+ } else if (!stringValue.equals(other.stringValue)) {
return false;
+ }
return true;
}
diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/FooInstanceCreator.java b/gson/src/test/java/org/baeldung/gson/deserialization/FooInstanceCreator.java
new file mode 100644
index 0000000000..4df3986ec3
--- /dev/null
+++ b/gson/src/test/java/org/baeldung/gson/deserialization/FooInstanceCreator.java
@@ -0,0 +1,14 @@
+package org.baeldung.gson.deserialization;
+
+import java.lang.reflect.Type;
+
+import com.google.gson.InstanceCreator;
+
+public class FooInstanceCreator implements InstanceCreator {
+
+ @Override
+ public Foo createInstance(Type type) {
+ return new Foo("sample");
+ }
+
+}
diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/FooWithInner.java b/gson/src/test/java/org/baeldung/gson/deserialization/FooWithInner.java
new file mode 100644
index 0000000000..705e534e77
--- /dev/null
+++ b/gson/src/test/java/org/baeldung/gson/deserialization/FooWithInner.java
@@ -0,0 +1,24 @@
+package org.baeldung.gson.deserialization;
+
+public class FooWithInner {
+ public int intValue;
+ public String stringValue;
+ public InnerFoo innerFoo;
+
+ public FooWithInner(int intValue, String stringValue, String name) {
+ super();
+ this.intValue = intValue;
+ this.stringValue = stringValue;
+ this.innerFoo = new InnerFoo(name);
+ }
+
+ public class InnerFoo {
+ public String name;
+
+ public InnerFoo(String name) {
+ super();
+ this.name = name;
+ }
+
+ }
+}
diff --git a/gson/src/test/java/org/baeldung/gson/deserialization/test/GsonDeserializationTest.java b/gson/src/test/java/org/baeldung/gson/deserialization/test/GsonDeserializationTest.java
index 342b3096d7..072a25e749 100644
--- a/gson/src/test/java/org/baeldung/gson/deserialization/test/GsonDeserializationTest.java
+++ b/gson/src/test/java/org/baeldung/gson/deserialization/test/GsonDeserializationTest.java
@@ -12,6 +12,8 @@ import java.util.Collection;
import org.baeldung.gson.deserialization.Foo;
import org.baeldung.gson.deserialization.FooDeserializerFromJsonWithDifferentFields;
+import org.baeldung.gson.deserialization.FooInstanceCreator;
+import org.baeldung.gson.deserialization.FooWithInner;
import org.baeldung.gson.deserialization.GenericFoo;
import org.junit.Test;
@@ -108,4 +110,29 @@ public class GsonDeserializationTest {
assertEquals(targetObject.stringValue, "seven");
}
+ // new examples
+
+ @Test
+ public void whenDeserializingToNestedObjects_thenCorrect() {
+ final String json = "{\"intValue\":1,\"stringValue\":\"one\",\"innerFoo\":{\"name\":\"inner\"}}";
+
+ final FooWithInner targetObject = new Gson().fromJson(json, FooWithInner.class);
+
+ assertEquals(targetObject.intValue, 1);
+ assertEquals(targetObject.stringValue, "one");
+ assertEquals(targetObject.innerFoo.name, "inner");
+ }
+
+ @Test
+ public void whenDeserializingUsingInstanceCreator_thenCorrect() {
+ final String json = "{\"intValue\":1}";
+
+ final GsonBuilder gsonBldr = new GsonBuilder();
+ gsonBldr.registerTypeAdapter(Foo.class, new FooInstanceCreator());
+ final Foo targetObject = gsonBldr.create().fromJson(json, Foo.class);
+
+ assertEquals(targetObject.intValue, 1);
+ assertEquals(targetObject.stringValue, "sample");
+ }
+
}
diff --git a/guava/README.md b/guava/README.md
index 8960b4676e..28bcfeb912 100644
--- a/guava/README.md
+++ b/guava/README.md
@@ -7,7 +7,11 @@
- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections)
- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order)
- [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates)
-
- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays)
-
- [Partition a List in Java](http://www.baeldung.com/java-list-split)
+- [Filtering and Transforming Collections in Guava](http://www.baeldung.com/guava-filter-and-transform-a-collection)
+- [Guava – Join and Split Collections](http://www.baeldung.com/guava-joiner-and-splitter-tutorial)
+- [Guava – Write to File, Read from File](http://www.baeldung.com/guava-write-to-file-read-from-file)
+- [Guava – Lists](http://www.baeldung.com/guava-lists)
+- [Guava – Sets](http://www.baeldung.com/guava-sets)
+- [Guava – Maps](http://www.baeldung.com/guava-maps)
diff --git a/guava/pom.xml b/guava/pom.xml
index 78c5a14e41..59ca3aa1bb 100644
--- a/guava/pom.xml
+++ b/guava/pom.xml
@@ -1,8 +1,8 @@
4.0.0
- org.baeldung
+ com.baeldung
guava
- 0.1-SNAPSHOT
+ 0.1.0-SNAPSHOT
guava
@@ -34,7 +34,7 @@
junit
- junit-dep
+ junit
${junit.version}
test
@@ -93,41 +93,37 @@
-
- 4.1.5.RELEASE
- 3.2.5.RELEASE
-
- 4.3.10.Final
- 5.1.35
+ 4.3.11.Final
+ 5.1.38
- 1.7.12
+ 1.7.13
1.1.3
5.1.3.Final
- 18.0
+ 19.0
3.4
1.3
- 4.11
+ 4.12
1.10.19
4.4.1
4.5
- 2.4.1
+ 2.9.0
- 3.3
+ 3.5.1
2.6
- 2.18.1
+ 2.19.1
2.7
- 1.4.14
+ 1.4.18
diff --git a/guava/src/main/webapp/WEB-INF/api-servlet.xml b/guava/src/main/webapp/WEB-INF/api-servlet.xml
deleted file mode 100644
index 4c74be8912..0000000000
--- a/guava/src/main/webapp/WEB-INF/api-servlet.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/guava/src/main/webapp/WEB-INF/web.xml b/guava/src/main/webapp/WEB-INF/web.xml
deleted file mode 100644
index 935beae648..0000000000
--- a/guava/src/main/webapp/WEB-INF/web.xml
+++ /dev/null
@@ -1,41 +0,0 @@
-
-
-
- Spring MVC Application
-
-
-
- contextClass
-
- org.springframework.web.context.support.AnnotationConfigWebApplicationContext
-
-
-
- contextConfigLocation
- org.baeldung.config
-
-
-
- org.springframework.web.context.ContextLoaderListener
-
-
-
-
- api
- org.springframework.web.servlet.DispatcherServlet
- 1
-
-
- api
- /
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java b/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java
index 26d3fa90ca..9c38afbcc2 100644
--- a/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java
+++ b/guava/src/test/java/org/baeldung/guava/GuavaCollectionTypesTest.java
@@ -148,6 +148,15 @@ public class GuavaCollectionTypesTest {
assertThat(intersection, containsInAnyOrder('b', 'c'));
}
+ @Test
+ public void whenCalculatingSetSymmetricDifference_thenCorrect() {
+ final Set first = ImmutableSet.of('a', 'b', 'c');
+ final Set second = ImmutableSet.of('b', 'c', 'd');
+
+ final Set intersection = Sets.symmetricDifference(first, second);
+ assertThat(intersection, containsInAnyOrder('a', 'd'));
+ }
+
@Test
public void whenCalculatingPowerSet_thenCorrect() {
final Set chars = ImmutableSet.of('a', 'b');
diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java b/guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java
new file mode 100644
index 0000000000..602205ff9f
--- /dev/null
+++ b/guava/src/test/java/org/baeldung/guava/GuavaMapFromSet.java
@@ -0,0 +1,101 @@
+package org.baeldung.guava;
+
+import java.util.AbstractMap;
+import java.util.AbstractSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.WeakHashMap;
+
+import com.google.common.base.Function;
+
+public class GuavaMapFromSet extends AbstractMap {
+
+ private class SingleEntry implements Entry {
+ private K key;
+
+ public SingleEntry( K key) {
+ this.key = key;
+ }
+
+ @Override
+ public K getKey() {
+ return this.key;
+ }
+
+ @Override
+ public V getValue() {
+ V value = GuavaMapFromSet.this.cache.get(this.key);
+ if (value == null) {
+ value = GuavaMapFromSet.this.function.apply(this.key);
+ GuavaMapFromSet.this.cache.put(this.key, value);
+ }
+ return value;
+ }
+
+ @Override
+ public V setValue( V value) {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ private class MyEntrySet extends AbstractSet> {
+
+ public class EntryIterator implements Iterator> {
+ private Iterator inner;
+
+ public EntryIterator() {
+ this.inner = MyEntrySet.this.keys.iterator();
+ }
+
+ @Override
+ public boolean hasNext() {
+ return this.inner.hasNext();
+ }
+
+ @Override
+ public Map.Entry next() {
+ K key = this.inner.next();
+ return new SingleEntry(key);
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+ private Set keys;
+
+ public MyEntrySet( Set keys) {
+ this.keys = keys;
+ }
+
+ @Override
+ public Iterator> iterator() {
+ return new EntryIterator();
+ }
+
+ @Override
+ public int size() {
+ return this.keys.size();
+ }
+
+ }
+
+ private WeakHashMap cache;
+ private Set> entries;
+ private Function super K, ? extends V> function;
+
+ public GuavaMapFromSet( Set keys, Function super K, ? extends V> function) {
+ this.function = function;
+ this.cache = new WeakHashMap();
+ this.entries = new MyEntrySet(keys);
+ }
+
+ @Override
+ public Set> entrySet() {
+ return this.entries;
+ }
+
+}
diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapFromSetTests.java b/guava/src/test/java/org/baeldung/guava/GuavaMapFromSetTests.java
new file mode 100644
index 0000000000..9abb5d14a9
--- /dev/null
+++ b/guava/src/test/java/org/baeldung/guava/GuavaMapFromSetTests.java
@@ -0,0 +1,66 @@
+package org.baeldung.guava;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.junit.Test;
+
+import com.google.common.base.Function;
+
+public class GuavaMapFromSetTests {
+
+ @Test
+ public void givenStringSet_whenMapsToElementLength_thenCorrect() {
+ Function function = new Function() {
+
+ @Override
+ public String apply(Integer from) {
+ return Integer.toBinaryString(from.intValue());
+ }
+ };
+ Set set = (Set) new TreeSet(Arrays.asList(
+ 32, 64, 128));
+ Map map = new GuavaMapFromSet(set,
+ function);
+ assertTrue(map.get(32).equals("100000")
+ && map.get(64).equals("1000000")
+ && map.get(128).equals("10000000"));
+ }
+
+ @Test
+ public void givenIntSet_whenMapsToElementBinaryValue_thenCorrect() {
+ Function function = new Function() {
+
+ @Override
+ public Integer apply(String from) {
+ return from.length();
+ }
+ };
+ Set set = (Set) new TreeSet(Arrays.asList(
+ "four", "three", "twelve"));
+ Map map = new GuavaMapFromSet(set,
+ function);
+ assertTrue(map.get("four") == 4 && map.get("three") == 5
+ && map.get("twelve") == 6);
+ }
+ @Test
+ public void givenSet_whenNewSetElementAddedAndMappedLive_thenCorrect() {
+ Function function = new Function() {
+
+ @Override
+ public Integer apply(String from) {
+ return from.length();
+ }
+ };
+ Set set = (Set) new TreeSet(Arrays.asList(
+ "four", "three", "twelve"));
+ Map map = new GuavaMapFromSet(set,
+ function);
+ set.add("one");
+ assertTrue(map.get("one") == 3 && map.size()==4);
+ }
+}
diff --git a/guava/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java b/guava/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java
new file mode 100644
index 0000000000..63583987ea
--- /dev/null
+++ b/guava/src/test/java/org/baeldung/java/CollectionJavaPartitionUnitTest.java
@@ -0,0 +1,70 @@
+package org.baeldung.java;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertThat;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+import org.junit.Test;
+
+import com.google.common.collect.Lists;
+
+public class CollectionJavaPartitionUnitTest {
+
+ // java8 groupBy
+ @Test
+ public final void givenList_whenParitioningIntoNSublistsUsingGroupingBy_thenCorrect() {
+ final List intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
+
+ final Map> groups = intList.stream().collect(Collectors.groupingBy(s -> (s - 1) / 3));
+ final List> subSets = new ArrayList>(groups.values());
+
+ // When
+ final List lastPartition = subSets.get(2);
+ final List expectedLastPartition = Lists. newArrayList(7, 8);
+ assertThat(subSets.size(), equalTo(3));
+ assertThat(lastPartition, equalTo(expectedLastPartition));
+
+ // intList.add(9);
+ // System.out.println(groups.values());
+ }
+
+ // java8 partitionBy
+ @Test
+ public final void givenList_whenParitioningIntoSublistsUsingPartitionBy_thenCorrect() {
+ final List intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
+
+ final Map> groups = intList.stream().collect(Collectors.partitioningBy(s -> s > 6));
+ final List> subSets = new ArrayList>(groups.values());
+
+ // When
+ final List lastPartition = subSets.get(1);
+ final List expectedLastPartition = Lists. newArrayList(7, 8);
+ assertThat(subSets.size(), equalTo(2));
+ assertThat(lastPartition, equalTo(expectedLastPartition));
+
+ // intList.add(9);
+ // System.out.println(groups.values());
+ }
+
+ // java8 split by separator
+ @Test
+ public final void givenList_whenSplittingBySeparator_thenCorrect() {
+ final List intList = Lists.newArrayList(1, 2, 3, 0, 4, 5, 6, 0, 7, 8);
+
+ final int[] indexes = Stream.of(IntStream.of(-1), IntStream.range(0, intList.size()).filter(i -> intList.get(i) == 0), IntStream.of(intList.size())).flatMapToInt(s -> s).toArray();
+ final List> subSets = IntStream.range(0, indexes.length - 1).mapToObj(i -> intList.subList(indexes[i] + 1, indexes[i + 1])).collect(Collectors.toList());
+
+ // When
+ final List lastPartition = subSets.get(2);
+ final List expectedLastPartition = Lists. newArrayList(7, 8);
+ assertThat(subSets.size(), equalTo(3));
+ assertThat(lastPartition, equalTo(expectedLastPartition));
+ }
+
+}
diff --git a/spring-security-oauth/.project b/guava18/.project
similarity index 90%
rename from spring-security-oauth/.project
rename to guava18/.project
index fe6e295165..11dff52392 100644
--- a/spring-security-oauth/.project
+++ b/guava18/.project
@@ -1,6 +1,6 @@
- spring-security-oauth
+ guava18
diff --git a/guava18/README.md b/guava18/README.md
index 8960b4676e..9924d7c16f 100644
--- a/guava18/README.md
+++ b/guava18/README.md
@@ -7,7 +7,6 @@
- [Guava Collections Cookbook](http://www.baeldung.com/guava-collections)
- [Guava Ordering Cookbook](http://www.baeldung.com/guava-order)
- [Guava Functional Cookbook](http://www.baeldung.com/guava-functions-predicates)
-
- [Hamcrest Collections Cookbook](http://www.baeldung.com/hamcrest-collections-arrays)
-
- [Partition a List in Java](http://www.baeldung.com/java-list-split)
+- [Guava 18: What’s New?](http://www.baeldung.com/whats-new-in-guava-18)
diff --git a/guava18/pom.xml b/guava18/pom.xml
index 21f4697a73..6002b37d74 100644
--- a/guava18/pom.xml
+++ b/guava18/pom.xml
@@ -5,8 +5,8 @@
4.0.0
com.baeldung
- guava
- 1.0-SNAPSHOT
+ guava18
+ 0.1.0-SNAPSHOT
diff --git a/guava19/.project b/guava19/.project
new file mode 100644
index 0000000000..b4c292ad2c
--- /dev/null
+++ b/guava19/.project
@@ -0,0 +1,17 @@
+
+
+ guava19
+
+
+
+
+
+ org.eclipse.m2e.core.maven2Builder
+
+
+
+
+
+ org.eclipse.m2e.core.maven2Nature
+
+
diff --git a/guava19/README.md b/guava19/README.md
new file mode 100644
index 0000000000..be9f2d72a4
--- /dev/null
+++ b/guava19/README.md
@@ -0,0 +1,7 @@
+=========
+
+## Guava 19
+
+
+### Relevant Articles:
+- [Guava 19: What’s New?](http://www.baeldung.com/whats-new-in-guava-19)
diff --git a/guava19/pom.xml b/guava19/pom.xml
index 97c1b0ea4e..13f3b471f1 100644
--- a/guava19/pom.xml
+++ b/guava19/pom.xml
@@ -1,12 +1,10 @@
-
+
4.0.0
com.baeldung
- guava
- 1.0-SNAPSHOT
+ guava19
+ 0.1.0-SNAPSHOT
@@ -25,6 +23,7 @@
1.3
+
diff --git a/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java b/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java
index 903381bd29..c7b8441b78 100644
--- a/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java
+++ b/guava19/src/test/java/com/baeldung/guava/GuavaMiscUtilsTest.java
@@ -1,16 +1,9 @@
package com.baeldung.guava;
-import com.baeldung.guava.entity.User;
-import com.google.common.base.CharMatcher;
import com.google.common.base.Throwables;
import com.google.common.collect.*;
-import com.google.common.hash.HashCode;
-import com.google.common.hash.HashFunction;
-import com.google.common.hash.Hashing;
-import com.google.common.reflect.TypeToken;
import org.junit.Test;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
diff --git a/handling-spring-static-resources/.classpath b/handling-spring-static-resources/.classpath
index 88536687a5..613195248b 100644
--- a/handling-spring-static-resources/.classpath
+++ b/handling-spring-static-resources/.classpath
@@ -6,7 +6,11 @@
-
+
+
+
+
+
@@ -19,9 +23,9 @@
-
+
-
+
diff --git a/handling-spring-static-resources/.project b/handling-spring-static-resources/.project
index a16def8042..ae47dfac0e 100644
--- a/handling-spring-static-resources/.project
+++ b/handling-spring-static-resources/.project
@@ -1,6 +1,6 @@
- handling-spring-static-resources
+ spring-static-resources
diff --git a/handling-spring-static-resources/pom.xml b/handling-spring-static-resources/pom.xml
index 67591e1844..f47d8a5592 100644
--- a/handling-spring-static-resources/pom.xml
+++ b/handling-spring-static-resources/pom.xml
@@ -1,12 +1,14 @@
4.0.0
- org.baeldung
- handling-spring-static-resources
- handling-spring-static-resources
- 0.1-SNAPSHOT
+
+ com.baeldung
+ spring-static-resources
+ 0.1.0-SNAPSHOT
war
+ spring-static-resources
+
@@ -161,7 +163,7 @@
- handling-spring-static-resources
+ spring-static-resources
src/main/resources
@@ -171,53 +173,50 @@
- 1.7
+ 1.8
+
- 4.1.5.RELEASE
- 3.2.5.RELEASE
+ 4.2.5.RELEASE
+ 4.0.4.RELEASE
1.8.1
2.3.2-b01
-
- 4.1.5.RELEASE
- 3.2.5.RELEASE
-
- 4.3.10.Final
- 5.1.35
- 1.7.2.RELEASE
+ 4.3.11.Final
+ 5.1.38
+ 1.9.2.RELEASE
- 2.4.4
+ 2.7.2
- 1.7.12
+ 1.7.13
1.1.3
- 5.1.3.Final
+ 5.2.2.Final
- 18.0
+ 19.0
3.4
1.3
- 4.11
+ 4.12
1.10.19
4.4.1
4.5
- 2.4.1
+ 2.9.0
- 3.3
+ 3.5.1
2.6
- 2.18.1
- 1.4.14
+ 2.19.1
+ 1.4.18
\ No newline at end of file
diff --git a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml b/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml
index 56d7f9c113..76b5015e7b 100644
--- a/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml
+++ b/handling-spring-static-resources/src/main/resources/webSecurityConfig.xml
@@ -2,10 +2,10 @@
@@ -21,7 +21,7 @@
-
+
diff --git a/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp b/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp
index 1b09f7c634..8c9f46c027 100644
--- a/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp
+++ b/handling-spring-static-resources/src/main/webapp/WEB-INF/view/login.jsp
@@ -41,15 +41,15 @@
-