Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Kevin Gilmore 2016-06-03 07:28:26 -05:00
commit 23e8b11e06
228 changed files with 8823 additions and 1144 deletions

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,101 +0,0 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled
org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull
org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault
org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable
org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
org.eclipse.jdt.core.compiler.problem.deadCode=warning
org.eclipse.jdt.core.compiler.problem.deprecation=warning
org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore
org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled
org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled
org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore
org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore
org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore
org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning
org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error
org.eclipse.jdt.core.compiler.problem.nullReference=warning
org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error
org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning
org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore
org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore
org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore
org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore
org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled
org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled
org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error
org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled
org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning
org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore
org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedImport=warning
org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore
org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore
org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
org.eclipse.jdt.core.compiler.source=1.8

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

@ -1,4 +1,5 @@
<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>com.baeldung</groupId>
<artifactId>core-java8</artifactId>

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

@ -13,7 +13,7 @@ public class UnzipFile {
final byte[] buffer = new byte[1024];
final ZipInputStream zis = new ZipInputStream(new FileInputStream(fileZip));
ZipEntry zipEntry = zis.getNextEntry();
while(zipEntry != null){
while (zipEntry != null) {
final String fileName = zipEntry.getName();
final File newFile = new File("src/main/resources/unzipTest/" + fileName);
final FileOutputStream fos = new FileOutputStream(newFile);

View File

@ -18,7 +18,7 @@ public class ZipFile {
zipOut.putNextEntry(zipEntry);
final byte[] bytes = new byte[1024];
int length;
while((length = fis.read(bytes)) >= 0) {
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
zipOut.close();

View File

@ -22,7 +22,7 @@ public class ZipMultipleFiles {
final byte[] bytes = new byte[1024];
int length;
while((length = fis.read(bytes)) >= 0) {
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
fis.close();

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>

View File

@ -6,7 +6,9 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import static com.baeldung.doublecolon.ComputerUtils.*;

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

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

@ -7,6 +7,7 @@ import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import static org.junit.Assert.*;
@ -53,8 +54,8 @@ public class Java8ExecutorServiceTest {
public void creationSubmittingTasksShuttingDownNow_whenShutDownAfterAwating_thenCorrect() {
ExecutorService threadPoolExecutor =
new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>());
new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>());
for (int i = 0; i < 100; i++) {
threadPoolExecutor.submit(callableTask);

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

@ -1,16 +1,15 @@
package com.baeldung.java8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.function.Function;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.Foo;
import com.baeldung.FooExtended;
import com.baeldung.UseFoo;
import org.junit.Before;
import org.junit.Test;
import java.util.function.Function;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class Java8FunctionalInteracesLambdasTest {

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 com.baeldung.java8;
import static org.hamcrest.Matchers.equalTo;
import com.baeldung.java8.entity.Human;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import org.junit.Assert;
import org.junit.Test;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.java8.entity.Human;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import static org.hamcrest.Matchers.equalTo;
public class Java8SortUnitTest {

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,22 +1,18 @@
package com.baeldung.java8;
import static org.junit.Assert.assertEquals;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.DecimalFormat;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.StreamSupport;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class JavaFolderSizeTest {
@ -93,7 +89,7 @@ public class JavaFolderSizeTest {
final File folder = new File(path);
final long size = getFolderSize(folder);
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
final int unitIndex = (int) (Math.log10(size) / 3);
final double unitValue = 1 << (unitIndex * 10);

View File

@ -1,13 +1,13 @@
package com.baeldung.java8;
import org.junit.Assert;
import org.junit.Test;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.Scanner;
import org.junit.Assert;
import org.junit.Test;
public class JavaTryWithResourcesTest {
private static final String TEST_STRING_HELLO_WORLD = "Hello World";

View File

@ -1,14 +1,12 @@
package com.baeldung.java8.base64;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import static org.junit.Assert.*;
public class ApacheCommonsEncodeDecodeTest {
// tests

View File

@ -1,14 +1,12 @@
package com.baeldung.java8.base64;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.UUID;
import org.junit.Test;
import static org.junit.Assert.*;
public class Java8EncodeDecodeTest {

View File

@ -9,7 +9,11 @@
<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>

View File

@ -0,0 +1,117 @@
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.CollectionUtils;
import org.apache.commons.collections15.Predicate;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;
public class Pizza {
private static EnumSet<PizzaStatusEnum> undeliveredPizzaStatuses =
EnumSet.of(PizzaStatusEnum.ORDERED, PizzaStatusEnum.READY);
private PizzaStatusEnum status;
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
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;}
@JsonProperty("timeToDelivery")
public int getTimeToDelivery() {
return timeToDelivery;
}
private 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> getAllUndeliveredPizza(List<Pizza> input) {
List<Pizza> undelivered = input;
CollectionUtils.filter(undelivered, thatAreNotDelivered());
return undelivered;
}
public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pizzaList) {
EnumMap<PizzaStatusEnum, List<Pizza>> pzByStatus = new EnumMap<PizzaStatusEnum, List<Pizza>>(PizzaStatusEnum.class);
for (Pizza pz : pizzaList) {
PizzaStatusEnum status = pz.getStatus();
if (pzByStatus.containsKey(status)) {
pzByStatus.get(status).add(pz);
} else {
List<Pizza> newPzList = new ArrayList<Pizza>();
newPzList.add(pz);
pzByStatus.put(status, newPzList);
}
}
return pzByStatus;
}
public void deliver() {
if (isDeliverable()) {
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
this.setStatus(PizzaStatusEnum.DELIVERED);
}
}
public static String getJsonString(Pizza pz) throws IOException {
ObjectMapper mapper = new ObjectMapper();
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(pz);
}
private static Predicate<Pizza> thatAreNotDelivered() {
return new Predicate<Pizza>() {
public boolean evaluate(Pizza entry) {
return 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,20 @@
package com.baeldung.enums;
public enum PizzaDeliverySystemConfiguration {
INSTANCE ;
private 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,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.PizzaStatusEnum.READY);
assertTrue(testPz.isDeliverable());
}
@Test
public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
List<Pizza> pzList = new ArrayList<Pizza>();
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.getAllUndeliveredPizza(pzList);
assertTrue(undeliveredPzs.size() == 3);
}
@Test
public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
List<Pizza> pzList = new ArrayList<Pizza>();
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,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()));
}

17
guava18/.project Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>guava18</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>

17
guava19/.project Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>guava19</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

@ -79,18 +79,22 @@ public class HttpClientMultipartTest {
@Test
public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException {
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + TEXTFILENAME);
final File file = new File(url.getPath());
final FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
final StringBody stringBody1 = new StringBody("This is message 1", ContentType.MULTIPART_FORM_DATA);
final StringBody stringBody2 = new StringBody("This is message 2", ContentType.MULTIPART_FORM_DATA);
//
final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
builder.addPart("text1", stringBody1);
builder.addPart("text2", stringBody2);
final HttpEntity entity = builder.build();
//
post.setEntity(entity);
response = client.execute(post);
final int statusCode = response.getStatusLine().getStatusCode();
final String responseString = getContent();
final String contentTypeInHeader = getContentTypeHeader();
@ -124,7 +128,7 @@ public class HttpClientMultipartTest {
}
@Test
public final void givenFileandInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws ClientProtocolException, IOException {
final URL url = Thread.currentThread().getContextClassLoader().getResource("uploads/" + ZIPFILENAME);
final URL url2 = Thread.currentThread().getContextClassLoader().getResource("uploads/" + IMAGEFILENAME);
final InputStream inputStream = new FileInputStream(url.getPath());

View File

@ -1,5 +1,5 @@
<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">
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>jackson</artifactId>
@ -22,6 +22,12 @@
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!--jackson for xml-->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
@ -55,12 +61,12 @@
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jsonSchema</artifactId>
<version>2.7.2</version>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jsonSchema</artifactId>
<version>2.7.2</version>
</dependency>
<dependency>

View File

@ -0,0 +1,86 @@
package com.baeldung.jackson.xml;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.junit.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class TestXMLSerializeDeserialize {
@Test
public void whenJavaSerializedToXmlStr_thenCorrect() throws JsonProcessingException {
XmlMapper xmlMapper = new XmlMapper();
String xml = xmlMapper.writeValueAsString(new SimpleBean());
assertNotNull(xml);
}
@Test
public void whenJavaSerializedToXmlFile_thenCorrect() throws IOException {
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(new File("target/simple_bean.xml"), new SimpleBean());
File file = new File("target/simple_bean.xml");
assertNotNull(file);
}
@Test
public void whenJavaGotFromXmlStr_thenCorrect() throws IOException {
XmlMapper xmlMapper = new XmlMapper();
SimpleBean value = xmlMapper.readValue(
"<SimpleBean><x>1</x><y>2</y></SimpleBean>", SimpleBean.class);
assertTrue(value.getX() == 1 && value.getY() == 2);
}
@Test
public void whenJavaGotFromXmlFile_thenCorrect() throws IOException {
File file = new File("src/test/resources/simple_bean.xml");
XmlMapper xmlMapper = new XmlMapper();
String xml = inputStreamToString(new FileInputStream(file));
SimpleBean value = xmlMapper.readValue(xml, SimpleBean.class);
assertTrue(value.getX() == 1 && value.getY() == 2);
}
private static String inputStreamToString(InputStream is) throws IOException {
BufferedReader br;
StringBuilder sb = new StringBuilder();
String line;
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
}
class SimpleBean {
private int x = 1;
private int y = 2;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}

View File

@ -0,0 +1,4 @@
<SimpleBean>
<x>1</x>
<y>2</y>
</SimpleBean>

View File

@ -17,12 +17,7 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<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/J2SE-1.5">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>

View File

@ -10,6 +10,11 @@
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
@ -17,6 +22,7 @@
</buildCommand>
</buildSpec>
<natures>
<nature>org.springframework.ide.eclipse.core.springnature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>

2
jsf/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/target
*.iml

116
jsf/pom.xml Normal file
View File

@ -0,0 +1,116 @@
<?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">
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>jsf</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- JSF -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>${com.sun.faces.version}</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>${com.sun.faces.version}</version>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
<version>${javax.servlet.version}</version>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- Spring -->
<org.springframework.version>4.2.5.RELEASE</org.springframework.version>
<!-- JSF -->
<com.sun.faces.version>2.1.7</com.sun.faces.version>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<!--Tomcat-->
<javax.servlet.version>3.1.0</javax.servlet.version>
</properties>
</project>

View File

@ -0,0 +1,36 @@
package com.baeldung.springintegration.config;
import com.sun.faces.config.FacesInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.util.Set;
public class MainWebAppInitializer extends FacesInitializer implements WebApplicationInitializer {
private static final Logger LOGGER = LoggerFactory.getLogger(MainWebAppInitializer.class);
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
super.onStartup(classes, servletContext);
}
/**
* Register and configure all Servlet container components necessary to power the web application.
*/
@Override
public void onStartup(final ServletContext sc) throws ServletException {
LOGGER.info("MainWebAppInitializer.onStartup()");
sc.setInitParameter("javax.faces.FACELETS_SKIP_COMMENTS", "true");
// Create the 'root' Spring application context
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.register(SpringCoreConfig.class);
sc.addListener(new ContextLoaderListener(root));
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.springintegration.config;
import com.baeldung.springintegration.dao.UserManagementDAO;
import com.baeldung.springintegration.dao.UserManagementDAOImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SpringCoreConfig {
@Bean
public UserManagementDAO userManagementDAO() {
return new UserManagementDAOImpl();
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.springintegration.controllers;
import com.baeldung.springintegration.dao.UserManagementDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import java.io.Serializable;
@ManagedBean(name = "registration")
@ViewScoped
public class RegistrationBean implements Serializable {
private static final Logger LOGGER = LoggerFactory.getLogger(RegistrationBean.class);
@ManagedProperty(value = "#{userManagementDAO}")
transient private UserManagementDAO userDao;
private String userName;
private String operationMessage;
public void createNewUser() {
try {
LOGGER.info("Creating new user");
FacesContext context = FacesContext.getCurrentInstance();
boolean operationStatus = userDao.createUser(userName);
context.isValidationFailed();
if (operationStatus) {
operationMessage = "User " + userName + " created";
}
} catch (Exception ex) {
LOGGER.error("Error registering new user ");
ex.printStackTrace();
operationMessage = "Error " + userName + " not created";
}
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setUserDao(UserManagementDAO userDao) {
this.userDao = userDao;
}
public UserManagementDAO getUserDao() {
return this.userDao;
}
public String getOperationMessage() {
return operationMessage;
}
public void setOperationMessage(String operationMessage) {
this.operationMessage = operationMessage;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.springintegration.dao;
public interface UserManagementDAO {
boolean createUser(String newUserData);
}

View File

@ -0,0 +1,38 @@
package com.baeldung.springintegration.dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
@Repository
public class UserManagementDAOImpl implements UserManagementDAO {
private static final Logger LOGGER = LoggerFactory.getLogger(UserManagementDAOImpl.class);
private List<String> users;
@PostConstruct
public void initUserList() {
users = new ArrayList<>();
}
@Override
public boolean createUser(String newUserData) {
if (newUserData != null) {
users.add(newUserData);
LOGGER.info("User {} successfully created", newUserData);
return true;
} else {
return false;
}
}
public UserManagementDAOImpl() {
}
}

View File

@ -0,0 +1,14 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,3 @@
message.valueRequired = This value is required
message.welcome = Baeldung | Register
label.saveButton = Save

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/Baeldung"/>

View File

@ -0,0 +1,39 @@
<?xml version='1.0' encoding='UTF-8'?>
<!-- =========== FULL CONFIGURATION FILE ================================== -->
<faces-config version="2.1"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">
<application>
<resource-bundle>
<base-name>
messages
</base-name>
<var>
msg
</var>
</resource-bundle>
<resource-bundle>
<base-name>
constraints
</base-name>
<var>
constraints
</var>
</resource-bundle>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
<navigation-rule>
<from-view-id>/*</from-view-id>
<navigation-case>
<from-outcome>home</from-outcome>
<to-view-id>/index.xhtml</to-view-id>
<redirect/>
</navigation-case>
</navigation-rule>
</faces-config>

View File

@ -0,0 +1,28 @@
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title><h:outputText value="#{msg['message.welcome']}"/></title>
</h:head>
<h:body>
<h:form>
<h:panelGrid id="theGrid" columns="3">
<h:outputText value="Username"/>
<h:inputText id="firstName" binding="#{userName}" required="true" requiredMessage="#{msg['message.valueRequired']}"
value="#{registration.userName}"/>
<h:message for="firstName" style="color:red;"/>
<h:commandButton value="#{msg['label.saveButton']}" action="#{registration.createNewUser}"
process="@this"/>
<!--
Accessing the Spring bean directly from the page
<h:commandButton value="Save"
action="#{registration.userDao.createUser(userName.value)}"/>
-->
<h:outputText value="#{registration.operationMessage}" style="color:green;"/>
</h:panelGrid>
</h:form>
</h:body>
</html>

83
junit5/pom.xml Normal file
View File

@ -0,0 +1,83 @@
<?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>junit5</artifactId>
<version>1.0-SNAPSHOT</version>
<name>junit5</name>
<description>Intro to JUnit 5</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<!-- Due to a bug in surefire-junit5-5.0.0-ALPHA we use the latest snapshot instead -->
<junit.gen5.version>5.0.0-SNAPSHOT</junit.gen5.version>
</properties>
<repositories>
<repository>
<id>snapshots-repo</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<!-- Do NOT cache JUnit 5 snapshot JARs. -->
<updatePolicy>always</updatePolicy>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>snapshots-repo</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<!-- Do NOT cache JUnit 5 snapshot JARs. -->
<updatePolicy>always</updatePolicy>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19</version>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>surefire-junit5</artifactId>
<version>${junit.gen5.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit5-api</artifactId>
<version>${junit.gen5.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,30 @@
package com.baeldung;
import org.junit.gen5.api.Test;
import static org.junit.gen5.api.Assertions.assertEquals;
import static org.junit.gen5.api.Assumptions.*;
public class AssumptionTest {
@Test
void trueAssumption() {
assumeTrue(5 > 1);
assertEquals(5 + 2, 7);
}
@Test
void falseAssumption() {
assumeFalse(5 < 1);
assertEquals(5 + 2, 7);
}
@Test
void assumptionThat() {
String someString = "Just a string";
assumingThat(
someString.equals("Just a string"),
() -> assertEquals(2 + 2, 4)
);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung;
import org.junit.gen5.api.Test;
import static org.junit.gen5.api.Assertions.assertEquals;
import static org.junit.gen5.api.Assertions.expectThrows;
public class ExceptionTest {
@Test
void shouldThrowException() {
Throwable exception = expectThrows(UnsupportedOperationException.class,
() -> {
throw new UnsupportedOperationException("Not supported");
});
assertEquals(exception.getMessage(), "Not supported");
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung;
import org.junit.gen5.api.Disabled;
import org.junit.gen5.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.gen5.api.Assertions.*;
class FirstTest {
@Test
void lambdaExpressions() {
List<Integer> numbers = Arrays.asList(1, 2, 3);
assertTrue(numbers
.stream()
.mapToInt(i -> i)
.sum() > 5, "Sum should be greater than 5");
}
@Test
void groupAssertions() {
int[] numbers = {0, 1, 2, 3, 4};
assertAll("numbers",
() -> assertEquals(numbers[0], 1),
() -> assertEquals(numbers[3], 3),
() -> assertEquals(numbers[4], 1)
);
}
@Test
@Disabled
void disabledTest() {
assertTrue(false);
}
}

View File

@ -0,0 +1,77 @@
package com.baeldung;
import org.junit.gen5.api.*;
import java.util.EmptyStackException;
import java.util.Stack;
public class NestedTest {
Stack<Object> stack;
boolean isRun = false;
@Test
@DisplayName("is instantiated with new Stack()")
void isInstantiatedWithNew() {
new Stack<Object>();
}
@Nested
@DisplayName("when new")
class WhenNew {
@BeforeEach
void init() {
stack = new Stack<Object>();
}
@Test
@DisplayName("is empty")
void isEmpty() {
Assertions.assertTrue(stack.isEmpty());
}
@Test
@DisplayName("throws EmptyStackException when popped")
void throwsExceptionWhenPopped() {
Assertions.expectThrows(EmptyStackException.class, () -> stack.pop());
}
@Test
@DisplayName("throws EmptyStackException when peeked")
void throwsExceptionWhenPeeked() {
Assertions.expectThrows(EmptyStackException.class, () -> stack.peek());
}
@Nested
@DisplayName("after pushing an element")
class AfterPushing {
String anElement = "an element";
@BeforeEach
void init() {
stack.push(anElement);
}
@Test
@DisplayName("it is no longer empty")
void isEmpty() {
Assertions.assertFalse(stack.isEmpty());
}
@Test
@DisplayName("returns the element when popped and is empty")
void returnElementWhenPopped() {
Assertions.assertEquals(anElement, stack.pop());
Assertions.assertTrue(stack.isEmpty());
}
@Test
@DisplayName("returns the element when peeked but remains not empty")
void returnElementWhenPeeked() {
Assertions.assertEquals(anElement, stack.peek());
Assertions.assertFalse(stack.isEmpty());
}
}
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung;
import org.junit.gen5.api.Tag;
import org.junit.gen5.api.Test;
import static org.junit.gen5.api.Assertions.assertEquals;
@Tag("Test case")
public class TaggedTest {
@Test
@Tag("Method")
void testMethod() {
assertEquals(2 + 2, 4);
}
}

View File

@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="org.eclipse.wst.jsdt.core.javascriptValidator"/>
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
</launchConfiguration>

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,95 +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.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,55 +0,0 @@
#Sat Jan 21 23:04:06 EET 2012
eclipse.preferences.version=1
editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
sp_cleanup.add_default_serial_version_id=true
sp_cleanup.add_generated_serial_version_id=false
sp_cleanup.add_missing_annotations=true
sp_cleanup.add_missing_deprecated_annotations=true
sp_cleanup.add_missing_methods=false
sp_cleanup.add_missing_nls_tags=false
sp_cleanup.add_missing_override_annotations=true
sp_cleanup.add_missing_override_annotations_interface_methods=true
sp_cleanup.add_serial_version_id=false
sp_cleanup.always_use_blocks=true
sp_cleanup.always_use_parentheses_in_expressions=true
sp_cleanup.always_use_this_for_non_static_field_access=false
sp_cleanup.always_use_this_for_non_static_method_access=false
sp_cleanup.convert_to_enhanced_for_loop=true
sp_cleanup.correct_indentation=true
sp_cleanup.format_source_code=true
sp_cleanup.format_source_code_changes_only=true
sp_cleanup.make_local_variable_final=true
sp_cleanup.make_parameters_final=true
sp_cleanup.make_private_fields_final=false
sp_cleanup.make_type_abstract_if_missing_method=false
sp_cleanup.make_variable_declarations_final=true
sp_cleanup.never_use_blocks=false
sp_cleanup.never_use_parentheses_in_expressions=false
sp_cleanup.on_save_use_additional_actions=true
sp_cleanup.organize_imports=true
sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
sp_cleanup.qualify_static_member_accesses_with_declaring_class=true
sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
sp_cleanup.remove_private_constructors=true
sp_cleanup.remove_trailing_whitespaces=true
sp_cleanup.remove_trailing_whitespaces_all=true
sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
sp_cleanup.remove_unnecessary_casts=true
sp_cleanup.remove_unnecessary_nls_tags=false
sp_cleanup.remove_unused_imports=true
sp_cleanup.remove_unused_local_variables=false
sp_cleanup.remove_unused_private_fields=true
sp_cleanup.remove_unused_private_members=false
sp_cleanup.remove_unused_private_methods=true
sp_cleanup.remove_unused_private_types=true
sp_cleanup.sort_members=false
sp_cleanup.sort_members_all=false
sp_cleanup.use_blocks=false
sp_cleanup.use_blocks_only_for_return_and_throw=false
sp_cleanup.use_parentheses_in_expressions=false
sp_cleanup.use_this_for_non_static_field_access=true
sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
sp_cleanup.use_this_for_non_static_method_access=true
sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true

View File

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

View File

@ -1,2 +0,0 @@
eclipse.preferences.version=1
org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false

View File

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="spring-rest">
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<property name="context-root" value="spring-rest"/>
<property name="java-output-path" value="/spring-rest/target/classes"/>
</wb-module>
</project-modules>

View File

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

View File

@ -1 +0,0 @@
org.eclipse.wst.jsdt.launching.baseBrowserLibrary

View File

@ -1,14 +0,0 @@
DELEGATES_PREFERENCE=delegateValidatorList
USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator;
USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.303.v201202090300
eclipse.preferences.version=1
override=true
suspend=false
vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01
vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01
vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01
vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01
vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01
vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02
vf.version=3

View File

@ -1,2 +0,0 @@
eclipse.preferences.version=1
org.eclipse.wst.ws.service.policy.projectEnabled=false

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

@ -1,124 +1,143 @@
<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>mockito</artifactId>
<version>0.1-SNAPSHOT</version>
<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>mockito</artifactId>
<version>0.1-SNAPSHOT</version>
<name>mockito</name>
<name>mockito</name>
<dependencies>
<dependencies>
<!-- utils -->
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- web -->
<!-- web -->
<!-- test scoped -->
<!-- test scoped -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<build>
<finalName>mockito</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</dependencies>
<plugins>
<build>
<finalName>mockito</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
</build>
</plugins>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>
<mysql-connector-java.version>5.1.38</mysql-connector-java.version>
</build>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<properties>
<!-- Spring -->
<org.springframework.version>4.1.5.RELEASE</org.springframework.version>
<org.springframework.security.version>3.2.5.RELEASE</org.springframework.security.version>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<!-- persistence -->
<hibernate.version>4.3.10.Final</hibernate.version>
<mysql-connector-java.version>5.1.35</mysql-connector-java.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<!-- logging -->
<org.slf4j.version>1.7.13</org.slf4j.version>
<logback.version>1.1.3</logback.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<!-- various -->
<hibernate-validator.version>5.1.3.Final</hibernate-validator.version>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.4</commons-lang3.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<powermock.version>1.6.4</powermock.version>
<!-- maven plugins -->
<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.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.18</cargo-maven2-plugin.version>
<httpcore.version>4.4.1</httpcore.version>
<httpclient.version>4.5</httpclient.version>
</properties>
<rest-assured.version>2.4.1</rest-assured.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.3</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-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.14</cargo-maven2-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,20 @@
package com.baeldung.powermockito.introduction;
public class CollaboratorForPartialMocking {
public static String staticMethod() {
return "Hello Baeldung!";
}
public final String finalMethod() {
return "Hello Baeldung!";
}
private String privateMethod() {
return "Hello Baeldung!";
}
public String privateMethodCaller() {
return privateMethod() + " Welcome to the Java world.";
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.powermockito.introduction;
public class CollaboratorWithFinalMethods {
public final String helloMethod() {
return "Hello World!";
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.powermockito.introduction;
public class CollaboratorWithStaticMethods {
public static String firstMethod(String name) {
return "Hello " + name + " !";
}
public static String secondMethod() {
return "Hello no one!";
}
public static String thirdMethod() {
return "Hello no one again!";
}
}

View File

@ -0,0 +1,78 @@
package com.baeldung.powermockito.introduction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.*")
public class PowerMockitoTest {
@Test
public void givenFinalMethods_whenUsingPowerMockito_thenCorrect() throws Exception {
CollaboratorWithFinalMethods mock = mock(CollaboratorWithFinalMethods.class);
whenNew(CollaboratorWithFinalMethods.class).withNoArguments().thenReturn(mock);
CollaboratorWithFinalMethods collaborator = new CollaboratorWithFinalMethods();
verifyNew(CollaboratorWithFinalMethods.class).withNoArguments();
when(collaborator.helloMethod()).thenReturn("Hello Baeldung!");
String welcome = collaborator.helloMethod();
Mockito.verify(collaborator).helloMethod();
assertEquals("Hello Baeldung!", welcome);
}
@Test(expected = RuntimeException.class)
public void givenStaticMethods_whenUsingPowerMockito_thenCorrect() {
mockStatic(CollaboratorWithStaticMethods.class);
when(CollaboratorWithStaticMethods.firstMethod(Mockito.anyString())).thenReturn("Hello Baeldung!");
when(CollaboratorWithStaticMethods.secondMethod()).thenReturn("Nothing special");
doThrow(new RuntimeException()).when(CollaboratorWithStaticMethods.class);
CollaboratorWithStaticMethods.thirdMethod();
String firstWelcome = CollaboratorWithStaticMethods.firstMethod("Whoever");
String secondWelcome = CollaboratorWithStaticMethods.firstMethod("Whatever");
assertEquals("Hello Baeldung!", firstWelcome);
assertEquals("Hello Baeldung!", secondWelcome);
verifyStatic(Mockito.times(2));
CollaboratorWithStaticMethods.firstMethod(Mockito.anyString());
verifyStatic(Mockito.never());
CollaboratorWithStaticMethods.secondMethod();
CollaboratorWithStaticMethods.thirdMethod();
}
@Test
public void givenPartialMocking_whenUsingPowerMockito_thenCorrect() throws Exception {
String returnValue;
spy(CollaboratorForPartialMocking.class);
when(CollaboratorForPartialMocking.staticMethod()).thenReturn("I am a static mock method.");
returnValue = CollaboratorForPartialMocking.staticMethod();
verifyStatic();
CollaboratorForPartialMocking.staticMethod();
assertEquals("I am a static mock method.", returnValue);
CollaboratorForPartialMocking collaborator = new CollaboratorForPartialMocking();
CollaboratorForPartialMocking mock = spy(collaborator);
when(mock.finalMethod()).thenReturn("I am a final mock method.");
returnValue = mock.finalMethod();
Mockito.verify(mock).finalMethod();
assertEquals("I am a final mock method.", returnValue);
when(mock, "privateMethod").thenReturn("I am a private mock method.");
returnValue = mock.privateMethodCaller();
verifyPrivate(mock).invoke("privateMethod");
assertEquals("I am a private mock method. Welcome to the Java world.", returnValue);
}
}

View File

@ -1,20 +1,14 @@
package org.baeldung.mockito;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import org.mockito.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import static org.junit.Assert.assertEquals;
//@RunWith(MockitoJUnitRunner.class)
public class MockitoAnnotationTest {

View File

@ -1,20 +1,17 @@
package org.baeldung.mockito;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.mockito.Mockito.*;
public class MockitoConfigExamplesTest {

View File

@ -0,0 +1,69 @@
package org.baeldung.mockito;
import static org.mockito.Mockito.*;
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.containsString;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import org.junit.Test;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
import org.mockito.MockSettings;
import org.mockito.exceptions.verification.TooLittleActualInvocations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
public class MockitoMockTest {
private static class CustomAnswer implements Answer<Boolean> {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
return false;
}
}
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void whenUsingSimpleMock_thenCorrect() {
MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);
boolean added = listMock.add(randomAlphabetic(6));
verify(listMock).add(anyString());
assertThat(added, is(false));
}
@Test
public void whenUsingMockWithName_thenCorrect() {
MyList listMock = mock(MyList.class, "myMock");
when(listMock.add(anyString())).thenReturn(false);
listMock.add(randomAlphabetic(6));
thrown.expect(TooLittleActualInvocations.class);
thrown.expectMessage(containsString("myMock.add"));
verify(listMock, times(2)).add(anyString());
}
@Test
public void whenUsingMockWithAnswer_thenCorrect() {
MyList listMock = mock(MyList.class, new CustomAnswer());
boolean added = listMock.add(randomAlphabetic(6));
verify(listMock).add(anyString());
assertThat(added, is(false));
}
@Test
public void whenUsingMockWithSettings_thenCorrect() {
MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());
MyList listMock = mock(MyList.class, customSettings);
boolean added = listMock.add(randomAlphabetic(6));
verify(listMock).add(anyString());
assertThat(added, is(false));
}
}

View File

@ -1,16 +1,16 @@
package org.baeldung.mockito;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
@RunWith(MockitoJUnitRunner.class)
public class MockitoSpyTest {

View File

@ -1,26 +1,18 @@
package org.baeldung.mockito;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import java.util.List;
import com.google.common.collect.Lists;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.mockito.exceptions.verification.NoInteractionsWanted;
import com.google.common.collect.Lists;
import java.util.List;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.*;
public class MockitoVerifyExamplesTest {
@ -115,10 +107,10 @@ public class MockitoVerifyExamplesTest {
@Test
public final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
final List<String> mockedList = mock(MyList.class);
mockedList.addAll(Lists.<String> newArrayList("someElement"));
mockedList.addAll(Lists.<String>newArrayList("someElement"));
final ArgumentCaptor<List> argumentCaptor = ArgumentCaptor.forClass(List.class);
verify(mockedList).addAll(argumentCaptor.capture());
final List<String> capturedArgument = argumentCaptor.<List<String>> getValue();
final List<String> capturedArgument = argumentCaptor.<List<String>>getValue();
assertThat(capturedArgument, hasItem("someElement"));
}

View File

@ -4,6 +4,7 @@ import java.util.HashMap;
import java.util.Map;
public class MyDictionary {
Map<String, String> wordMap;
public MyDictionary() {

View File

@ -1,13 +0,0 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -64,6 +64,7 @@
<module>spring-security-rest-full</module>
<module>spring-thymeleaf</module>
<module>spring-zuul</module>
<module>jsf</module>
</modules>

View File

@ -2,23 +2,19 @@ package org.baeldung.caching.config;
import java.util.Arrays;
import org.baeldung.caching.example.CustomerDataService;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
@ComponentScan("org.baeldung.caching.example")
public class CachingConfig {
@Bean
public CustomerDataService customerDataService() {
return new CustomerDataService();
}
@Bean
public CacheManager cacheManager() {
final SimpleCacheManager cacheManager = new SimpleCacheManager();

View File

@ -0,0 +1,76 @@
package org.baeldung.caching.example;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
public abstract class AbstractService {
// this method configuration is equivalent to xml configuration
@Cacheable(value = "addresses", key = "#customer.name")
public String getAddress(final Customer customer) {
return customer.getAddress();
}
/**
* The method returns the customer's address,
only it doesn't find it the cache- addresses and directory.
*
* @param customer the customer
* @return the address
*/
@Cacheable({ "addresses", "directory" })
public String getAddress1(final Customer customer) {
return customer.getAddress();
}
/**
* The method returns the customer's address,
but refreshes all the entries in the cache to load new ones.
*
* @param customer the customer
* @return the address
*/
@CacheEvict(value = "addresses", allEntries = true)
public String getAddress2(final Customer customer) {
return customer.getAddress();
}
/**
* The method returns the customer's address,
but not before selectively evicting the cache as per specified paramters.
*
* @param customer the customer
* @return the address
*/
@Caching(evict = { @CacheEvict("addresses"), @CacheEvict(value = "directory", key = "#customer.name") })
public String getAddress3(final Customer customer) {
return customer.getAddress();
}
/**
* The method uses the class level cache to look up for entries.
*
* @param customer the customer
* @return the address
*/
@Cacheable
// parameter not required as we have declared it using @CacheConfig
public String getAddress4(final Customer customer) {
return customer.getAddress();
}
/**
* The method selectively caches the results that meet the predefined criteria.
*
* @param customer the customer
* @return the address
*/
@CachePut(value = "addresses", condition = "#customer.name=='Tom'")
// @CachePut(value = "addresses", unless = "#result.length>64")
public String getAddress5(final Customer customer) {
return customer.getAddress();
}
}

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