Merge branch 'master' into pr/470-alexB-logging

This commit is contained in:
Slavisa Baeldung 2016-06-30 16:38:55 +02:00
commit d67f19d9e5
1436 changed files with 41183 additions and 24850 deletions

7
.gitignore vendored
View File

@ -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/

View File

@ -1,11 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>parent</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
</buildSpec>
<natures>
</natures>
<name>parent-modules</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@ -1,8 +1,8 @@
The "REST with Spring" Classes
==============================
This is what I'm working on: <br/>
**[>> 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: <br/>
**[>> 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/)**

View File

@ -1,6 +1,6 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<groupId>com.baeldung</groupId>
<artifactId>apache-fop</artifactId>
<version>0.1-SNAPSHOT</version>
@ -37,7 +37,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
@ -142,16 +142,12 @@
</build>
<properties>
<!-- Spring -->
<org.springframework.version>4.1.5.RELEASE</org.springframework.version>
<org.springframework.security.version>3.2.5.RELEASE</org.springframework.security.version>
<!-- persistence -->
<hibernate.version>4.3.8.Final</hibernate.version>
<mysql-connector-java.version>5.1.34</mysql-connector-java.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<!-- marshalling -->
<jackson.version>2.4.4</jackson.version>
<jackson.version>2.7.2</jackson.version>
<!-- logging -->
<org.slf4j.version>1.7.9</org.slf4j.version>
@ -161,25 +157,25 @@
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<!-- util -->
<guava.version>17.0</guava.version> <!-- upgrade to 18.0 -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.3.2</commons-lang3.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.11</junit.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<httpcore.version>4.4</httpcore.version>
<httpclient.version>4.4</httpclient.version>
<rest-assured.version>2.4.0</rest-assured.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.2</maven-compiler-plugin.version>
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.12</cargo-maven2-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
</properties>

38
assertj/pom.xml Normal file
View File

@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>assertj</artifactId>
<version>1.0.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.4.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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<String> list = Arrays.asList("1", "2", "3");
assertThat(list)
.contains("1");
}
@Test
public void whenCheckingForElement_thenMultipleAssertions() throws Exception {
List<String> 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<Integer, String> 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);
}
}

View File

@ -1,15 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>core-java-8</name>
<name>core-java8</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
@ -17,8 +12,6 @@
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@ -1,5 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/webapp"/>
<classpathentry kind="output" path=""/>
</classpath>

View File

@ -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

View File

@ -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

View File

@ -1,4 +0,0 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

View File

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beansProjectDescription>
<version>1</version>
<pluginVersion><![CDATA[3.3.0.201307091516-RELEASE]]></pluginVersion>
<configSuffixes>
<configSuffix><![CDATA[xml]]></configSuffix>
</configSuffixes>
<enableImports><![CDATA[false]]></enableImports>
<configs>
<config>src/main/webapp/WEB-INF/api-servlet.xml</config>
</configs>
<configSets>
</configSets>
</beansProjectDescription>

View File

@ -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)

View File

@ -1,10 +1,11 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<artifactId>spring-rest</artifactId>
<groupId>com.baeldung</groupId>
<artifactId>core-java8</artifactId>
<version>0.1-SNAPSHOT</version>
<name>spring-rest</name>
<name>core-java8</name>
<dependencies>
@ -40,6 +41,12 @@
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
@ -56,6 +63,12 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
@ -98,14 +111,14 @@
<properties>
<!-- logging -->
<org.slf4j.version>1.7.12</org.slf4j.version>
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.0.13</logback.version>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<!-- util -->
<guava.version>18.0</guava.version>
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<!-- testing -->
@ -114,9 +127,9 @@
<mockito.version>1.10.19</mockito.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
</properties>

View File

@ -0,0 +1,12 @@
package com.baeldung;
import java.util.function.Consumer;
import java.util.function.Function;
public interface Adder {
String addWithFunction(Function<String, String> f);
void addWithConsumer(Consumer<Integer> f);
}

View File

@ -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<String, String> f) {
return f.apply("Something ");
}
@Override
public void addWithConsumer(final Consumer<Integer> f) {
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung;
@FunctionalInterface
public interface Bar {
String method(String string);
default String defaultMethod() {
return "String from Bar";
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung;
@FunctionalInterface
public interface Baz {
String method(String string);
default String defaultMethod() {
return "String from Baz";
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung;
@FunctionalInterface
public interface Foo {
String method(String string);
default void defaultMethod() {
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung;
@FunctionalInterface
public interface FooExtended extends Baz, Bar {
@Override
default String defaultMethod() {
return Bar.super.defaultMethod();
}
}

View File

@ -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<String, String> 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;
}
}

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.datetime;
import java.time.LocalDateTime;
public class UseLocalDateTime {
public LocalDateTime getLocalDateTimeUsingParseMethod(String representation){
return LocalDateTime.parse(representation);
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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<Computer> filter(final List<Computer> inventory, final ComputerPredicate p) {
final List<Computer> 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);
}
}
}

View File

@ -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<Double, Double> function = super::calculateValue;
final Double pcValue = function.apply(initialValue);
System.out.println("First value is:" + pcValue);
return pcValue + (initialValue / 10);
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.doublecolon.function;
import com.baeldung.doublecolon.Computer;
@FunctionalInterface
public interface ComputerPredicate {
boolean filter(Computer c);
}

View File

@ -0,0 +1,15 @@
package com.baeldung.doublecolon.function;
import java.util.Objects;
import java.util.function.Function;
@FunctionalInterface
public interface TriFunction<A, B, C, R> {
R apply(A a, B b, C c);
default <V> TriFunction<A, B, C, V> 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));
}
}

View File

@ -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<PizzaStatusEnum> 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<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
}
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> 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);
}
}
}

View File

@ -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);
}

View File

@ -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;
}
}

View File

@ -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<CustomRecursiveAction> createSubtasks() {
List<CustomRecursiveAction> 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());
}
}

View File

@ -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<Integer> {
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<CustomRecursiveTask> createSubtasks() {
List<CustomRecursiveTask> 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();
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.forkjoin.util;
import java.util.concurrent.ForkJoinPool;
public class PoolUtil {
public static ForkJoinPool forkJoinPool = new ForkJoinPool(2);
}

View File

@ -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;
}
}

View File

@ -0,0 +1,4 @@
package com.baeldung.java_8_features;
public class CustomException extends RuntimeException {
}

View File

@ -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<String> PARTS = Arrays.asList("turbine", "pump");
public List<String> getParts() {
return PARTS;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.java_8_features;
import java.util.Optional;
public class OptionalAddress {
private String street;
public Optional<String> getStreet() {
return Optional.ofNullable(street);
}
public void setStreet(String street) {
this.street = street;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.java_8_features;
import java.util.Optional;
public class OptionalUser {
private OptionalAddress address;
public Optional<OptionalAddress> getAddress() {
return Optional.of(address);
}
public void setAddress(OptionalAddress address) {
this.address = address;
}
}

View File

@ -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<String> 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;
}
}

View File

@ -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();
}
}

View File

@ -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
}
}

View File

@ -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<String> streamOf(List<String> list) {
return (list == null || list.isEmpty()) ? Stream.empty() : list.stream();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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<String> 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();
}
}

Binary file not shown.

Binary file not shown.

View File

@ -10,7 +10,7 @@
<!-- <logger name="org.springframework" level="WARN" /> -->
<root level="INFO">
<appender-ref ref="STDOUT" />
<appender-ref ref="STDOUT"/>
</root>
</configuration>

Binary file not shown.

View File

@ -0,0 +1 @@
Hello World!

View File

@ -0,0 +1 @@
Hello World!

View File

@ -0,0 +1 @@
My Name is John

View File

@ -0,0 +1 @@
My Name is Tom

View File

@ -0,0 +1 @@
My Name is Jane

View File

@ -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();
}
}

View File

@ -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);
}
}

View File

@ -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")));
}
}

View File

@ -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());
}
}

View File

@ -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));
}
}

View File

@ -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));
}
}

View File

@ -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));
}
}

View File

@ -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<Integer, String, Computer> c4Function = Computer::new;
Computer c4 = c4Function.apply(2013, "white");
BiFunction<Integer, String, Computer> c5Function = Computer::new;
Computer c5 = c5Function.apply(2010, "black");
BiFunction<Integer, String, Computer> c6Function = Computer::new;
Computer c6 = c6Function.apply(2008, "black");
List<Computer> inventory = Arrays.asList(c1, c2, c3, c4, c5, c6);
List<Computer> blackComputer = filter(inventory, blackPredicate);
Assert.assertEquals("The black Computers are: ", blackComputer.size(), 4);
List<Computer> after2010Computer = filter(inventory, after2010Predicate);
Assert.assertEquals("The Computer bought after 2010 are: ", after2010Computer.size(), 3);
List<Computer> 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<Integer, String, Integer, Computer> c6Function = Computer::new;
Computer c3 = c6Function.apply(2008, "black", 90);
List<Computer> 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<Computer> inventory = Arrays.asList(c1, c2);
inventory.forEach(Computer::turnOnPc);
}
@Test
public void testSuperMethodReference() {
final TriFunction<Integer, String, Integer, MacbookPro> 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);
}
}

View File

@ -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<Pizza> 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<Pizza> undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
assertTrue(undeliveredPzs.size() == 3);
}
@Test
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
List<Pizza> 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<Pizza.PizzaStatusEnum, List<Pizza>> 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);
}
}

View File

@ -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<Integer> 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<Integer> listWithDuplicates = Lists.newArrayList(1, 1, 2, 2, 3, 3);

View File

@ -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");
}
}

View File

@ -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<String> callableTask;
private List<Callable<String>> 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<Runnable> notExecutedTasks = smartShutdown(threadPoolExecutor);
assertTrue(threadPoolExecutor.isShutdown());
assertFalse(notExecutedTasks.isEmpty());
assertTrue(notExecutedTasks.size() > 0 && notExecutedTasks.size() < 98);
}
private List<Runnable> smartShutdown(ExecutorService executorService) {
List<Runnable> 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<Future<String>> 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<String> 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<String> 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<String> 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);
}
}

View File

@ -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);
}
}

View File

@ -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<String, String> 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]);
}
}

View File

@ -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<String> 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<User> 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<User> stream = list.stream().map(User::new);
List<User> userList = stream.collect(Collectors.toList());
assertEquals(userList.size(), list.size());
assertTrue(userList.get(0) instanceof User);
}
}

View File

@ -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<String> 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<String> optionalEmpty = Optional.empty();
assertFalse(optionalEmpty.isPresent());
String str = "value";
Optional<String> optional = Optional.of(str);
assertEquals(optional.get(), "value");
Optional<String> optionalNullable = Optional.ofNullable(str);
Optional<String> optionalNull = Optional.ofNullable(null);
assertEquals(optionalNullable.get(), "value");
assertFalse(optionalNull.isPresent());
List<String> listOpt = Optional.of(list).orElse(new ArrayList<>());
List<String> listNull = null;
List<String> listOptNull = Optional.ofNullable(listNull).orElse(new ArrayList<>());
assertTrue(listOpt == list);
assertTrue(listOptNull.isEmpty());
Optional<User> user = Optional.ofNullable(getUser());
String result = user.map(User::getAddress)
.map(Address::getStreet)
.orElse("not specified");
assertEquals(result, "1st Avenue");
Optional<OptionalUser> optionalUser = Optional.ofNullable(getOptionalUser());
String resultOpt = optionalUser.flatMap(OptionalUser::getAddress)
.flatMap(OptionalAddress::getStreet)
.orElse("not specified");
assertEquals(resultOpt, "1st Avenue");
Optional<User> userNull = Optional.ofNullable(getUserNull());
String resultNull = userNull.map(User::getAddress)
.map(Address::getStreet)
.orElse("not specified");
assertEquals(resultNull, "not specified");
Optional<OptionalUser> 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;
}
}

View File

@ -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 {

View File

@ -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<Product> 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<String> 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<String> 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<String> streamEmpty = Stream.empty();
assertEquals(0, streamEmpty.count());
List<String> names = Collections.emptyList();
Stream<String> streamOf = Product.streamOf(names);
assertTrue(streamOf.count() == 0);
}
@Test
public void createStream_whenCreated_thenCorrect() {
Collection<String> collection = Arrays.asList("a", "b", "c");
Stream<String> streamOfCollection = collection.stream();
assertEquals(3, streamOfCollection.count());
Stream<String> streamOfArray = Stream.of("a", "b", "c");
assertEquals(3, streamOfArray.count());
String[] arr = new String[]{"a", "b", "c"};
Stream<String> 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<String> streamOfString = Pattern.compile(", ").splitAsStream("a, b, c");
assertEquals("a", streamOfString.findFirst().get());
Path path = getPath();
Stream<String> 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<String> streamBuilder = Stream.<String>builder().add("a").add("b").add("c").build();
assertEquals(3, streamBuilder.count());
Stream<String> streamGenerated = Stream.generate(() -> "element").limit(10);
assertEquals(10, streamGenerated.count());
Stream<Integer> streamIterated = Stream.iterate(40, n -> n + 2).limit(20);
assertTrue(40 <= streamIterated.findAny().get());
}
@Test
public void runStreamPipeline_whenOrderIsRight_thenCorrect() {
List<String> list = Arrays.asList("abc1", "abc2", "abc3");
Optional<String> 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<String> 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<Integer, List<Product>> collectorMapOfLists = productList.stream()
.collect(Collectors.groupingBy(Product::getPrice));
assertEquals(3, collectorMapOfLists.keySet().size());
Map<Boolean, List<Product>> 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<Product> unmodifiableSet = productList.stream()
.collect(Collectors.collectingAndThen(Collectors.toSet(),
Collections::unmodifiableSet));
unmodifiableSet.add(new Product(4, "tea"));
}
@Test
public void customCollector_whenResultContainsAllElementsFrSource_thenCorrect() {
Collector<Product, ?, LinkedList<Product>> toLinkedList =
Collector.of(LinkedList::new, LinkedList::add,
(first, second) -> {
first.addAll(second);
return first;
});
LinkedList<Product> linkedListOfPersons = productList.stream().collect(toLinkedList);
assertTrue(linkedListOfPersons.containsAll(productList));
}
@Test
public void parallelStream_whenWorks_thenCorrect() {
Stream<Product> 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++;
}
}

View File

@ -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<String> 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<String> streamArr = Arrays.stream(arr);
assertEquals(streamArr.count(), 3);
Stream<String> 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<String> streamFilter = list.stream().filter(element -> element.isEmpty());
assertEquals(streamFilter.count(), 2);
}
@Test
public void checkStreamCount_whenOperationMap_thanCorrect() {
List<String> uris = new ArrayList<>();
uris.add("C:\\My.txt");
Stream<Path> streamMap = uris.stream().map(uri -> Paths.get(uri));
assertEquals(streamMap.count(), 1);
List<Detail> details = new ArrayList<>();
details.add(new Detail());
details.add(new Detail());
Stream<String> 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<Integer> 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<String> 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
}
}

View File

@ -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<Path>() {
@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<File> 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);

View File

@ -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);
}
}
}

View File

@ -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

View File

@ -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 {

View File

@ -1,4 +1,4 @@
package org.baeldung.java8.entity;
package com.baeldung.java8.entity;
public class Human {
private String name;

View File

@ -27,7 +27,7 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="owner.project.facets" value="java"/>
</attributes>

View File

@ -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

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
<installed facet="java" version="1.7"/>
<installed facet="java" version="1.8"/>
</faceted-project>

View File

@ -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)

View File

@ -1,15 +1,19 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.baeldung</groupId>
<groupId>com.baeldung</groupId>
<artifactId>core-java</artifactId>
<version>0.1-SNAPSHOT</version>
<version>0.1.0-SNAPSHOT</version>
<name>core-java</name>
<dependencies>
<!-- utils -->
<dependency>
<groupId>net.sourceforge.collections</groupId>
<artifactId>collections-generic</artifactId>
<version>4.01</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
@ -79,7 +83,7 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
@ -122,8 +126,8 @@
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
@ -143,44 +147,40 @@
</build>
<properties>
<!-- Spring -->
<org.springframework.version>4.1.5.RELEASE</org.springframework.version>
<org.springframework.security.version>3.2.5.RELEASE</org.springframework.security.version>
<!-- persistence -->
<hibernate.version>4.3.10.Final</hibernate.version>
<mysql-connector-java.version>5.1.35</mysql-connector-java.version>
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
<!-- marshalling -->
<jackson.version>2.4.4</jackson.version>
<jackson.version>2.7.2</jackson.version>
<!-- logging -->
<org.slf4j.version>1.7.12</org.slf4j.version>
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<!-- util -->
<guava.version>18.0</guava.version>
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.11</junit.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<rest-assured.version>2.4.1</rest-assured.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.3</maven-compiler-plugin.version>
<maven-compiler-plugin.version>3.5.1</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.14</cargo-maven2-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
</properties>

View File

@ -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<PizzaStatus> 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<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
return input.stream().filter(
(s) -> undeliveredPizzaStatuses.contains(s.getStatus()))
.collect(Collectors.toList());
}
public static EnumMap<PizzaStatus, List<Pizza>>
groupPizzaByStatus(List<Pizza> 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<Pizza> thatAreNotDelivered() {
return entry -> undeliveredPizzaStatuses.contains(entry.getStatus());
}
}

View File

@ -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);
}

View File

@ -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;
}
}

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd" >
</beans>

View File

@ -1,41 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
>
<display-name>Spring MVC Application</display-name>
<!-- Spring root -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.baeldung.config</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring child -->
<servlet>
<servlet-name>api</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>api</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file/>
</welcome-file-list>
</web-app>

View File

@ -31,7 +31,7 @@ public class JavaCollectionConversionUnitTest {
@Test
public final void givenUsingCoreJava_whenListConvertedToArray_thenCorrect() {
final List<Integer> sourceList = Lists.<Integer> newArrayList(0, 1, 2, 3, 4, 5);
final List<Integer> sourceList = Arrays.asList(0, 1, 2, 3, 4, 5);
final Integer[] targetArray = sourceList.toArray(new Integer[sourceList.size()]);
}

View File

@ -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<Pizza> 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<Pizza> undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
assertTrue(undeliveredPzs.size() == 3);
}
@Test
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
List<Pizza> 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<Pizza.PizzaStatus, List<Pizza>> 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);
}
}

View File

@ -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()));
}

Some files were not shown because too many files have changed in this diff Show More