diff --git a/core-java-8/.project b/core-java-8/.project index 235c555abb..a23ff42ae0 100644 --- a/core-java-8/.project +++ b/core-java-8/.project @@ -1,15 +1,10 @@ - core-java-8 + core-java8 - - org.eclipse.jdt.core.javabuilder - - - org.eclipse.m2e.core.maven2Builder @@ -17,8 +12,6 @@ - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature diff --git a/core-java-8/.settings/.jsdtscope b/core-java-8/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/core-java-8/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/core-java-8/.settings/org.eclipse.jdt.core.prefs b/core-java-8/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index c38ccc1294..0000000000 --- a/core-java-8/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,101 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled -org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore -org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull -org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault -org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable -org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.autoboxing=ignore -org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning -org.eclipse.jdt.core.compiler.problem.deadCode=warning -org.eclipse.jdt.core.compiler.problem.deprecation=warning -org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled -org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled -org.eclipse.jdt.core.compiler.problem.discouragedReference=warning -org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore -org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore -org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled -org.eclipse.jdt.core.compiler.problem.fieldHiding=warning -org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning -org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning -org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled -org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning -org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore -org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning -org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning -org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore -org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled -org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore -org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled -org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning -org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore -org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning -org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning -org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore -org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning -org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error -org.eclipse.jdt.core.compiler.problem.nullReference=warning -org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error -org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning -org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning -org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore -org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore -org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning -org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning -org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore -org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore -org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore -org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore -org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled -org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning -org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled -org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled -org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled -org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore -org.eclipse.jdt.core.compiler.problem.typeParameterHiding=error -org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled -org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning -org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning -org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore -org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning -org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore -org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore -org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled -org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedImport=warning -org.eclipse.jdt.core.compiler.problem.unusedLabel=warning -org.eclipse.jdt.core.compiler.problem.unusedLocal=warning -org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled -org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled -org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning -org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore -org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning -org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/core-java-8/.settings/org.eclipse.jdt.ui.prefs b/core-java-8/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index d84d2a7f8c..0000000000 --- a/core-java-8/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,57 +0,0 @@ -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=true -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_functional_interfaces=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=true -sp_cleanup.make_local_variable_final=true -sp_cleanup.make_parameters_final=true -sp_cleanup.make_private_fields_final=false -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=false -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_anonymous_class_creation=false -sp_cleanup.use_blocks=true -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_lambda=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=true -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/core-java-8/.settings/org.eclipse.m2e.core.prefs b/core-java-8/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/core-java-8/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/core-java-8/.springBeans b/core-java-8/.springBeans deleted file mode 100644 index a79097f40d..0000000000 --- a/core-java-8/.springBeans +++ /dev/null @@ -1,14 +0,0 @@ - - - 1 - - - - - - - src/main/webapp/WEB-INF/api-servlet.xml - - - - diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml index bc1e402b4d..0e589ebf47 100644 --- a/core-java-8/pom.xml +++ b/core-java-8/pom.xml @@ -1,4 +1,5 @@ - + 4.0.0 com.baeldung core-java8 diff --git a/core-java-8/src/main/java/com/baeldung/enums/Pizza.java b/core-java-8/src/main/java/com/baeldung/enums/Pizza.java new file mode 100644 index 0000000000..5bc2d9a9eb --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/enums/Pizza.java @@ -0,0 +1,91 @@ +package com.baeldung.enums; + +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.List; +import java.util.stream.Collectors; + +public class Pizza { + + private static EnumSet deliveredPizzaStatuses = + EnumSet.of(PizzaStatusEnum.DELIVERED); + + private PizzaStatusEnum status; + + public enum PizzaStatusEnum { + ORDERED(5) { + @Override + public boolean isOrdered() { + return true; + } + }, + READY(2) { + @Override + public boolean isReady() { + return true; + } + }, + DELIVERED(0) { + @Override + public boolean isDelivered() { + return true; + } + }; + + private int timeToDelivery; + + public boolean isOrdered() { + return false; + } + + public boolean isReady() { + return false; + } + + public boolean isDelivered() { + return false; + } + + public int getTimeToDelivery() { + return timeToDelivery; + } + + PizzaStatusEnum(int timeToDelivery) { + this.timeToDelivery = timeToDelivery; + } + } + + public PizzaStatusEnum getStatus() { + return status; + } + + public void setStatus(PizzaStatusEnum status) { + this.status = status; + } + + public boolean isDeliverable() { + return this.status.isReady(); + } + + public void printTimeToDeliver() { + System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days"); + } + + public static List getAllUndeliveredPizzas(List input) { + return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList()); + } + + public static EnumMap> groupPizzaByStatus(List pzList) { + return pzList.stream().collect( + Collectors.groupingBy(Pizza::getStatus, + () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList())); + } + + public void deliver() { + if (isDeliverable()) { + PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this); + this.setStatus(PizzaStatusEnum.DELIVERED); + } + } + +} \ No newline at end of file diff --git a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java new file mode 100644 index 0000000000..ed65919387 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java @@ -0,0 +1,18 @@ +package com.baeldung.enums; + +public enum PizzaDeliveryStrategy { + EXPRESS { + @Override + public void deliver(Pizza pz) { + System.out.println("Pizza will be delivered in express mode"); + } + }, + NORMAL { + @Override + public void deliver(Pizza pz) { + System.out.println("Pizza will be delivered in normal mode"); + } + }; + + public abstract void deliver(Pizza pz); +} diff --git a/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java new file mode 100644 index 0000000000..5ccff5e959 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java @@ -0,0 +1,22 @@ +package com.baeldung.enums; + + +public enum PizzaDeliverySystemConfiguration { + INSTANCE; + + PizzaDeliverySystemConfiguration() { + // Do the configuration initialization which + // involves overriding defaults like delivery strategy + } + + private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL; + + public static PizzaDeliverySystemConfiguration getInstance() { + return INSTANCE; + } + + public PizzaDeliveryStrategy getDeliveryStrategy() { + return deliveryStrategy; + } + +} diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java b/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java new file mode 100644 index 0000000000..f1ab2d8d09 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveAction.java @@ -0,0 +1,49 @@ +package com.baeldung.forkjoin; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.RecursiveAction; +import java.util.logging.Logger; + +public class CustomRecursiveAction extends RecursiveAction { + + private String workLoad = ""; + private static final int THRESHOLD = 4; + + private static Logger logger = Logger.getAnonymousLogger(); + + public CustomRecursiveAction(String workLoad) { + this.workLoad = workLoad; + } + + @Override + protected void compute() { + + if (workLoad.length() > THRESHOLD) { + ForkJoinTask.invokeAll(createSubtasks()); + } else { + processing(workLoad); + } + } + + private Collection createSubtasks() { + + List subtasks = + new ArrayList<>(); + + String partOne = workLoad.substring(0, workLoad.length() / 2); + String partTwo = workLoad.substring(workLoad.length() / 2, workLoad.length()); + + subtasks.add(new CustomRecursiveAction(partOne)); + subtasks.add(new CustomRecursiveAction(partTwo)); + + return subtasks; + } + + private void processing(String work) { + String result = work.toUpperCase(); + logger.info("This result - (" + result + ") - was processed by " + Thread.currentThread().getName()); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java b/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java new file mode 100644 index 0000000000..5d4d97b805 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/forkjoin/CustomRecursiveTask.java @@ -0,0 +1,51 @@ +package com.baeldung.forkjoin; + + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.RecursiveTask; + +public class CustomRecursiveTask extends RecursiveTask { + + private int[] arr; + + private static final int THRESHOLD = 20; + + public CustomRecursiveTask(int[] arr) { + this.arr = arr; + } + + @Override + protected Integer compute() { + + if (arr.length > THRESHOLD) { + + return ForkJoinTask.invokeAll(createSubtasks()) + .stream() + .mapToInt(ForkJoinTask::join) + .sum(); + + } else { + return processing(arr); + } + } + + private Collection createSubtasks() { + List dividedTasks = new ArrayList<>(); + dividedTasks.add(new CustomRecursiveTask( + Arrays.copyOfRange(arr, 0, arr.length / 2))); + dividedTasks.add(new CustomRecursiveTask( + Arrays.copyOfRange(arr, arr.length / 2, arr.length))); + return dividedTasks; + } + + private Integer processing(int[] arr) { + return Arrays.stream(arr) + .filter(a -> a > 10 && a < 27) + .map(a -> a * 10) + .sum(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java b/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java new file mode 100644 index 0000000000..521616600f --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/forkjoin/util/PoolUtil.java @@ -0,0 +1,10 @@ +package com.baeldung.forkjoin.util; + + +import java.util.concurrent.ForkJoinPool; + +public class PoolUtil { + + public static ForkJoinPool forkJoinPool = new ForkJoinPool(2); + +} diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java b/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java new file mode 100644 index 0000000000..1f89503288 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java @@ -0,0 +1,14 @@ +package com.baeldung.java_8_features; + +public class Address { + + private String street; + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java b/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java new file mode 100644 index 0000000000..ff9be6ab06 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java @@ -0,0 +1,4 @@ +package com.baeldung.java_8_features; + +public class CustomException extends RuntimeException { +} diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java b/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java new file mode 100644 index 0000000000..811937dba7 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/java_8_features/Detail.java @@ -0,0 +1,13 @@ +package com.baeldung.java_8_features; + +import java.util.Arrays; +import java.util.List; + +public class Detail { + + private static final List PARTS = Arrays.asList("turbine", "pump"); + + public List getParts() { + return PARTS; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java b/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java new file mode 100644 index 0000000000..8d6c517ac5 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java @@ -0,0 +1,16 @@ +package com.baeldung.java_8_features; + +import java.util.Optional; + +public class OptionalAddress { + + private String street; + + public Optional getStreet() { + return Optional.ofNullable(street); + } + + public void setStreet(String street) { + this.street = street; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java b/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java new file mode 100644 index 0000000000..ff06cd21d6 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java @@ -0,0 +1,16 @@ +package com.baeldung.java_8_features; + +import java.util.Optional; + +public class OptionalUser { + + private OptionalAddress address; + + public Optional getAddress() { + return Optional.of(address); + } + + public void setAddress(OptionalAddress address) { + this.address = address; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/User.java b/core-java-8/src/main/java/com/baeldung/java_8_features/User.java new file mode 100644 index 0000000000..3708d276c8 --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/java_8_features/User.java @@ -0,0 +1,40 @@ +package com.baeldung.java_8_features; + +import java.util.Optional; + +public class User { + + private String name; + + private Address address; + + public Address getAddress() { + return address; + } + + public void setAddress(Address address) { + this.address = address; + } + + public User() { + } + + public User(String name) { + this.name = name; + } + + public static boolean isRealUser(User user) { + return true; + } + + public String getOrThrow() { + String value = null; + Optional valueOpt = Optional.ofNullable(value); + String result = valueOpt.orElseThrow(CustomException::new).toUpperCase(); + return result; + } + + public boolean isLegalName(String name) { + return name.length() > 3 && name.length() < 16; + } +} diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java b/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java new file mode 100644 index 0000000000..011173bcaf --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java @@ -0,0 +1,18 @@ +package com.baeldung.java_8_features; + +public interface Vehicle { + + void moveTo(long altitude, long longitude); + + static String producer() { + return "N&F Vehicles"; + } + + default long[] startPosition() { + return new long[]{23, 15}; + } + + default String getOverview() { + return "ATV made by " + producer(); + } +} diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java b/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java new file mode 100644 index 0000000000..83e55f5f4d --- /dev/null +++ b/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java @@ -0,0 +1,9 @@ +package com.baeldung.java_8_features; + +public class VehicleImpl implements Vehicle { + + @Override + public void moveTo(long altitude, long longitude) { + //do nothing + } +} diff --git a/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java index 813d8f20f8..6648d5f926 100644 --- a/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java +++ b/core-java-8/src/main/java/com/baeldung/unzip/UnzipFile.java @@ -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); diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java index af80ec9609..f9ccac9713 100644 --- a/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java +++ b/core-java-8/src/main/java/com/baeldung/zip/ZipFile.java @@ -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(); diff --git a/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java b/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java index 211696195d..fc86147e43 100644 --- a/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java +++ b/core-java-8/src/main/java/com/baeldung/zip/ZipMultipleFiles.java @@ -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(); diff --git a/core-java-8/src/main/resources/logback.xml b/core-java-8/src/main/resources/logback.xml index 62d0ea5037..eefdc7a337 100644 --- a/core-java-8/src/main/resources/logback.xml +++ b/core-java-8/src/main/resources/logback.xml @@ -10,7 +10,7 @@ - + \ No newline at end of file diff --git a/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java b/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java index 5ae6f02a56..85194f5aa6 100644 --- a/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java +++ b/core-java-8/src/test/java/com/baeldung/doublecolon/TestComputerUtils.java @@ -6,7 +6,9 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.util.*; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; import java.util.function.BiFunction; import static com.baeldung.doublecolon.ComputerUtils.*; diff --git a/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java b/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java new file mode 100644 index 0000000000..deeebaa240 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/enums/PizzaTest.java @@ -0,0 +1,80 @@ +package com.baeldung.enums; + + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; + +import static junit.framework.TestCase.assertTrue; + +public class PizzaTest { + + @Test + public void givenPizaOrder_whenReady_thenDeliverable() { + Pizza testPz = new Pizza(); + testPz.setStatus(Pizza.PizzaStatusEnum.READY); + assertTrue(testPz.isDeliverable()); + } + + @Test + public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() { + List pzList = new ArrayList<>(); + Pizza pz1 = new Pizza(); + pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); + + Pizza pz2 = new Pizza(); + pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); + + Pizza pz3 = new Pizza(); + pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); + + Pizza pz4 = new Pizza(); + pz4.setStatus(Pizza.PizzaStatusEnum.READY); + + pzList.add(pz1); + pzList.add(pz2); + pzList.add(pz3); + pzList.add(pz4); + + List undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList); + assertTrue(undeliveredPzs.size() == 3); + } + + @Test + public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() { + + List pzList = new ArrayList<>(); + Pizza pz1 = new Pizza(); + pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); + + Pizza pz2 = new Pizza(); + pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); + + Pizza pz3 = new Pizza(); + pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); + + Pizza pz4 = new Pizza(); + pz4.setStatus(Pizza.PizzaStatusEnum.READY); + + pzList.add(pz1); + pzList.add(pz2); + pzList.add(pz3); + pzList.add(pz4); + + EnumMap> map = Pizza.groupPizzaByStatus(pzList); + assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1); + assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2); + assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1); + } + + @Test + public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() { + Pizza pz = new Pizza(); + pz.setStatus(Pizza.PizzaStatusEnum.READY); + pz.deliver(); + assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED); + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java index 9c248ad8ce..ef4b80c6e8 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8CollectionCleanupUnitTest.java @@ -1,14 +1,13 @@ package com.baeldung.java8; -import static org.hamcrest.Matchers.hasSize; -import static org.junit.Assert.assertThat; +import com.google.common.collect.Lists; +import org.junit.Test; import java.util.List; import java.util.stream.Collectors; -import org.junit.Test; - -import com.google.common.collect.Lists; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; public class Java8CollectionCleanupUnitTest { diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java new file mode 100644 index 0000000000..21a5e34b9b --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsTest.java @@ -0,0 +1,27 @@ +package com.baeldung.java8; + +import com.baeldung.java_8_features.Vehicle; +import com.baeldung.java_8_features.VehicleImpl; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class Java8DefaultStaticIntefaceMethodsTest { + + @Test + public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() { + Vehicle vehicle = new VehicleImpl(); + String overview = vehicle.getOverview(); + long[] startPosition = vehicle.startPosition(); + + assertEquals(overview, "ATV made by N&F Vehicles"); + assertEquals(startPosition[0], 23); + assertEquals(startPosition[1], 15); + } + + @Test + public void callDefaultInterfaceMethods_whenExpectedResults_thenCorrect() { + String producer = Vehicle.producer(); + assertEquals(producer, "N&F Vehicles"); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java index 1609ae98a4..581ccec182 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8ExecutorServiceTest.java @@ -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); diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java new file mode 100644 index 0000000000..273b2d78db --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8ForkJoinTest.java @@ -0,0 +1,100 @@ +package com.baeldung.java8; + + +import com.baeldung.forkjoin.CustomRecursiveAction; +import com.baeldung.forkjoin.CustomRecursiveTask; +import com.baeldung.forkjoin.util.PoolUtil; +import org.junit.Before; +import org.junit.Test; + +import java.util.Random; +import java.util.concurrent.ForkJoinPool; + +import static org.junit.Assert.*; + +public class Java8ForkJoinTest { + + private int[] arr; + private CustomRecursiveTask customRecursiveTask; + + @Before + public void init() { + Random random = new Random(); + arr = new int[50]; + for (int i = 0; i < arr.length; i++) { + arr[i] = random.nextInt(35); + } + customRecursiveTask = new CustomRecursiveTask(arr); + } + + + @Test + public void callPoolUtil_whenExistsAndExpectedType_thenCorrect() { + + ForkJoinPool forkJoinPool = PoolUtil.forkJoinPool; + ForkJoinPool forkJoinPoolTwo = PoolUtil.forkJoinPool; + + assertNotNull(forkJoinPool); + assertEquals(2, forkJoinPool.getParallelism()); + assertEquals(forkJoinPool, forkJoinPoolTwo); + + } + + @Test + public void callCommonPool_whenExistsAndExpectedType_thenCorrect() { + + ForkJoinPool commonPool = ForkJoinPool.commonPool(); + ForkJoinPool commonPoolTwo = ForkJoinPool.commonPool(); + + assertNotNull(commonPool); + assertEquals(commonPool, commonPoolTwo); + + } + + @Test + public void executeRecursiveAction_whenExecuted_thenCorrect() { + + CustomRecursiveAction myRecursiveAction = new CustomRecursiveAction("ddddffffgggghhhh"); + ForkJoinPool.commonPool().invoke(myRecursiveAction); + + assertTrue(myRecursiveAction.isDone()); + + } + + @Test + public void executeRecursiveTask_whenExecuted_thenCorrect() { + + ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); + + forkJoinPool.execute(customRecursiveTask); + int result = customRecursiveTask.join(); + assertTrue(customRecursiveTask.isDone()); + + forkJoinPool.submit(customRecursiveTask); + int resultTwo = customRecursiveTask.join(); + assertTrue(customRecursiveTask.isDone()); + + } + + @Test + public void executeRecursiveTaskWithFJ_whenExecuted_thenCorrect() { + + CustomRecursiveTask customRecursiveTaskFirst = new CustomRecursiveTask(arr); + CustomRecursiveTask customRecursiveTaskSecond = new CustomRecursiveTask(arr); + CustomRecursiveTask customRecursiveTaskLast = new CustomRecursiveTask(arr); + + customRecursiveTaskFirst.fork(); + customRecursiveTaskSecond.fork(); + customRecursiveTaskLast.fork(); + int result = 0; + result += customRecursiveTaskLast.join(); + result += customRecursiveTaskSecond.join(); + result += customRecursiveTaskFirst.join(); + + assertTrue(customRecursiveTaskFirst.isDone()); + assertTrue(customRecursiveTaskSecond.isDone()); + assertTrue(customRecursiveTaskLast.isDone()); + assertTrue(result != 0); + + } +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java index 94448fcc83..faaf3ae407 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasTest.java @@ -1,16 +1,15 @@ package com.baeldung.java8; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -import java.util.function.Function; - -import org.junit.Before; -import org.junit.Test; - import com.baeldung.Foo; import com.baeldung.FooExtended; import com.baeldung.UseFoo; +import org.junit.Before; +import org.junit.Test; + +import java.util.function.Function; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; public class Java8FunctionalInteracesLambdasTest { diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java new file mode 100644 index 0000000000..d9d88c5052 --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceTest.java @@ -0,0 +1,67 @@ +package com.baeldung.java8; + +import com.baeldung.java_8_features.User; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class Java8MethodReferenceTest { + + private List list; + + @Before + public void init() { + list = new ArrayList<>(); + list.add("One"); + list.add("OneAndOnly"); + list.add("Derek"); + list.add("Change"); + list.add("factory"); + list.add("justBefore"); + list.add("Italy"); + list.add("Italy"); + list.add("Thursday"); + list.add(""); + list.add(""); + } + + @Test + public void checkStaticMethodReferences_whenWork_thenCorrect() { + + List users = new ArrayList<>(); + users.add(new User()); + users.add(new User()); + boolean isReal = users.stream().anyMatch(u -> User.isRealUser(u)); + boolean isRealRef = users.stream().anyMatch(User::isRealUser); + assertTrue(isReal); + assertTrue(isRealRef); + } + + @Test + public void checkInstanceMethodReferences_whenWork_thenCorrect() { + User user = new User(); + boolean isLegalName = list.stream().anyMatch(user::isLegalName); + assertTrue(isLegalName); + } + + @Test + public void checkParticularTypeReferences_whenWork_thenCorrect() { + long count = list.stream().filter(String::isEmpty).count(); + assertEquals(count, 2); + } + + @Test + public void checkConstructorReferences_whenWork_thenCorrect() { + Stream stream = list.stream().map(User::new); + List userList = stream.collect(Collectors.toList()); + assertEquals(userList.size(), list.size()); + assertTrue(userList.get(0) instanceof User); + } +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java new file mode 100644 index 0000000000..26de39bc0e --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalTest.java @@ -0,0 +1,118 @@ +package com.baeldung.java8; + +import com.baeldung.java_8_features.*; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.*; + +public class Java8OptionalTest { + + private List list; + + @Before + public void init() { + list = new ArrayList<>(); + list.add("One"); + list.add("OneAndOnly"); + list.add("Derek"); + list.add("Change"); + list.add("factory"); + list.add("justBefore"); + list.add("Italy"); + list.add("Italy"); + list.add("Thursday"); + list.add(""); + list.add(""); + } + + @Test + public void checkOptional_whenAsExpected_thenCorrect() { + + Optional optionalEmpty = Optional.empty(); + assertFalse(optionalEmpty.isPresent()); + + String str = "value"; + Optional optional = Optional.of(str); + assertEquals(optional.get(), "value"); + + Optional optionalNullable = Optional.ofNullable(str); + Optional optionalNull = Optional.ofNullable(null); + assertEquals(optionalNullable.get(), "value"); + assertFalse(optionalNull.isPresent()); + + List listOpt = Optional.of(list).orElse(new ArrayList<>()); + List listNull = null; + List listOptNull = Optional.ofNullable(listNull).orElse(new ArrayList<>()); + assertTrue(listOpt == list); + assertTrue(listOptNull.isEmpty()); + + Optional user = Optional.ofNullable(getUser()); + String result = user.map(User::getAddress) + .map(Address::getStreet) + .orElse("not specified"); + assertEquals(result, "1st Avenue"); + + Optional optionalUser = Optional.ofNullable(getOptionalUser()); + String resultOpt = optionalUser.flatMap(OptionalUser::getAddress) + .flatMap(OptionalAddress::getStreet) + .orElse("not specified"); + assertEquals(resultOpt, "1st Avenue"); + + Optional userNull = Optional.ofNullable(getUserNull()); + String resultNull = userNull.map(User::getAddress) + .map(Address::getStreet) + .orElse("not specified"); + assertEquals(resultNull, "not specified"); + + Optional optionalUserNull = Optional.ofNullable(getOptionalUserNull()); + String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress) + .flatMap(OptionalAddress::getStreet) + .orElse("not specified"); + assertEquals(resultOptNull, "not specified"); + + } + + @Test(expected = CustomException.class) + public void callMethod_whenCustomException_thenCorrect() { + User user = new User(); + String result = user.getOrThrow(); + } + + private User getUser() { + User user = new User(); + Address address = new Address(); + address.setStreet("1st Avenue"); + user.setAddress(address); + return user; + } + + private OptionalUser getOptionalUser() { + OptionalUser user = new OptionalUser(); + OptionalAddress address = new OptionalAddress(); + address.setStreet("1st Avenue"); + user.setAddress(address); + return user; + } + + private OptionalUser getOptionalUserNull() { + OptionalUser user = new OptionalUser(); + OptionalAddress address = new OptionalAddress(); + address.setStreet(null); + user.setAddress(address); + return user; + } + + private User getUserNull() { + User user = new User(); + Address address = new Address(); + address.setStreet(null); + user.setAddress(address); + return user; + } + +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java index 2ba9e417d6..f371c0d7da 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java @@ -1,17 +1,16 @@ package com.baeldung.java8; -import static org.hamcrest.Matchers.equalTo; +import com.baeldung.java8.entity.Human; +import com.google.common.collect.Lists; +import com.google.common.primitives.Ints; +import org.junit.Assert; +import org.junit.Test; import java.util.Collections; import java.util.Comparator; import java.util.List; -import org.junit.Assert; -import org.junit.Test; - -import com.baeldung.java8.entity.Human; -import com.google.common.collect.Lists; -import com.google.common.primitives.Ints; +import static org.hamcrest.Matchers.equalTo; public class Java8SortUnitTest { diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java new file mode 100644 index 0000000000..1f1dda49ce --- /dev/null +++ b/core-java-8/src/test/java/com/baeldung/java8/Java8StreamsTest.java @@ -0,0 +1,113 @@ +package com.baeldung.java8; + +import com.baeldung.java_8_features.Detail; +import org.junit.Before; +import org.junit.Test; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.*; + +public class Java8StreamsTest { + + private List list; + + @Before + public void init() { + list = new ArrayList<>(); + list.add("One"); + list.add("OneAndOnly"); + list.add("Derek"); + list.add("Change"); + list.add("factory"); + list.add("justBefore"); + list.add("Italy"); + list.add("Italy"); + list.add("Thursday"); + list.add(""); + list.add(""); + } + + @Test + public void checkStreamCount_whenCreating_givenDifferentSources() { + String[] arr = new String[]{"a", "b", "c"}; + Stream streamArr = Arrays.stream(arr); + assertEquals(streamArr.count(), 3); + + Stream streamOf = Stream.of("a", "b", "c"); + assertEquals(streamOf.count(), 3); + + long count = list.stream().distinct().count(); + assertEquals(count, 9); + } + + + @Test + public void checkStreamCount_whenOperationFilter_thanCorrect() { + Stream streamFilter = list.stream().filter(element -> element.isEmpty()); + assertEquals(streamFilter.count(), 2); + } + + + @Test + public void checkStreamCount_whenOperationMap_thanCorrect() { + List uris = new ArrayList<>(); + uris.add("C:\\My.txt"); + Stream streamMap = uris.stream().map(uri -> Paths.get(uri)); + assertEquals(streamMap.count(), 1); + + List details = new ArrayList<>(); + details.add(new Detail()); + details.add(new Detail()); + Stream streamFlatMap = details.stream() + .flatMap(detail -> detail.getParts().stream()); + assertEquals(streamFlatMap.count(), 4); + } + + + @Test + public void checkStreamCount_whenOperationMatch_thenCorrect() { + boolean isValid = list.stream().anyMatch(element -> element.contains("h")); + boolean isValidOne = list.stream().allMatch(element -> element.contains("h")); + boolean isValidTwo = list.stream().noneMatch(element -> element.contains("h")); + assertTrue(isValid); + assertFalse(isValidOne); + assertFalse(isValidTwo); + } + + + @Test + public void checkStreamReducedValue_whenOperationReduce_thenCorrect() { + List integers = new ArrayList<>(); + integers.add(1); + integers.add(1); + integers.add(1); + Integer reduced = integers.stream().reduce(23, (a, b) -> a + b); + assertTrue(reduced == 26); + } + + @Test + public void checkStreamContains_whenOperationCollect_thenCorrect() { + List resultList = list.stream() + .map(element -> element.toUpperCase()) + .collect(Collectors.toList()); + assertEquals(resultList.size(), list.size()); + assertTrue(resultList.contains("")); + } + + + @Test + public void checkParallelStream_whenDoWork() { + list.parallelStream().forEach(element -> doWork(element)); + } + + private void doWork(String string) { + assertTrue(true); //just imitate an amount of work + } +} diff --git a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java index 2ac16b5d1d..efd548a4b1 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/JavaFolderSizeTest.java @@ -1,22 +1,18 @@ package com.baeldung.java8; -import static org.junit.Assert.assertEquals; +import org.apache.commons.io.FileUtils; +import org.junit.Before; +import org.junit.Test; import java.io.File; import java.io.IOException; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; +import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.text.DecimalFormat; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.StreamSupport; -import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class JavaFolderSizeTest { @@ -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); diff --git a/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java b/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java index 18110b181d..224c4e9d6a 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesTest.java @@ -1,13 +1,13 @@ package com.baeldung.java8; +import org.junit.Assert; +import org.junit.Test; + import java.io.PrintWriter; import java.io.StringWriter; import java.util.Date; import java.util.Scanner; -import org.junit.Assert; -import org.junit.Test; - public class JavaTryWithResourcesTest { private static final String TEST_STRING_HELLO_WORLD = "Hello World"; diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java b/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java index 07380cdd01..164a571817 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/base64/ApacheCommonsEncodeDecodeTest.java @@ -1,14 +1,12 @@ package com.baeldung.java8.base64; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; - -import java.io.UnsupportedEncodingException; - import org.apache.commons.codec.binary.Base64; import org.junit.Test; +import java.io.UnsupportedEncodingException; + +import static org.junit.Assert.*; + public class ApacheCommonsEncodeDecodeTest { // tests diff --git a/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java b/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java index 3c504edbf3..18dccf71ba 100644 --- a/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java +++ b/core-java-8/src/test/java/com/baeldung/java8/base64/Java8EncodeDecodeTest.java @@ -1,14 +1,12 @@ package com.baeldung.java8.base64; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.Test; import java.io.UnsupportedEncodingException; import java.util.Base64; import java.util.UUID; -import org.junit.Test; +import static org.junit.Assert.*; public class Java8EncodeDecodeTest { diff --git a/core-java/pom.xml b/core-java/pom.xml index e3a9043b09..39cb79a86a 100644 --- a/core-java/pom.xml +++ b/core-java/pom.xml @@ -9,7 +9,11 @@ - + + net.sourceforge.collections + collections-generic + 4.01 + com.google.guava guava diff --git a/core-java/src/main/java/com/baeldung/enums/Pizza.java b/core-java/src/main/java/com/baeldung/enums/Pizza.java new file mode 100644 index 0000000000..b1c90b42cf --- /dev/null +++ b/core-java/src/main/java/com/baeldung/enums/Pizza.java @@ -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 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 getAllUndeliveredPizza(List input) { + List undelivered = input; + CollectionUtils.filter(undelivered, thatAreNotDelivered()); + return undelivered; + } + + public static EnumMap> groupPizzaByStatus(List pizzaList) { + EnumMap> pzByStatus = new EnumMap>(PizzaStatusEnum.class); + for (Pizza pz : pizzaList) { + PizzaStatusEnum status = pz.getStatus(); + + if (pzByStatus.containsKey(status)) { + pzByStatus.get(status).add(pz); + } else { + List newPzList = new ArrayList(); + 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 thatAreNotDelivered() { + return new Predicate() { + public boolean evaluate(Pizza entry) { + return undeliveredPizzaStatuses.contains(entry.getStatus()); + } + }; + } +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java b/core-java/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java new file mode 100644 index 0000000000..ed65919387 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/enums/PizzaDeliveryStrategy.java @@ -0,0 +1,18 @@ +package com.baeldung.enums; + +public enum PizzaDeliveryStrategy { + EXPRESS { + @Override + public void deliver(Pizza pz) { + System.out.println("Pizza will be delivered in express mode"); + } + }, + NORMAL { + @Override + public void deliver(Pizza pz) { + System.out.println("Pizza will be delivered in normal mode"); + } + }; + + public abstract void deliver(Pizza pz); +} diff --git a/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java b/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java new file mode 100644 index 0000000000..9210945783 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/enums/PizzaDeliverySystemConfiguration.java @@ -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; + } + +} diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java new file mode 100644 index 0000000000..9f6a8feae5 --- /dev/null +++ b/core-java/src/test/java/org/baeldung/java/enums/PizzaTest.java @@ -0,0 +1,80 @@ +package org.baeldung.java.enums; + + +import com.baeldung.enums.Pizza; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; + +import static junit.framework.TestCase.assertTrue; + + +public class PizzaTest { + @Test + public void givenPizaOrder_whenReady_thenDeliverable() { + Pizza testPz = new Pizza(); + testPz.setStatus(Pizza.PizzaStatusEnum.READY); + assertTrue(testPz.isDeliverable()); + } + + @Test + public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() { + List pzList = new ArrayList(); + Pizza pz1 = new Pizza(); + pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); + + Pizza pz2 = new Pizza(); + pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); + + Pizza pz3 = new Pizza(); + pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); + + Pizza pz4 = new Pizza(); + pz4.setStatus(Pizza.PizzaStatusEnum.READY); + + pzList.add(pz1); + pzList.add(pz2); + pzList.add(pz3); + pzList.add(pz4); + + List undeliveredPzs = Pizza.getAllUndeliveredPizza(pzList); + assertTrue(undeliveredPzs.size() == 3); + } + + @Test + public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() { + + List pzList = new ArrayList(); + Pizza pz1 = new Pizza(); + pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED); + + Pizza pz2 = new Pizza(); + pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED); + + Pizza pz3 = new Pizza(); + pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED); + + Pizza pz4 = new Pizza(); + pz4.setStatus(Pizza.PizzaStatusEnum.READY); + + pzList.add(pz1); + pzList.add(pz2); + pzList.add(pz3); + pzList.add(pz4); + + EnumMap> map = Pizza.groupPizzaByStatus(pzList); + assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1); + assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2); + assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1); + } + + @Test + public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() { + Pizza pz = new Pizza(); + pz.setStatus(Pizza.PizzaStatusEnum.READY); + pz.deliver(); + assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED); + } +} diff --git a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java b/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java index c139e34afb..24213ba869 100644 --- a/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java +++ b/core-java/src/test/java/org/baeldung/java/io/JavaFileIntegrationTest.java @@ -1,5 +1,6 @@ package org.baeldung.java.io; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.junit.Assert.assertTrue; import java.io.File; @@ -57,9 +58,8 @@ public class JavaFileIntegrationTest { @Test public final void givenUsingJDK7Nio2_whenMovingFile_thenCorrect() throws IOException { - final Path fileToMovePath = Files.createFile(Paths.get("src/test/resources/fileToMove.txt")); - final Path dirPath = Paths.get("src/test/resources/"); - final Path targetPath = Files.createDirectory(dirPath); + final Path fileToMovePath = Files.createFile(Paths.get("src/test/resources/" + randomAlphabetic(5) + ".txt")); + final Path targetPath = Paths.get("src/main/resources/"); Files.move(fileToMovePath, targetPath.resolve(fileToMovePath.getFileName())); } diff --git a/guava18/.project b/guava18/.project new file mode 100644 index 0000000000..11dff52392 --- /dev/null +++ b/guava18/.project @@ -0,0 +1,17 @@ + + + guava18 + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/guava19/.project b/guava19/.project new file mode 100644 index 0000000000..b4c292ad2c --- /dev/null +++ b/guava19/.project @@ -0,0 +1,17 @@ + + + guava19 + + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.m2e.core.maven2Nature + + diff --git a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartTest.java b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartTest.java index 687a248490..371657af62 100644 --- a/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartTest.java +++ b/httpclient/src/test/java/org/baeldung/httpclient/HttpClientMultipartTest.java @@ -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()); diff --git a/jackson/pom.xml b/jackson/pom.xml index f63ec08b48..c7cd172757 100644 --- a/jackson/pom.xml +++ b/jackson/pom.xml @@ -1,5 +1,5 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.baeldung jackson @@ -22,6 +22,12 @@ commons-io 2.4 + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + 2.7.4 + org.apache.commons @@ -55,12 +61,12 @@ com.fasterxml.jackson.datatype jackson-datatype-joda ${jackson.version} - + - - com.fasterxml.jackson.module - jackson-module-jsonSchema - 2.7.2 + + com.fasterxml.jackson.module + jackson-module-jsonSchema + 2.7.2 diff --git a/jackson/src/test/java/com/baeldung/jackson/xml/TestXMLSerializeDeserialize.java b/jackson/src/test/java/com/baeldung/jackson/xml/TestXMLSerializeDeserialize.java new file mode 100644 index 0000000000..92d0bd13d4 --- /dev/null +++ b/jackson/src/test/java/com/baeldung/jackson/xml/TestXMLSerializeDeserialize.java @@ -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( + "12", 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; + } + +} diff --git a/jackson/src/test/resources/simple_bean.xml b/jackson/src/test/resources/simple_bean.xml new file mode 100644 index 0000000000..7829ea35a4 --- /dev/null +++ b/jackson/src/test/resources/simple_bean.xml @@ -0,0 +1,4 @@ + + 1 + 2 + \ No newline at end of file diff --git a/jooq-spring/.classpath b/jooq-spring/.classpath index e43402fa4f..9ae7bca0fc 100644 --- a/jooq-spring/.classpath +++ b/jooq-spring/.classpath @@ -17,12 +17,7 @@ - - - - - - + diff --git a/jooq-spring/.project b/jooq-spring/.project index 3c3f3d602b..a291146b79 100644 --- a/jooq-spring/.project +++ b/jooq-spring/.project @@ -10,6 +10,11 @@ + + org.springframework.ide.eclipse.core.springbuilder + + + org.eclipse.m2e.core.maven2Builder @@ -17,6 +22,7 @@ + org.springframework.ide.eclipse.core.springnature org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature diff --git a/jsf/.gitignore b/jsf/.gitignore new file mode 100644 index 0000000000..d1c20ca0f1 --- /dev/null +++ b/jsf/.gitignore @@ -0,0 +1,2 @@ +/target +*.iml diff --git a/jsf/pom.xml b/jsf/pom.xml new file mode 100644 index 0000000000..2f5d315e41 --- /dev/null +++ b/jsf/pom.xml @@ -0,0 +1,116 @@ + + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + 4.0.0 + + jsf + 0.1-SNAPSHOT + war + + + + + com.sun.faces + jsf-api + ${com.sun.faces.version} + + + com.sun.faces + jsf-impl + ${com.sun.faces.version} + + + + + + org.springframework + spring-web + ${org.springframework.version} + + + org.springframework + spring-webmvc + ${org.springframework.version} + + + org.springframework + spring-websocket + ${org.springframework.version} + + + org.springframework + spring-messaging + ${org.springframework.version} + + + org.springframework + spring-web + ${org.springframework.version} + + + javax.servlet + javax.servlet-api + provided + ${javax.servlet.version} + + + + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + + org.slf4j + jcl-over-slf4j + ${org.slf4j.version} + + + + org.slf4j + log4j-over-slf4j + ${org.slf4j.version} + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.5.1 + + 1.8 + 1.8 + + + + + + + + 4.2.5.RELEASE + + + 2.1.7 + + + 1.7.13 + 1.1.3 + + + 3.1.0 + + \ No newline at end of file diff --git a/jsf/src/main/java/com/baeldung/springintegration/config/MainWebAppInitializer.java b/jsf/src/main/java/com/baeldung/springintegration/config/MainWebAppInitializer.java new file mode 100644 index 0000000000..2de647915c --- /dev/null +++ b/jsf/src/main/java/com/baeldung/springintegration/config/MainWebAppInitializer.java @@ -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> 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)); + } + +} diff --git a/jsf/src/main/java/com/baeldung/springintegration/config/SpringCoreConfig.java b/jsf/src/main/java/com/baeldung/springintegration/config/SpringCoreConfig.java new file mode 100644 index 0000000000..a39da3fe25 --- /dev/null +++ b/jsf/src/main/java/com/baeldung/springintegration/config/SpringCoreConfig.java @@ -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(); + } +} diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/RegistrationBean.java b/jsf/src/main/java/com/baeldung/springintegration/controllers/RegistrationBean.java new file mode 100644 index 0000000000..cf8dab5289 --- /dev/null +++ b/jsf/src/main/java/com/baeldung/springintegration/controllers/RegistrationBean.java @@ -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; + } +} diff --git a/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAO.java b/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAO.java new file mode 100644 index 0000000000..2acb4e636d --- /dev/null +++ b/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAO.java @@ -0,0 +1,7 @@ +package com.baeldung.springintegration.dao; + +public interface UserManagementDAO { + + boolean createUser(String newUserData); + +} diff --git a/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java b/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java new file mode 100644 index 0000000000..56cbdd7b88 --- /dev/null +++ b/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java @@ -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 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() { + } + + +} diff --git a/jsf/src/main/resources/logback.xml b/jsf/src/main/resources/logback.xml new file mode 100644 index 0000000000..e9ae1894a6 --- /dev/null +++ b/jsf/src/main/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + web - %date [%thread] %-5level %logger{36} - %message%n + + + + + + + + + \ No newline at end of file diff --git a/jsf/src/main/resources/messages.properties b/jsf/src/main/resources/messages.properties new file mode 100644 index 0000000000..41e9622630 --- /dev/null +++ b/jsf/src/main/resources/messages.properties @@ -0,0 +1,3 @@ +message.valueRequired = This value is required +message.welcome = Baeldung | Register +label.saveButton = Save diff --git a/jsf/src/main/webapp/META-INF/context.xml b/jsf/src/main/webapp/META-INF/context.xml new file mode 100644 index 0000000000..cf746bfae4 --- /dev/null +++ b/jsf/src/main/webapp/META-INF/context.xml @@ -0,0 +1,2 @@ + + diff --git a/jsf/src/main/webapp/WEB-INF/faces-config.xml b/jsf/src/main/webapp/WEB-INF/faces-config.xml new file mode 100644 index 0000000000..e9e6404b95 --- /dev/null +++ b/jsf/src/main/webapp/WEB-INF/faces-config.xml @@ -0,0 +1,39 @@ + + + + + + + + + + messages + + + msg + + + + + constraints + + + constraints + + + org.springframework.web.jsf.el.SpringBeanFacesELResolver + + + + /* + + home + /index.xhtml + + + + + diff --git a/jsf/src/main/webapp/index.xhtml b/jsf/src/main/webapp/index.xhtml new file mode 100644 index 0000000000..b37c864f2c --- /dev/null +++ b/jsf/src/main/webapp/index.xhtml @@ -0,0 +1,28 @@ + + + + + <h:outputText value="#{msg['message.welcome']}"/> + + + + + + + + + + + + + + + diff --git a/junit5/pom.xml b/junit5/pom.xml new file mode 100644 index 0000000000..5a2ea61668 --- /dev/null +++ b/junit5/pom.xml @@ -0,0 +1,83 @@ + + + 4.0.0 + + com.baeldung + junit5 + 1.0-SNAPSHOT + + junit5 + Intro to JUnit 5 + + + UTF-8 + 1.8 + + 5.0.0-SNAPSHOT + + + + + snapshots-repo + https://oss.sonatype.org/content/repositories/snapshots + + false + + + + always + true + + + + + + + snapshots-repo + https://oss.sonatype.org/content/repositories/snapshots + + false + + + + always + true + + + + + + + + maven-compiler-plugin + 3.1 + + ${java.version} + ${java.version} + + + + maven-surefire-plugin + 2.19 + + + org.junit + surefire-junit5 + ${junit.gen5.version} + + + + + + + + + org.junit + junit5-api + ${junit.gen5.version} + test + + + \ No newline at end of file diff --git a/junit5/src/test/java/com/baeldung/AssumptionTest.java b/junit5/src/test/java/com/baeldung/AssumptionTest.java new file mode 100644 index 0000000000..e4c2b56124 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/AssumptionTest.java @@ -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) + ); + } +} diff --git a/junit5/src/test/java/com/baeldung/ExceptionTest.java b/junit5/src/test/java/com/baeldung/ExceptionTest.java new file mode 100644 index 0000000000..5c30ad5b44 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/ExceptionTest.java @@ -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"); + } +} diff --git a/junit5/src/test/java/com/baeldung/FirstTest.java b/junit5/src/test/java/com/baeldung/FirstTest.java new file mode 100644 index 0000000000..4fc6037174 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/FirstTest.java @@ -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 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); + } +} diff --git a/junit5/src/test/java/com/baeldung/NestedTest.java b/junit5/src/test/java/com/baeldung/NestedTest.java new file mode 100644 index 0000000000..3fbe4f8644 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/NestedTest.java @@ -0,0 +1,77 @@ +package com.baeldung; + +import org.junit.gen5.api.*; + +import java.util.EmptyStackException; +import java.util.Stack; + +public class NestedTest { + Stack stack; + boolean isRun = false; + + @Test + @DisplayName("is instantiated with new Stack()") + void isInstantiatedWithNew() { + new Stack(); + } + + @Nested + @DisplayName("when new") + class WhenNew { + + @BeforeEach + void init() { + stack = new Stack(); + } + + @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()); + } + } + } +} diff --git a/junit5/src/test/java/com/baeldung/TaggedTest.java b/junit5/src/test/java/com/baeldung/TaggedTest.java new file mode 100644 index 0000000000..dbc82f4022 --- /dev/null +++ b/junit5/src/test/java/com/baeldung/TaggedTest.java @@ -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); + } +} diff --git a/mockito/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/mockito/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch deleted file mode 100644 index 627021fb96..0000000000 --- a/mockito/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/mockito/.settings/.jsdtscope b/mockito/.settings/.jsdtscope deleted file mode 100644 index 7b3f0c8b9f..0000000000 --- a/mockito/.settings/.jsdtscope +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/mockito/.settings/org.eclipse.jdt.core.prefs b/mockito/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index b126d6476b..0000000000 --- a/mockito/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -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 diff --git a/mockito/.settings/org.eclipse.jdt.ui.prefs b/mockito/.settings/org.eclipse.jdt.ui.prefs deleted file mode 100644 index 471e9b0d81..0000000000 --- a/mockito/.settings/org.eclipse.jdt.ui.prefs +++ /dev/null @@ -1,55 +0,0 @@ -#Sat Jan 21 23:04:06 EET 2012 -eclipse.preferences.version=1 -editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true -sp_cleanup.add_default_serial_version_id=true -sp_cleanup.add_generated_serial_version_id=false -sp_cleanup.add_missing_annotations=true -sp_cleanup.add_missing_deprecated_annotations=true -sp_cleanup.add_missing_methods=false -sp_cleanup.add_missing_nls_tags=false -sp_cleanup.add_missing_override_annotations=true -sp_cleanup.add_missing_override_annotations_interface_methods=true -sp_cleanup.add_serial_version_id=false -sp_cleanup.always_use_blocks=true -sp_cleanup.always_use_parentheses_in_expressions=true -sp_cleanup.always_use_this_for_non_static_field_access=false -sp_cleanup.always_use_this_for_non_static_method_access=false -sp_cleanup.convert_to_enhanced_for_loop=true -sp_cleanup.correct_indentation=true -sp_cleanup.format_source_code=true -sp_cleanup.format_source_code_changes_only=true -sp_cleanup.make_local_variable_final=true -sp_cleanup.make_parameters_final=true -sp_cleanup.make_private_fields_final=false -sp_cleanup.make_type_abstract_if_missing_method=false -sp_cleanup.make_variable_declarations_final=true -sp_cleanup.never_use_blocks=false -sp_cleanup.never_use_parentheses_in_expressions=false -sp_cleanup.on_save_use_additional_actions=true -sp_cleanup.organize_imports=true -sp_cleanup.qualify_static_field_accesses_with_declaring_class=false -sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true -sp_cleanup.qualify_static_member_accesses_with_declaring_class=true -sp_cleanup.qualify_static_method_accesses_with_declaring_class=false -sp_cleanup.remove_private_constructors=true -sp_cleanup.remove_trailing_whitespaces=true -sp_cleanup.remove_trailing_whitespaces_all=true -sp_cleanup.remove_trailing_whitespaces_ignore_empty=false -sp_cleanup.remove_unnecessary_casts=true -sp_cleanup.remove_unnecessary_nls_tags=false -sp_cleanup.remove_unused_imports=true -sp_cleanup.remove_unused_local_variables=false -sp_cleanup.remove_unused_private_fields=true -sp_cleanup.remove_unused_private_members=false -sp_cleanup.remove_unused_private_methods=true -sp_cleanup.remove_unused_private_types=true -sp_cleanup.sort_members=false -sp_cleanup.sort_members_all=false -sp_cleanup.use_blocks=false -sp_cleanup.use_blocks_only_for_return_and_throw=false -sp_cleanup.use_parentheses_in_expressions=false -sp_cleanup.use_this_for_non_static_field_access=true -sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true -sp_cleanup.use_this_for_non_static_method_access=true -sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true diff --git a/mockito/.settings/org.eclipse.m2e.core.prefs b/mockito/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1cb..0000000000 --- a/mockito/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/mockito/.settings/org.eclipse.m2e.wtp.prefs b/mockito/.settings/org.eclipse.m2e.wtp.prefs deleted file mode 100644 index ef86089622..0000000000 --- a/mockito/.settings/org.eclipse.m2e.wtp.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.m2e.wtp.enabledProjectSpecificPrefs=false diff --git a/mockito/.settings/org.eclipse.wst.common.component b/mockito/.settings/org.eclipse.wst.common.component deleted file mode 100644 index e98377cb0f..0000000000 --- a/mockito/.settings/org.eclipse.wst.common.component +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/mockito/.settings/org.eclipse.wst.common.project.facet.core.xml b/mockito/.settings/org.eclipse.wst.common.project.facet.core.xml deleted file mode 100644 index f4ef8aa0a5..0000000000 --- a/mockito/.settings/org.eclipse.wst.common.project.facet.core.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/mockito/.settings/org.eclipse.wst.jsdt.ui.superType.container b/mockito/.settings/org.eclipse.wst.jsdt.ui.superType.container deleted file mode 100644 index 3bd5d0a480..0000000000 --- a/mockito/.settings/org.eclipse.wst.jsdt.ui.superType.container +++ /dev/null @@ -1 +0,0 @@ -org.eclipse.wst.jsdt.launching.baseBrowserLibrary \ No newline at end of file diff --git a/mockito/.settings/org.eclipse.wst.jsdt.ui.superType.name b/mockito/.settings/org.eclipse.wst.jsdt.ui.superType.name deleted file mode 100644 index 05bd71b6ec..0000000000 --- a/mockito/.settings/org.eclipse.wst.jsdt.ui.superType.name +++ /dev/null @@ -1 +0,0 @@ -Window \ No newline at end of file diff --git a/mockito/.settings/org.eclipse.wst.validation.prefs b/mockito/.settings/org.eclipse.wst.validation.prefs deleted file mode 100644 index cacf5451ae..0000000000 --- a/mockito/.settings/org.eclipse.wst.validation.prefs +++ /dev/null @@ -1,14 +0,0 @@ -DELEGATES_PREFERENCE=delegateValidatorList -USER_BUILD_PREFERENCE=enabledBuildValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_MANUAL_PREFERENCE=enabledManualValidatorListorg.eclipse.jst.j2ee.internal.classpathdep.ClasspathDependencyValidator; -USER_PREFERENCE=overrideGlobalPreferencestruedisableAllValidationfalseversion1.2.303.v201202090300 -eclipse.preferences.version=1 -override=true -suspend=false -vals/org.eclipse.jst.jsf.ui.JSFAppConfigValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPBatchValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.JSPContentValidator/global=FF01 -vals/org.eclipse.jst.jsp.core.TLDValidator/global=FF01 -vals/org.eclipse.wst.dtd.core.dtdDTDValidator/global=FF01 -vals/org.eclipse.wst.jsdt.web.core.JsBatchValidator/global=TF02 -vf.version=3 diff --git a/mockito/.settings/org.eclipse.wst.ws.service.policy.prefs b/mockito/.settings/org.eclipse.wst.ws.service.policy.prefs deleted file mode 100644 index 9cfcabe16f..0000000000 --- a/mockito/.settings/org.eclipse.wst.ws.service.policy.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.wst.ws.service.policy.projectEnabled=false diff --git a/mockito/.springBeans b/mockito/.springBeans deleted file mode 100644 index a79097f40d..0000000000 --- a/mockito/.springBeans +++ /dev/null @@ -1,14 +0,0 @@ - - - 1 - - - - - - - src/main/webapp/WEB-INF/api-servlet.xml - - - - diff --git a/mockito/pom.xml b/mockito/pom.xml index 95b7b46d44..16c7cb0dd8 100644 --- a/mockito/pom.xml +++ b/mockito/pom.xml @@ -1,124 +1,143 @@ - - 4.0.0 - com.baeldung - mockito - 0.1-SNAPSHOT + + 4.0.0 + org.baeldung + mockito + 0.1-SNAPSHOT - mockito + mockito - + - + - - com.google.guava - guava - ${guava.version} - + + com.google.guava + guava + ${guava.version} + - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + - + - + - - junit - junit - ${junit.version} - test - + + junit + junit + ${junit.version} + test + - - org.hamcrest - hamcrest-core - ${org.hamcrest.version} - test - - - org.hamcrest - hamcrest-library - ${org.hamcrest.version} - test - + + org.hamcrest + hamcrest-core + ${org.hamcrest.version} + test + + + org.hamcrest + hamcrest-library + ${org.hamcrest.version} + test + - - org.mockito - mockito-core - ${mockito.version} - test - + + org.mockito + mockito-core + ${mockito.version} + test + - + + org.powermock + powermock-module-junit4 + ${powermock.version} + test + + + org.powermock + powermock-api-mockito + ${powermock.version} + test + - - mockito - - - src/main/resources - true - - + - + + mockito + + + src/main/resources + true + + - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - 1.8 - 1.8 - - + - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + - + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + - + - - - 4.3.11.Final - 5.1.38 + - - 1.7.13 - 1.1.3 + + + 4.1.5.RELEASE + 3.2.5.RELEASE - - 5.1.3.Final + + 4.3.10.Final + 5.1.35 - - 19.0 - 3.4 + + 1.7.13 + 1.1.3 - - 1.3 - 4.12 - 1.10.19 + + 5.1.3.Final - 4.4.1 - 4.5 + + 19.0 + 3.4 - 2.9.0 + + 1.3 + 4.12 + 1.10.19 + 1.6.4 - - 3.5.1 - 2.6 - 2.19.1 - 2.7 - 1.4.18 + 4.4.1 + 4.5 - + 2.4.1 + + + 3.3 + 2.6 + 2.18.1 + 2.7 + 1.4.14 + + \ No newline at end of file diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java b/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java new file mode 100644 index 0000000000..771444f13d --- /dev/null +++ b/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorForPartialMocking.java @@ -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."; + } +} \ No newline at end of file diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java b/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java new file mode 100644 index 0000000000..8287454782 --- /dev/null +++ b/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithFinalMethods.java @@ -0,0 +1,9 @@ +package com.baeldung.powermockito.introduction; + +public class CollaboratorWithFinalMethods { + + public final String helloMethod() { + return "Hello World!"; + } + +} diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java b/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java new file mode 100644 index 0000000000..2795ae97f1 --- /dev/null +++ b/mockito/src/test/java/com/baeldung/powermockito/introduction/CollaboratorWithStaticMethods.java @@ -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!"; + } +} \ No newline at end of file diff --git a/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoTest.java b/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoTest.java new file mode 100644 index 0000000000..6f12f3e459 --- /dev/null +++ b/mockito/src/test/java/com/baeldung/powermockito/introduction/PowerMockitoTest.java @@ -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); + } +} \ No newline at end of file diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationTest.java b/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationTest.java index 3acc2c937b..ec68c38f70 100644 --- a/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationTest.java +++ b/mockito/src/test/java/org/baeldung/mockito/MockitoAnnotationTest.java @@ -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 { diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoConfigExamplesTest.java b/mockito/src/test/java/org/baeldung/mockito/MockitoConfigExamplesTest.java index 399c511d4e..de6e7fca72 100644 --- a/mockito/src/test/java/org/baeldung/mockito/MockitoConfigExamplesTest.java +++ b/mockito/src/test/java/org/baeldung/mockito/MockitoConfigExamplesTest.java @@ -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 { diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoMockTest.java b/mockito/src/test/java/org/baeldung/mockito/MockitoMockTest.java new file mode 100644 index 0000000000..5a1996fa97 --- /dev/null +++ b/mockito/src/test/java/org/baeldung/mockito/MockitoMockTest.java @@ -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 { + @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)); + } +} \ No newline at end of file diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoSpyTest.java b/mockito/src/test/java/org/baeldung/mockito/MockitoSpyTest.java index adfd3ed1ae..8682e16e5d 100644 --- a/mockito/src/test/java/org/baeldung/mockito/MockitoSpyTest.java +++ b/mockito/src/test/java/org/baeldung/mockito/MockitoSpyTest.java @@ -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 { diff --git a/mockito/src/test/java/org/baeldung/mockito/MockitoVerifyExamplesTest.java b/mockito/src/test/java/org/baeldung/mockito/MockitoVerifyExamplesTest.java index 6875a9f819..6beae34138 100644 --- a/mockito/src/test/java/org/baeldung/mockito/MockitoVerifyExamplesTest.java +++ b/mockito/src/test/java/org/baeldung/mockito/MockitoVerifyExamplesTest.java @@ -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 mockedList = mock(MyList.class); - mockedList.addAll(Lists. newArrayList("someElement")); + mockedList.addAll(Lists.newArrayList("someElement")); final ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(List.class); verify(mockedList).addAll(argumentCaptor.capture()); - final List capturedArgument = argumentCaptor.> getValue(); + final List capturedArgument = argumentCaptor.>getValue(); assertThat(capturedArgument, hasItem("someElement")); } diff --git a/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java b/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java index 3fb2c30646..a613b28f59 100644 --- a/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java +++ b/mockito/src/test/java/org/baeldung/mockito/MyDictionary.java @@ -4,6 +4,7 @@ import java.util.HashMap; import java.util.Map; public class MyDictionary { + Map wordMap; public MyDictionary() { diff --git a/mockito/src/test/resources/.gitignore b/mockito/src/test/resources/.gitignore deleted file mode 100644 index 83c05e60c8..0000000000 --- a/mockito/src/test/resources/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -*.class - -#folders# -/target -/neoDb* -/data -/src/main/webapp/WEB-INF/classes -*/META-INF/* - -# Packaged files # -*.jar -*.war -*.ear \ No newline at end of file diff --git a/pom.xml b/pom.xml index 6f63269248..d6a1d7c034 100644 --- a/pom.xml +++ b/pom.xml @@ -64,6 +64,7 @@ spring-security-rest-full spring-thymeleaf spring-zuul + jsf diff --git a/spring-all/src/main/java/org/baeldung/caching/config/CachingConfig.java b/spring-all/src/main/java/org/baeldung/caching/config/CachingConfig.java index 4153ec9636..c995bca68d 100644 --- a/spring-all/src/main/java/org/baeldung/caching/config/CachingConfig.java +++ b/spring-all/src/main/java/org/baeldung/caching/config/CachingConfig.java @@ -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(); diff --git a/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java b/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java new file mode 100644 index 0000000000..38b5a5a3ec --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/caching/example/AbstractService.java @@ -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(); + } + +} diff --git a/spring-all/src/main/java/org/baeldung/caching/example/CustomerDataService.java b/spring-all/src/main/java/org/baeldung/caching/example/CustomerDataService.java index fe4de5d282..1c595057a8 100644 --- a/spring-all/src/main/java/org/baeldung/caching/example/CustomerDataService.java +++ b/spring-all/src/main/java/org/baeldung/caching/example/CustomerDataService.java @@ -1,7 +1,5 @@ package org.baeldung.caching.example; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; @@ -13,9 +11,6 @@ import org.springframework.stereotype.Component; @CacheConfig(cacheNames = { "addresses" }) public class CustomerDataService { - @Autowired - CacheManager cacheManager; - // this method configuration is equivalent to xml configuration @Cacheable(value = "addresses", key = "#customer.name") public String getAddress(final Customer customer) { diff --git a/spring-all/src/main/java/org/baeldung/caching/example/CustomerServiceWithParent.java b/spring-all/src/main/java/org/baeldung/caching/example/CustomerServiceWithParent.java new file mode 100644 index 0000000000..a5ded7daf9 --- /dev/null +++ b/spring-all/src/main/java/org/baeldung/caching/example/CustomerServiceWithParent.java @@ -0,0 +1,10 @@ +package org.baeldung.caching.example; + +import org.springframework.cache.annotation.CacheConfig; +import org.springframework.stereotype.Component; + +@Component +@CacheConfig(cacheNames = { "addresses" }) +public class CustomerServiceWithParent extends AbstractService { + // +} diff --git a/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingBehaviorTest.java b/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingBehaviorTest.java deleted file mode 100644 index a4a3733dd8..0000000000 --- a/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingBehaviorTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.baeldung.caching.test; - -import org.baeldung.caching.config.CachingConfig; -import org.baeldung.caching.example.Customer; -import org.baeldung.caching.example.CustomerDataService; -import org.junit.Test; -import org.springframework.stereotype.Component; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; - -@Component -public class SpringCachingBehaviorTest { - - @Test - public void testCaching() { - @SuppressWarnings("resource") - final - // final ApplicationContext context = new ClassPathXmlApplicationContext("config.xml"); - AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); - context.register(CachingConfig.class); - context.refresh(); - final CustomerDataService service = context.getBean(CustomerDataService.class); - - final Customer cust = new Customer("Tom", "67-2, Downing Street, NY"); - service.getAddress(cust); - service.getAddress(cust); - - // fail("Unable to instantiate the CustomerDataService"); - } - -} diff --git a/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingIntegrationTest.java b/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingIntegrationTest.java new file mode 100644 index 0000000000..8c4ebaa7ec --- /dev/null +++ b/spring-all/src/test/java/org/baeldung/caching/test/SpringCachingIntegrationTest.java @@ -0,0 +1,71 @@ +package org.baeldung.caching.test; + +import org.baeldung.caching.config.CachingConfig; +import org.baeldung.caching.example.Customer; +import org.baeldung.caching.example.CustomerDataService; +import org.baeldung.caching.example.CustomerServiceWithParent; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = { CachingConfig.class }, loader = AnnotationConfigContextLoader.class) +public class SpringCachingIntegrationTest { + + @Autowired + private CustomerDataService service; + + @Autowired + private CustomerServiceWithParent serviceWithParent; + + // + + @Test + public void whenGettingAddress_thenCorrect() { + final Customer cust = new Customer("Tom", "67-2, Downing Street, NY"); + service.getAddress(cust); + service.getAddress(cust); + + service.getAddress1(cust); + service.getAddress1(cust); + + service.getAddress2(cust); + service.getAddress2(cust); + + service.getAddress3(cust); + service.getAddress3(cust); + + service.getAddress4(cust); + service.getAddress4(cust); + + service.getAddress5(cust); + service.getAddress5(cust); + } + + @Test + public void givenUsingServiceWithParent_whenGettingAddress_thenCorrect() { + final Customer cust = new Customer("Tom", "67-2, Downing Street, NY"); + + serviceWithParent.getAddress(cust); + serviceWithParent.getAddress(cust); + + serviceWithParent.getAddress1(cust); + serviceWithParent.getAddress1(cust); + + serviceWithParent.getAddress2(cust); + serviceWithParent.getAddress2(cust); + + serviceWithParent.getAddress3(cust); + serviceWithParent.getAddress3(cust); + + // serviceWithParent.getAddress4(cust); + // serviceWithParent.getAddress4(cust); + + serviceWithParent.getAddress5(cust); + serviceWithParent.getAddress5(cust); + } + +} diff --git a/spring-autowire/pom.xml b/spring-autowire/pom.xml new file mode 100644 index 0000000000..e28efdae61 --- /dev/null +++ b/spring-autowire/pom.xml @@ -0,0 +1,63 @@ + + 4.0.0 + + com.baeldung + spring-autowire + 0.0.1-SNAPSHOT + jar + + spring-autowire + http://maven.apache.org + + + UTF-8 + 4.2.5.RELEASE + 3.5.1 + 2.19.1 + + + + + junit + junit + 4.11 + + + org.springframework + spring-core + ${org.springframework.version} + + + org.springframework + spring-context + ${org.springframework.version} + + + org.springframework + spring-test + ${org.springframework.version} + test + + + + + spring-autowire + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java new file mode 100644 index 0000000000..725a9b8406 --- /dev/null +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/App.java @@ -0,0 +1,11 @@ +package com.baeldung.autowire.sample; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +public class App { + public static void main(String[] args) { + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class); + FooService fooService = ctx.getBean(FooService.class); + fooService.doStuff(); + } +} diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/AppConfig.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/AppConfig.java new file mode 100644 index 0000000000..f948e2bf8e --- /dev/null +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/AppConfig.java @@ -0,0 +1,10 @@ +package com.baeldung.autowire.sample; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.autowire.sample") +public class AppConfig { + +} diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/Bar.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/Bar.java new file mode 100644 index 0000000000..7aa820adef --- /dev/null +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/Bar.java @@ -0,0 +1,5 @@ +package com.baeldung.autowire.sample; + +public class Bar { + +} diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java new file mode 100644 index 0000000000..fb704453fc --- /dev/null +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/BarFormatter.java @@ -0,0 +1,13 @@ +package com.baeldung.autowire.sample; + +import org.springframework.stereotype.Component; + +@FormatterType("Bar") +@Component +public class BarFormatter implements Formatter { + + public String format() { + return "bar"; + } + +} diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/Foo.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/Foo.java new file mode 100644 index 0000000000..b587ab38b8 --- /dev/null +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/Foo.java @@ -0,0 +1,5 @@ +package com.baeldung.autowire.sample; + +public class Foo { + +} diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooDAO.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooDAO.java new file mode 100644 index 0000000000..aec26202ab --- /dev/null +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooDAO.java @@ -0,0 +1,5 @@ +package com.baeldung.autowire.sample; + +public class FooDAO { + +} diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java new file mode 100644 index 0000000000..73966e9e43 --- /dev/null +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooFormatter.java @@ -0,0 +1,13 @@ +package com.baeldung.autowire.sample; + +import org.springframework.stereotype.Component; + +@FormatterType("Foo") +@Component +public class FooFormatter implements Formatter { + + public String format() { + return "foo"; + } + +} diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java new file mode 100644 index 0000000000..eccea4351a --- /dev/null +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FooService.java @@ -0,0 +1,17 @@ +package com.baeldung.autowire.sample; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class FooService { + + @Autowired + @FormatterType("Foo") + private Formatter formatter; + + public String doStuff(){ + return formatter.format(); + } + +} diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java new file mode 100644 index 0000000000..83716d6e92 --- /dev/null +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/Formatter.java @@ -0,0 +1,7 @@ +package com.baeldung.autowire.sample; + +public interface Formatter { + + String format(); + +} diff --git a/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java new file mode 100644 index 0000000000..7ffc308c9a --- /dev/null +++ b/spring-autowire/src/main/java/com/baeldung/autowire/sample/FormatterType.java @@ -0,0 +1,17 @@ +package com.baeldung.autowire.sample; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import org.springframework.beans.factory.annotation.Qualifier; + +@Qualifier +@Target({ElementType.FIELD, ElementType.METHOD,ElementType.TYPE, ElementType.PARAMETER}) +@Retention(RetentionPolicy.RUNTIME) +public @interface FormatterType { + + String value(); + +} diff --git a/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java b/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java new file mode 100644 index 0000000000..4607f527d9 --- /dev/null +++ b/spring-autowire/src/test/java/com/baeldung/autowire/sample/FooServiceTest.java @@ -0,0 +1,22 @@ +package com.baeldung.autowire.sample; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes=AppConfig.class, loader=AnnotationConfigContextLoader.class) +public class FooServiceTest { + + @Autowired + FooService fooService; + + @Test + public void whenFooFormatterType_thenReturnFoo(){ + Assert.assertEquals("foo", fooService.doStuff()); + } +} diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index bedab2391e..d0a66197bf 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -11,7 +11,7 @@ org.springframework.boot spring-boot-starter-parent - 1.2.6.RELEASE + 1.3.3.RELEASE diff --git a/spring-data-couchbase-2/pom.xml b/spring-data-couchbase-2/pom.xml index 93b3dbddb4..d24ef4aeaa 100644 --- a/spring-data-couchbase-2/pom.xml +++ b/spring-data-couchbase-2/pom.xml @@ -93,7 +93,7 @@ 1.7 UTF-8 4.2.4.RELEASE - 2.0.0.RELEASE + 2.1.1.RELEASE 5.2.4.Final 2.9.2 1.1.3 diff --git a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java index bedae26e00..3fabf7a11e 100644 --- a/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java +++ b/spring-data-couchbase-2/src/test/java/org/baeldung/spring/data/couchbase/service/PersonServiceTest.java @@ -27,28 +27,20 @@ public abstract class PersonServiceTest extends IntegrationTest { static final String smith = "Smith"; static final String johnSmithId = "person:" + john + ":" + smith; static final Person johnSmith = new Person(johnSmithId, john, smith); - static final JsonObject jsonJohnSmith = JsonObject.empty() - .put(typeField, Person.class.getName()) - .put("firstName", john) - .put("lastName", smith) - .put("created", DateTime.now().getMillis()); + static final JsonObject jsonJohnSmith = JsonObject.empty().put(typeField, Person.class.getName()).put("firstName", john).put("lastName", smith).put("created", DateTime.now().getMillis()); static final String foo = "Foo"; static final String bar = "Bar"; static final String foobarId = "person:" + foo + ":" + bar; static final Person foobar = new Person(foobarId, foo, bar); - static final JsonObject jsonFooBar = JsonObject.empty() - .put(typeField, Person.class.getName()) - .put("firstName", foo) - .put("lastName", bar) - .put("created", DateTime.now().getMillis()); - + static final JsonObject jsonFooBar = JsonObject.empty().put(typeField, Person.class.getName()).put("firstName", foo).put("lastName", bar).put("created", DateTime.now().getMillis()); + PersonService personService; - + @BeforeClass public static void setupBeforeClass() { - Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST); - Bucket bucket = cluster.openBucket(MyCouchbaseConfig.BUCKET_NAME, MyCouchbaseConfig.BUCKET_PASSWORD); + final Cluster cluster = CouchbaseCluster.create(MyCouchbaseConfig.NODE_LIST); + final Bucket bucket = cluster.openBucket(MyCouchbaseConfig.BUCKET_NAME, MyCouchbaseConfig.BUCKET_PASSWORD); bucket.upsert(JsonDocument.create(johnSmithId, jsonJohnSmith)); bucket.upsert(JsonDocument.create(foobarId, jsonFooBar)); bucket.close(); @@ -57,7 +49,7 @@ public abstract class PersonServiceTest extends IntegrationTest { @Test public void whenFindingPersonByJohnSmithId_thenReturnsJohnSmith() { - Person actualPerson = personService.findOne(johnSmithId); + final Person actualPerson = personService.findOne(johnSmithId); assertNotNull(actualPerson); assertNotNull(actualPerson.getCreated()); assertEquals(johnSmith, actualPerson); @@ -65,7 +57,7 @@ public abstract class PersonServiceTest extends IntegrationTest { @Test public void whenFindingAllPersons_thenReturnsTwoOrMorePersonsIncludingJohnSmithAndFooBar() { - List resultList = personService.findAll(); + final List resultList = personService.findAll(); assertNotNull(resultList); assertFalse(resultList.isEmpty()); assertTrue(resultContains(resultList, johnSmith)); @@ -75,8 +67,8 @@ public abstract class PersonServiceTest extends IntegrationTest { @Test public void whenFindingByFirstNameJohn_thenReturnsOnlyPersonsNamedJohn() { - String expectedFirstName = john; - List resultList = personService.findByFirstName(expectedFirstName); + final String expectedFirstName = john; + final List resultList = personService.findByFirstName(expectedFirstName); assertNotNull(resultList); assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedFirstName(resultList, expectedFirstName)); @@ -84,17 +76,24 @@ public abstract class PersonServiceTest extends IntegrationTest { @Test public void whenFindingByLastNameSmith_thenReturnsOnlyPersonsNamedSmith() { - String expectedLastName = smith; - List resultList = personService.findByLastName(expectedLastName); + final String expectedLastName = smith; + final List resultList = personService.findByLastName(expectedLastName); assertNotNull(resultList); assertFalse(resultList.isEmpty()); assertTrue(allResultsContainExpectedLastName(resultList, expectedLastName)); } - + + @Test + public void whenFindingByFirstNameJohn_thenReturnsOnePersonNamedJohn() { + final String expectedFirstName = john; + final List resultList = personService.findByFirstName(expectedFirstName); + assertTrue(resultList.size() == 1); + } + private boolean resultContains(List resultList, Person person) { boolean found = false; - for(Person p : resultList) { - if(p.equals(person)) { + for (final Person p : resultList) { + if (p.equals(person)) { found = true; break; } @@ -104,8 +103,8 @@ public abstract class PersonServiceTest extends IntegrationTest { private boolean allResultsContainExpectedFirstName(List resultList, String firstName) { boolean found = false; - for(Person p : resultList) { - if(p.getFirstName().equals(firstName)) { + for (final Person p : resultList) { + if (p.getFirstName().equals(firstName)) { found = true; break; } @@ -115,8 +114,8 @@ public abstract class PersonServiceTest extends IntegrationTest { private boolean allResultsContainExpectedLastName(List resultList, String lastName) { boolean found = false; - for(Person p : resultList) { - if(p.getLastName().equals(lastName)) { + for (final Person p : resultList) { + if (p.getLastName().equals(lastName)) { found = true; break; } diff --git a/core-java-8/.classpath b/spring-data-elasticsearch/.classpath similarity index 85% rename from core-java-8/.classpath rename to spring-data-elasticsearch/.classpath index 5efa587d72..6d7587a819 100644 --- a/core-java-8/.classpath +++ b/spring-data-elasticsearch/.classpath @@ -6,18 +6,18 @@ - - - - - - - + + + + + + + @@ -27,10 +27,5 @@ - - - - - diff --git a/mockito/.project b/spring-data-elasticsearch/.project similarity index 58% rename from mockito/.project rename to spring-data-elasticsearch/.project index 1c6c0deddc..09b9a781ed 100644 --- a/mockito/.project +++ b/spring-data-elasticsearch/.project @@ -1,6 +1,6 @@ - mockito + spring-data-elasticsearch @@ -10,27 +10,20 @@ - - org.eclipse.wst.common.project.facet.core.builder - - - - - org.eclipse.wst.validation.validationbuilder - - - org.eclipse.m2e.core.maven2Builder + + org.springframework.ide.eclipse.core.springbuilder + + + - org.eclipse.jem.workbench.JavaEMFNature - org.eclipse.wst.common.modulecore.ModuleCoreNature + org.springframework.ide.eclipse.core.springnature org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature - org.eclipse.wst.common.project.facet.core.nature diff --git a/spring-data-elasticsearch/pom.xml b/spring-data-elasticsearch/pom.xml index 27fb521dbc..3a6e330564 100644 --- a/spring-data-elasticsearch/pom.xml +++ b/spring-data-elasticsearch/pom.xml @@ -18,7 +18,7 @@ 4.11 1.7.12 1.1.3 - 1.3.2.RELEASE + 2.0.1.RELEASE @@ -44,6 +44,11 @@ spring-data-elasticsearch ${elasticsearch.version} + net.java.dev.jna + jna + 4.1.0 + test + org.slf4j slf4j-api diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java index 3857056b70..f93999a1cc 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/config/Config.java @@ -1,10 +1,16 @@ package com.baeldung.spring.data.es.config; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + import org.elasticsearch.client.Client; -import org.elasticsearch.common.settings.ImmutableSettings; +import org.elasticsearch.common.settings.Settings; import org.elasticsearch.node.NodeBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -12,35 +18,33 @@ import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - @Configuration @EnableElasticsearchRepositories(basePackages = "com.baeldung.spring.data.es.repository") -@ComponentScan(basePackages = {"com.baeldung.spring.data.es.service"}) +@ComponentScan(basePackages = { "com.baeldung.spring.data.es.service" }) public class Config { + @Value("${elasticsearch.home:/usr/local/Cellar/elasticsearch/2.3.2}") + private String elasticsearchHome; + private static Logger logger = LoggerFactory.getLogger(Config.class); @Bean public Client client() { try { - Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data"); + final Path tmpDir = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), "elasticsearch_data"); - ImmutableSettings.Builder elasticsearchSettings = ImmutableSettings.settingsBuilder() - .put("http.enabled", "false") - .put("path.data", tmpDir.toAbsolutePath().toString()); + // @formatter:off + + final Settings.Builder elasticsearchSettings = + Settings.settingsBuilder().put("http.enabled", "false") + .put("path.data", tmpDir.toAbsolutePath().toString()) + .put("path.home", elasticsearchHome); + // @formatter:on logger.debug(tmpDir.toAbsolutePath().toString()); - return new NodeBuilder() - .local(true) - .settings(elasticsearchSettings.build()) - .node() - .client(); - } catch (IOException ioex) { + return new NodeBuilder().local(true).settings(elasticsearchSettings.build()).node().client(); + } catch (final IOException ioex) { logger.error("Cannot create temp dir", ioex); throw new RuntimeException(); } diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java index 40db51ac13..01330a6c9c 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Article.java @@ -1,27 +1,25 @@ package com.baeldung.spring.data.es.model; -import org.springframework.data.annotation.Id; -import org.springframework.data.elasticsearch.annotations.*; - -import java.util.Arrays; -import java.util.List; - import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed; import static org.springframework.data.elasticsearch.annotations.FieldType.Nested; import static org.springframework.data.elasticsearch.annotations.FieldType.String; +import java.util.Arrays; +import java.util.List; + +import org.springframework.data.annotation.Id; +import org.springframework.data.elasticsearch.annotations.Document; +import org.springframework.data.elasticsearch.annotations.Field; +import org.springframework.data.elasticsearch.annotations.InnerField; +import org.springframework.data.elasticsearch.annotations.MultiField; + @Document(indexName = "blog", type = "article") public class Article { @Id private String id; - @MultiField( - mainField = @Field(type = String), - otherFields = { - @NestedField(index = not_analyzed, dotSuffix = "verbatim", type = String) - } - ) + @MultiField(mainField = @Field(type = String), otherFields = { @InnerField(index = not_analyzed, suffix = "verbatim", type = String) }) private String title; @Field(type = Nested) @@ -71,11 +69,6 @@ public class Article { @Override public String toString() { - return "Article{" + - "id='" + id + '\'' + - ", title='" + title + '\'' + - ", authors=" + authors + - ", tags=" + Arrays.toString(tags) + - '}'; + return "Article{" + "id='" + id + '\'' + ", title='" + title + '\'' + ", authors=" + authors + ", tags=" + Arrays.toString(tags) + '}'; } } diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Author.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Author.java index c335c4534a..38f50e1614 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Author.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/model/Author.java @@ -21,8 +21,6 @@ public class Author { @Override public String toString() { - return "Author{" + - "name='" + name + '\'' + - '}'; + return "Author{" + "name='" + name + '\'' + '}'; } } diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java index 760bad4b01..b5a8fde633 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleService.java @@ -6,10 +6,16 @@ import org.springframework.data.domain.Pageable; public interface ArticleService { Article save(Article article); + Article findOne(String id); + Iterable
findAll(); + Page
findByAuthorName(String name, Pageable pageable); + Page
findByAuthorNameUsingCustomQuery(String name, Pageable pageable); + long count(); + void delete(Article article); } diff --git a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java index 3bb6e6a0e0..0ea922bdd3 100644 --- a/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java +++ b/spring-data-elasticsearch/src/main/java/com/baeldung/spring/data/es/service/ArticleServiceImpl.java @@ -49,6 +49,6 @@ public class ArticleServiceImpl implements ArticleService { @Override public void delete(Article article) { - articleRepository.delete(article); + articleRepository.delete(article); } } diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java index fbc18cbb4c..1551d6442e 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchQueryTest.java @@ -1,12 +1,20 @@ package com.baeldung.spring.data.es; -import com.baeldung.spring.data.es.config.Config; -import com.baeldung.spring.data.es.model.Article; -import com.baeldung.spring.data.es.model.Author; -import com.baeldung.spring.data.es.service.ArticleService; -import org.elasticsearch.action.ActionFuture; -import org.elasticsearch.action.index.IndexRequest; -import org.elasticsearch.action.index.IndexResponse; +import static java.util.Arrays.asList; +import static java.util.stream.Collectors.toList; +import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND; +import static org.elasticsearch.index.query.QueryBuilders.boolQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchQuery; +import static org.elasticsearch.index.query.QueryBuilders.multiMatchQuery; +import static org.elasticsearch.index.query.QueryBuilders.nestedQuery; +import static org.elasticsearch.index.query.QueryBuilders.termQuery; +import static org.junit.Assert.assertEquals; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.common.unit.Fuzziness; @@ -28,19 +36,13 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import static java.util.Arrays.asList; -import static java.util.stream.Collectors.toList; -import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND; -import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.junit.Assert.assertEquals; +import com.baeldung.spring.data.es.config.Config; +import com.baeldung.spring.data.es.model.Article; +import com.baeldung.spring.data.es.model.Author; +import com.baeldung.spring.data.es.service.ArticleService; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {Config.class}, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { Config.class }, loader = AnnotationConfigContextLoader.class) public class ElasticSearchQueryTest { @Autowired @@ -60,7 +62,7 @@ public class ElasticSearchQueryTest { elasticsearchTemplate.deleteIndex(Article.class); elasticsearchTemplate.createIndex(Article.class); elasticsearchTemplate.putMapping(Article.class); - elasticsearchTemplate.refresh(Article.class, true); + elasticsearchTemplate.refresh(Article.class); Article article = new Article("Spring Data Elasticsearch"); article.setAuthors(asList(johnSmith, johnDoe)); @@ -85,127 +87,92 @@ public class ElasticSearchQueryTest { @Test public void givenFullTitle_whenRunMatchQuery_thenDocIsFound() { - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchQuery("title", "Search engines").operator(AND)) - .build(); - List
articles = elasticsearchTemplate - .queryForList(searchQuery, Article.class); + final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(AND)).build(); + final List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(1, articles.size()); } @Test public void givenOneTermFromTitle_whenRunMatchQuery_thenDocIsFound() { - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchQuery("title", "Engines Solutions")) - .build(); - List
articles = elasticsearchTemplate - .queryForList(searchQuery, Article.class); + final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Engines Solutions")).build(); + final List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(1, articles.size()); assertEquals("Search engines", articles.get(0).getTitle()); } @Test public void givenPartTitle_whenRunMatchQuery_thenDocIsFound() { - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchQuery("title", "elasticsearch data")) - .build(); - List
articles = elasticsearchTemplate - .queryForList(searchQuery, Article.class); + final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "elasticsearch data")).build(); + final List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(3, articles.size()); } @Test public void givenFullTitle_whenRunMatchQueryOnVerbatimField_thenDocIsFound() { - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch")) - .build(); - List
articles = elasticsearchTemplate - .queryForList(searchQuery, Article.class); + SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About Elasticsearch")).build(); + List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(1, articles.size()); - searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchQuery("title.verbatim", "Second Article About")) - .build(); - articles = elasticsearchTemplate - .queryForList(searchQuery, Article.class); + searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title.verbatim", "Second Article About")).build(); + articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(0, articles.size()); } @Test public void givenNestedObject_whenQueryByAuthorsName_thenFoundArticlesByThatAuthor() { - QueryBuilder builder = nestedQuery("authors", - boolQuery().must(termQuery("authors.name", "smith"))); + final QueryBuilder builder = nestedQuery("authors", boolQuery().must(termQuery("authors.name", "smith"))); - SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); - List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); + final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); + final List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(2, articles.size()); } @Test public void givenAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTokenCountsSeparately() { - TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("title"); - SearchResponse response = client.prepareSearch("blog").setTypes("article") - .addAggregation(aggregation).execute().actionGet(); + final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("title"); + final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation).execute().actionGet(); - Map results = response.getAggregations().asMap(); - StringTerms topTags = (StringTerms) results.get("top_tags"); + final Map results = response.getAggregations().asMap(); + final StringTerms topTags = (StringTerms) results.get("top_tags"); - List keys = topTags.getBuckets().stream().map(b -> b.getKey()).collect(toList()); + final List keys = topTags.getBuckets().stream().map(b -> b.getKeyAsString()).collect(toList()); Collections.sort(keys); - assertEquals(asList("about", "article", "data", "elasticsearch", - "engines", "search", "second", "spring", "tutorial"), keys); + assertEquals(asList("about", "article", "data", "elasticsearch", "engines", "search", "second", "spring", "tutorial"), keys); } @Test public void givenNotAnalyzedQuery_whenMakeAggregationOnTermCount_thenEachTermCountsIndividually() { - TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags") - .order(Terms.Order.aggregation("_count", false)); - SearchResponse response = client.prepareSearch("blog").setTypes("article") - .addAggregation(aggregation).execute().actionGet(); + final TermsBuilder aggregation = AggregationBuilders.terms("top_tags").field("tags").order(Terms.Order.aggregation("_count", false)); + final SearchResponse response = client.prepareSearch("blog").setTypes("article").addAggregation(aggregation).execute().actionGet(); - Map results = response.getAggregations().asMap(); - StringTerms topTags = (StringTerms) results.get("top_tags"); + final Map results = response.getAggregations().asMap(); + final StringTerms topTags = (StringTerms) results.get("top_tags"); - List keys = topTags.getBuckets().stream().map(b -> b.getKey()).collect(toList()); + final List keys = topTags.getBuckets().stream().map(b -> b.getKeyAsString()).collect(toList()); assertEquals(asList("elasticsearch", "spring data", "search engines", "tutorial"), keys); } @Test public void givenNotExactPhrase_whenUseSlop_thenQueryMatches() { - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1)) - .build(); - List
articles = elasticsearchTemplate - .queryForList(searchQuery, Article.class); + final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchPhraseQuery("title", "spring elasticsearch").slop(1)).build(); + final List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(1, articles.size()); } @Test public void givenPhraseWithType_whenUseFuzziness_thenQueryMatches() { - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchQuery("title", "spring date elasticserch") - .operator(AND) - .fuzziness(Fuzziness.ONE) - .prefixLength(3)) - .build(); + final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "spring date elasticserch").operator(AND).fuzziness(Fuzziness.ONE).prefixLength(3)).build(); - List
articles = elasticsearchTemplate - .queryForList(searchQuery, Article.class); + final List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(1, articles.size()); } @Test public void givenMultimatchQuery_whenDoSearch_thenAllProvidedFieldsMatch() { - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(multiMatchQuery("tutorial") - .field("title") - .field("tags") - .type(MultiMatchQueryBuilder.Type.BEST_FIELDS)) - .build(); + final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(multiMatchQuery("tutorial").field("title").field("tags").type(MultiMatchQueryBuilder.Type.BEST_FIELDS)).build(); - List
articles = elasticsearchTemplate - .queryForList(searchQuery, Article.class); + final List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(2, articles.size()); } } diff --git a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java index 7b48772d3f..e10b5f48d7 100644 --- a/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java +++ b/spring-data-elasticsearch/src/test/java/com/baeldung/spring/data/es/ElasticSearchTest.java @@ -1,9 +1,15 @@ package com.baeldung.spring.data.es; -import com.baeldung.spring.data.es.config.Config; -import com.baeldung.spring.data.es.model.Article; -import com.baeldung.spring.data.es.model.Author; -import com.baeldung.spring.data.es.service.ArticleService; +import static java.util.Arrays.asList; +import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND; +import static org.elasticsearch.index.query.QueryBuilders.fuzzyQuery; +import static org.elasticsearch.index.query.QueryBuilders.matchQuery; +import static org.elasticsearch.index.query.QueryBuilders.regexpQuery; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.List; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -17,17 +23,13 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import java.util.List; - -import static java.util.Arrays.asList; -import static org.elasticsearch.index.query.FilterBuilders.regexpFilter; -import static org.elasticsearch.index.query.MatchQueryBuilder.Operator.AND; -import static org.elasticsearch.index.query.QueryBuilders.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import com.baeldung.spring.data.es.config.Config; +import com.baeldung.spring.data.es.model.Article; +import com.baeldung.spring.data.es.model.Author; +import com.baeldung.spring.data.es.service.ArticleService; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {Config.class}, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = { Config.class }, loader = AnnotationConfigContextLoader.class) public class ElasticSearchTest { @Autowired @@ -59,8 +61,7 @@ public class ElasticSearchTest { @Test public void givenArticleService_whenSaveArticle_thenIdIsAssigned() { - List authors = asList( - new Author("John Smith"), johnDoe); + final List authors = asList(new Author("John Smith"), johnDoe); Article article = new Article("Making Search Elastic"); article.setAuthors(authors); @@ -72,39 +73,34 @@ public class ElasticSearchTest { @Test public void givenPersistedArticles_whenSearchByAuthorsName_thenRightFound() { - Page
articleByAuthorName = articleService.findByAuthorName(johnSmith.getName(), new PageRequest(0, 10)); + final Page
articleByAuthorName = articleService.findByAuthorName(johnSmith.getName(), new PageRequest(0, 10)); assertEquals(2L, articleByAuthorName.getTotalElements()); } @Test public void givenCustomQuery_whenSearchByAuthorsName_thenArticleIsFound() { - Page
articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("John Smith", new PageRequest(0, 10)); + final Page
articleByAuthorName = articleService.findByAuthorNameUsingCustomQuery("John Smith", new PageRequest(0, 10)); assertEquals(3L, articleByAuthorName.getTotalElements()); } - @Test public void givenPersistedArticles_whenUseRegexQuery_thenRightArticlesFound() { - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withFilter(regexpFilter("title", ".*data.*")) - .build(); - List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); + final SearchQuery searchQuery = new NativeSearchQueryBuilder().withFilter(regexpQuery("title", ".*data.*")).build(); + final List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(1, articles.size()); } @Test public void givenSavedDoc_whenTitleUpdated_thenCouldFindByUpdatedTitle() { - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(fuzzyQuery("title", "serch")) - .build(); - List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); + final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fuzzyQuery("title", "serch")).build(); + final List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(1, articles.size()); - Article article = articles.get(0); + final Article article = articles.get(0); final String newTitle = "Getting started with Search Engines"; article.setTitle(newTitle); articleService.save(article); @@ -117,10 +113,8 @@ public class ElasticSearchTest { final String articleTitle = "Spring Data Elasticsearch"; - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%")) - .build(); - List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); + final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", articleTitle).minimumShouldMatch("75%")).build(); + final List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(1, articles.size()); final long count = articleService.count(); @@ -131,10 +125,8 @@ public class ElasticSearchTest { @Test public void givenSavedDoc_whenOneTermMatches_thenFindByTitle() { - SearchQuery searchQuery = new NativeSearchQueryBuilder() - .withQuery(matchQuery("title", "Search engines").operator(AND)) - .build(); - List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); + final SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchQuery("title", "Search engines").operator(AND)).build(); + final List
articles = elasticsearchTemplate.queryForList(searchQuery, Article.class); assertEquals(1, articles.size()); } } diff --git a/mockito/.classpath b/spring-data-redis/.classpath similarity index 84% rename from mockito/.classpath rename to spring-data-redis/.classpath index 8ebf6d9c31..9ae7bca0fc 100644 --- a/mockito/.classpath +++ b/spring-data-redis/.classpath @@ -6,18 +6,18 @@ - - - - - - - + + + + + + + @@ -27,10 +27,5 @@ - - - - - diff --git a/spring-data-redis/.project b/spring-data-redis/.project new file mode 100644 index 0000000000..244dfe15fb --- /dev/null +++ b/spring-data-redis/.project @@ -0,0 +1,29 @@ + + + spring-data-redis + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + org.springframework.ide.eclipse.core.springbuilder + + + + + + org.springframework.ide.eclipse.core.springnature + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/IntegrationTestSuite.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/IntegrationTestSuite.java index c107a221d6..f5c45a5d6f 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/IntegrationTestSuite.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/IntegrationTestSuite.java @@ -1,20 +1,24 @@ package com.baeldung.persistence; -import com.baeldung.persistence.hibernate.FooPaginationPersistenceIntegrationTest; -import com.baeldung.persistence.hibernate.FooSortingPersistenceServiceTest; -import com.baeldung.persistence.service.FooServicePersistenceIntegrationTest; -import com.baeldung.persistence.service.FooServiceBasicPersistenceIntegrationTest; -import com.baeldung.persistence.service.ParentServicePersistenceIntegrationTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; +import com.baeldung.persistence.audit.AuditTestSuite; +import com.baeldung.persistence.hibernate.FooPaginationPersistenceIntegrationTest; +import com.baeldung.persistence.hibernate.FooSortingPersistenceIntegrationTest; +import com.baeldung.persistence.service.FooServiceBasicPersistenceIntegrationTest; +import com.baeldung.persistence.service.FooServicePersistenceIntegrationTest; +import com.baeldung.persistence.service.ParentServicePersistenceIntegrationTest; + @RunWith(Suite.class) @Suite.SuiteClasses({ // @formatter:off - FooServiceBasicPersistenceIntegrationTest.class + AuditTestSuite.class + ,FooServiceBasicPersistenceIntegrationTest.class ,FooPaginationPersistenceIntegrationTest.class ,FooServicePersistenceIntegrationTest.class ,ParentServicePersistenceIntegrationTest.class - ,FooSortingPersistenceServiceTest.class + ,FooSortingPersistenceIntegrationTest.class + }) // @formatter:on public class IntegrationTestSuite { // diff --git a/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceServiceTest.java b/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java similarity index 99% rename from spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceServiceTest.java rename to spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java index c890e08d15..0f76526960 100644 --- a/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceServiceTest.java +++ b/spring-hibernate4/src/test/java/com/baeldung/persistence/hibernate/FooSortingPersistenceIntegrationTest.java @@ -26,7 +26,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class) @SuppressWarnings("unchecked") -public class FooSortingPersistenceServiceTest { +public class FooSortingPersistenceIntegrationTest { @Autowired private SessionFactory sessionFactory; diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java index 73c36190f9..091bec0ba0 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/FooPaginationPersistenceIntegrationTest.java @@ -88,11 +88,12 @@ public class FooPaginationPersistenceIntegrationTest { public final void givenEntitiesExist_whenRetrievingPage_thenCorrect() { final int pageSize = 10; - final Query queryIds = entityManager.createQuery("Select f.id from Foo f order by f.lastName"); + final Query queryIds = entityManager.createQuery("Select f.id from Foo f order by f.name"); final List fooIds = queryIds.getResultList(); - final Query query = entityManager.createQuery("Select f from Foo e whet f.id in :ids"); + final Query query = entityManager.createQuery("Select f from Foo as f where f.id in :ids"); query.setParameter("ids", fooIds.subList(0, pageSize)); + final List fooList = query.getResultList(); // Then @@ -129,13 +130,15 @@ public class FooPaginationPersistenceIntegrationTest { final Root from = criteriaQuery.from(Foo.class); final CriteriaQuery select = criteriaQuery.select(from); - final TypedQuery typedQuery = entityManager.createQuery(select); + TypedQuery typedQuery; while (pageNumber < count.intValue()) { + typedQuery = entityManager.createQuery(select); typedQuery.setFirstResult(pageNumber - 1); typedQuery.setMaxResults(pageSize); System.out.println("Current page: " + typedQuery.getResultList()); pageNumber += pageSize; } + } // UTIL diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java index 96b3235f64..4c57865f74 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServicePersistenceIntegrationTest.java @@ -36,7 +36,7 @@ public class FooServicePersistenceIntegrationTest { @Test(expected = DataIntegrityViolationException.class) public final void whenInvalidEntityIsCreated_thenDataException() { - service.create(new Foo()); + service.create(new Foo(randomAlphabetic(2048))); } @Test(expected = DataIntegrityViolationException.class) @@ -53,7 +53,7 @@ public class FooServicePersistenceIntegrationTest { @Test(expected = DataAccessException.class) public final void temp_whenInvalidEntityIsCreated_thenDataException() { - service.create(new Foo()); + service.create(new Foo(randomAlphabetic(2048))); } @Test diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingTests.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java similarity index 95% rename from spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingTests.java rename to spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java index 319d36151e..3c9f509da5 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingTests.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingIntegrationTest.java @@ -22,7 +22,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) @SuppressWarnings("unchecked") -public class FooServiceSortingTests { +public class FooServiceSortingIntegrationTest { @PersistenceContext private EntityManager entityManager; @@ -65,7 +65,10 @@ public class FooServiceSortingTests { final Query barJoinQuery = entityManager.createQuery(jql); final List fooList = barJoinQuery.getResultList(); for (final Foo foo : fooList) { - System.out.println("Name:" + foo.getName() + "-------BarId:" + foo.getBar().getId()); + System.out.println("Name:" + foo.getName()); + if (foo.getBar() != null) { + System.out.print("-------BarId:" + foo.getBar().getId()); + } } } diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java similarity index 93% rename from spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualTest.java rename to spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java index 986e4e4a7d..040eee1c73 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/FooServiceSortingWitNullsManualIntegrationTest.java @@ -20,7 +20,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { PersistenceJPAConfig.class }, loader = AnnotationConfigContextLoader.class) -public class FooServiceSortingWitNullsManualTest { +public class FooServiceSortingWitNullsManualIntegrationTest { @PersistenceContext private EntityManager entityManager; @@ -30,6 +30,7 @@ public class FooServiceSortingWitNullsManualTest { // tests + @SuppressWarnings("unchecked") @Test public final void whenSortingByStringNullLast_thenLastNull() { service.create(new Foo()); @@ -44,6 +45,7 @@ public class FooServiceSortingWitNullsManualTest { } } + @SuppressWarnings("unchecked") @Test public final void whenSortingByStringNullFirst_thenFirstNull() { service.create(new Foo()); diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBTest.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java similarity index 94% rename from spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBTest.java rename to spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java index 427e182d9e..e036a4f3c1 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBTest.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/JpaMultipleDBIntegrationTest.java @@ -15,13 +15,11 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { UserConfig.class, ProductConfig.class }) -@TransactionConfiguration -public class JpaMultipleDBTest { +public class JpaMultipleDBIntegrationTest { @Autowired private UserRepository userRepository; diff --git a/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java b/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java index 919171de9f..aa2dfb5293 100644 --- a/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java +++ b/spring-jpa/src/test/java/org/baeldung/persistence/service/PersistenceTestSuite.java @@ -7,10 +7,9 @@ import org.junit.runners.Suite; @Suite.SuiteClasses({ // @formatter:off FooPaginationPersistenceIntegrationTest.class ,FooServicePersistenceIntegrationTest.class - ,FooServiceSortingTests.class - ,JpaMultipleDBTest.class - // manual only - // ,FooServiceSortingWitNullsManualTest.class + ,FooServiceSortingIntegrationTest.class + ,JpaMultipleDBIntegrationTest.class + ,FooServiceSortingWitNullsManualIntegrationTest.class }) // @formatter:on public class PersistenceTestSuite { // diff --git a/spring-mvc-java/pom.xml b/spring-mvc-java/pom.xml index f53a07264d..e796099190 100644 --- a/spring-mvc-java/pom.xml +++ b/spring-mvc-java/pom.xml @@ -17,6 +17,28 @@ spring-webmvc ${org.springframework.version} + + org.springframework + spring-websocket + ${org.springframework.version} + + + org.springframework + spring-messaging + ${org.springframework.version} + + + + com.fasterxml.jackson.core + jackson-core + 2.7.3 + + + com.fasterxml.jackson.core + jackson-databind + 2.7.3 + + javax.servlet diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/Message.java b/spring-mvc-java/src/main/java/com/baeldung/model/Message.java new file mode 100644 index 0000000000..c1f7f52215 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/model/Message.java @@ -0,0 +1,15 @@ +package com.baeldung.model; + +public class Message { + + private String from; + private String text; + + public String getText() { + return text; + } + + public String getFrom() { + return from; + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java b/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java new file mode 100644 index 0000000000..fc201ed016 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/model/OutputMessage.java @@ -0,0 +1,27 @@ +package com.baeldung.model; + +public class OutputMessage { + + private String from; + private String text; + private String time; + + public OutputMessage(final String from, final String text, final String time) { + + this.from = from; + this.text = text; + this.time = time; + } + + public String getText() { + return text; + } + + public String getTime() { + return time; + } + + public String getFrom() { + return from; + } +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java index c108a450ae..1b30479685 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ClientWebConfig.java @@ -25,69 +25,69 @@ import org.thymeleaf.templateresolver.ServletContextTemplateResolver; @Configuration public class ClientWebConfig extends WebMvcConfigurerAdapter { - public ClientWebConfig() { - super(); - } + public ClientWebConfig() { + super(); + } - // API + // API - @Override - public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + super.addViewControllers(registry); - registry.addViewController("/sample.html"); - } + registry.addViewController("/sample.html"); + } - @Bean - public ViewResolver thymeleafViewResolver() { - final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); - viewResolver.setTemplateEngine(templateEngine()); - viewResolver.setOrder(1); - return viewResolver; - } + @Bean + public ViewResolver thymeleafViewResolver() { + final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); + viewResolver.setTemplateEngine(templateEngine()); + viewResolver.setOrder(1); + return viewResolver; + } - @Bean - public ViewResolver viewResolver() { - final InternalResourceViewResolver bean = new InternalResourceViewResolver(); - bean.setViewClass(JstlView.class); - bean.setPrefix("/WEB-INF/view/"); - bean.setSuffix(".jsp"); - bean.setOrder(0); - return bean; - } + @Bean + public ViewResolver viewResolver() { + final InternalResourceViewResolver bean = new InternalResourceViewResolver(); + bean.setViewClass(JstlView.class); + bean.setPrefix("/WEB-INF/view/"); + bean.setSuffix(".jsp"); + bean.setOrder(0); + return bean; + } - @Bean - @Description("Thymeleaf template resolver serving HTML 5") - public ServletContextTemplateResolver templateResolver() { - final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); - templateResolver.setPrefix("/WEB-INF/templates/"); - templateResolver.setSuffix(".html"); - templateResolver.setTemplateMode("HTML5"); - return templateResolver; - } + @Bean + @Description("Thymeleaf template resolver serving HTML 5") + public ServletContextTemplateResolver templateResolver() { + final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); + templateResolver.setPrefix("/WEB-INF/templates/"); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode("HTML5"); + return templateResolver; + } - @Bean - @Description("Thymeleaf template engine with Spring integration") - public SpringTemplateEngine templateEngine() { - final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); - templateEngine.setTemplateResolver(templateResolver()); - final Set dialects = new HashSet<>(); - dialects.add(new CustomDialect()); - templateEngine.setAdditionalDialects(dialects); - return templateEngine; - } + @Bean + @Description("Thymeleaf template engine with Spring integration") + public SpringTemplateEngine templateEngine() { + final SpringTemplateEngine templateEngine = new SpringTemplateEngine(); + templateEngine.setTemplateResolver(templateResolver()); + final Set dialects = new HashSet<>(); + dialects.add(new CustomDialect()); + templateEngine.setAdditionalDialects(dialects); + return templateEngine; + } - @Bean - @Description("Spring message resolver") - public MessageSource messageSource() { - final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); - messageSource.setBasename("messages"); - return messageSource; - } + @Bean + @Description("Spring message resolver") + public MessageSource messageSource() { + final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); + messageSource.setBasename("messages"); + return messageSource; + } - @Override - public void addResourceHandlers(final ResourceHandlerRegistry registry) { - registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); - } + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } } \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java index 9780575678..498105ded1 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/ContentManagementWebConfig.java @@ -23,14 +23,8 @@ public class ContentManagementWebConfig extends WebMvcConfigurerAdapter { @Override public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) { - configurer.favorPathExtension(false). - favorParameter(true). - parameterName("mediaType"). - ignoreAcceptHeader(true). - useJaf(false). - defaultContentType(MediaType.APPLICATION_JSON). - mediaType("xml", MediaType.APPLICATION_XML). - mediaType("json", MediaType.APPLICATION_JSON); + configurer.favorPathExtension(false).favorParameter(true).parameterName("mediaType").ignoreAcceptHeader(true).useJaf(false).defaultContentType(MediaType.APPLICATION_JSON).mediaType("xml", MediaType.APPLICATION_XML).mediaType("json", + MediaType.APPLICATION_JSON); } @Override diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java index 4a11ba986c..f428fc3223 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/MainWebAppInitializer.java @@ -14,37 +14,37 @@ import org.springframework.web.servlet.DispatcherServlet; public class MainWebAppInitializer implements WebApplicationInitializer { - private static final String TMP_FOLDER = "C:/Users/ivan/Desktop/tmp"; - private static final int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; // 5 MB + private static final String TMP_FOLDER = "/tmp"; + private static final int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; // 5 MB - /** - * Register and configure all Servlet container components necessary to power the web application. - */ - @Override - public void onStartup(final ServletContext sc) throws ServletException { + /** + * Register and configure all Servlet container components necessary to power the web application. + */ + @Override + public void onStartup(final ServletContext sc) throws ServletException { - // Create the 'root' Spring application context - final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); - root.scan("com.baeldung.spring.web.config"); - // root.getEnvironment().setDefaultProfiles("embedded"); + // Create the 'root' Spring application context + final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); + root.scan("com.baeldung.spring.web.config"); + // root.getEnvironment().setDefaultProfiles("embedded"); - // Manages the lifecycle of the root application context - sc.addListener(new ContextLoaderListener(root)); + // Manages the lifecycle of the root application context + sc.addListener(new ContextLoaderListener(root)); - // Handles requests into the application - final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext())); - appServlet.setLoadOnStartup(1); + // Handles requests into the application + final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext())); + appServlet.setLoadOnStartup(1); - // final MultipartConfigElement multipartConfigElement = new - // MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE, - // MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2); - // - // appServlet.setMultipartConfig(multipartConfigElement); + // final MultipartConfigElement multipartConfigElement = new + // MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE, + // MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2); + // + // appServlet.setMultipartConfig(multipartConfigElement); - final Set mappingConflicts = appServlet.addMapping("/"); - if (!mappingConflicts.isEmpty()) { - throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278"); - } - } + final Set mappingConflicts = appServlet.addMapping("/"); + if (!mappingConflicts.isEmpty()) { + throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278"); + } + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 693fd74f74..ba7f35fd65 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -1,9 +1,15 @@ package com.baeldung.spring.web.config; +import java.util.ArrayList; +import java.util.List; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; +import org.springframework.http.MediaType; +import org.springframework.http.converter.ByteArrayHttpMessageConverter; +import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @@ -23,19 +29,19 @@ public class WebConfig extends WebMvcConfigurerAdapter { super(); } - // @Bean - // public StandardServletMultipartResolver multipartResolver() { - // return new StandardServletMultipartResolver(); - // } + // @Bean + // public StandardServletMultipartResolver multipartResolver() { + // return new StandardServletMultipartResolver(); + // } - @Bean(name = "multipartResolver") - public CommonsMultipartResolver multipartResolver() { + @Bean(name = "multipartResolver") + public CommonsMultipartResolver multipartResolver() { - final CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); - multipartResolver.setMaxUploadSize(100000); + final CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); + multipartResolver.setMaxUploadSize(100000); - return multipartResolver; - } + return multipartResolver; + } @Override public void addViewControllers(final ViewControllerRegistry registry) { @@ -69,4 +75,25 @@ public class WebConfig extends WebMvcConfigurerAdapter { return bean; } + @Override + public void extendMessageConverters(final List> converters) { + converters.add(byteArrayHttpMessageConverter()); + } + + @Bean + public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() { + final ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter(); + arrayHttpMessageConverter.setSupportedMediaTypes(getSupportedMediaTypes()); + + return arrayHttpMessageConverter; + } + + private List getSupportedMediaTypes() { + final List list = new ArrayList(); + list.add(MediaType.IMAGE_JPEG); + list.add(MediaType.IMAGE_PNG); + list.add(MediaType.APPLICATION_OCTET_STREAM); + + return list; + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java new file mode 100644 index 0000000000..6330041c60 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebSocketConfig.java @@ -0,0 +1,24 @@ +package com.baeldung.spring.web.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.simp.config.MessageBrokerRegistry; +import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; +import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; +import org.springframework.web.socket.config.annotation.StompEndpointRegistry; + +@Configuration +@EnableWebSocketMessageBroker +public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { + + @Override + public void configureMessageBroker(final MessageBrokerRegistry config) { + config.enableSimpleBroker("/topic"); + config.setApplicationDestinationPrefixes("/app"); + } + + @Override + public void registerStompEndpoints(final StompEndpointRegistry registry) { + registry.addEndpoint("/chat").withSockJS(); + } + +} \ No newline at end of file diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ChatController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/ChatController.java new file mode 100644 index 0000000000..f4bed1950b --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/ChatController.java @@ -0,0 +1,23 @@ +package com.baeldung.web.controller; + +import com.baeldung.model.Message; +import com.baeldung.model.OutputMessage; +import org.springframework.messaging.handler.annotation.MessageMapping; +import org.springframework.messaging.handler.annotation.SendTo; +import org.springframework.stereotype.Controller; + +import java.text.SimpleDateFormat; +import java.util.Date; + +@Controller +public class ChatController { + + @MessageMapping("/chat") + @SendTo("/topic/messages") + public OutputMessage send(final Message message) throws Exception { + + final String time = new SimpleDateFormat("HH:mm").format(new Date()); + return new OutputMessage(message.getFrom(), message.getText(), time); + } + +} diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/FileUploadController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/FileUploadController.java index bc9cf13c34..61bccb21aa 100644 --- a/spring-mvc-java/src/main/java/com/baeldung/web/controller/FileUploadController.java +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/FileUploadController.java @@ -10,23 +10,23 @@ import org.springframework.web.multipart.MultipartFile; @Controller public class FileUploadController { - @RequestMapping(value = "/fileUpload", method = RequestMethod.GET) - public String displayForm() { + @RequestMapping(value = "/fileUpload", method = RequestMethod.GET) + public String displayForm() { - return "fileUploadForm"; - } + return "fileUploadForm"; + } - @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) - public String submit(@RequestParam("file") final MultipartFile file, final ModelMap modelMap) { + @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) + public String submit(@RequestParam("file") final MultipartFile file, final ModelMap modelMap) { - modelMap.addAttribute("file", file); - return "fileUploadView"; - } + modelMap.addAttribute("file", file); + return "fileUploadView"; + } - @RequestMapping(value = "/uploadMultiFile", method = RequestMethod.POST) - public String submit(@RequestParam("files") final MultipartFile[] files, final ModelMap modelMap) { + @RequestMapping(value = "/uploadMultiFile", method = RequestMethod.POST) + public String submit(@RequestParam("files") final MultipartFile[] files, final ModelMap modelMap) { - modelMap.addAttribute("files", files); - return "fileUploadView"; - } + modelMap.addAttribute("files", files); + return "fileUploadView"; + } } diff --git a/spring-mvc-java/src/main/java/com/baeldung/web/controller/ImageController.java b/spring-mvc-java/src/main/java/com/baeldung/web/controller/ImageController.java new file mode 100644 index 0000000000..5a8a491989 --- /dev/null +++ b/spring-mvc-java/src/main/java/com/baeldung/web/controller/ImageController.java @@ -0,0 +1,27 @@ +package com.baeldung.web.controller; + +import java.io.IOException; +import java.io.InputStream; + +import javax.servlet.ServletContext; + +import org.apache.commons.io.IOUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +public class ImageController { + + @Autowired + ServletContext servletContext; + + @RequestMapping(value = "/image-byte-array", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) + public @ResponseBody byte[] getImageAsByteArray() throws IOException { + final InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg"); + return IOUtils.toByteArray(in); + } +} diff --git a/spring-mvc-java/src/main/webapp/WEB-INF/images/image-example.jpg b/spring-mvc-java/src/main/webapp/WEB-INF/images/image-example.jpg new file mode 100644 index 0000000000..219abe530f Binary files /dev/null and b/spring-mvc-java/src/main/webapp/WEB-INF/images/image-example.jpg differ diff --git a/spring-mvc-java/src/main/webapp/resources/chat.html b/spring-mvc-java/src/main/webapp/resources/chat.html new file mode 100644 index 0000000000..92a54534fd --- /dev/null +++ b/spring-mvc-java/src/main/webapp/resources/chat.html @@ -0,0 +1,88 @@ + + + Chat WebSocket + + + + + + + + + + +
+ + +
+ +
+
+
+ + +
+
+
+ + +

+
+
+ + + \ No newline at end of file diff --git a/spring-mvc-java/src/main/webapp/resources/js/sockjs-0.3.4.js b/spring-mvc-java/src/main/webapp/resources/js/sockjs-0.3.4.js new file mode 100644 index 0000000000..9f5b8f3deb --- /dev/null +++ b/spring-mvc-java/src/main/webapp/resources/js/sockjs-0.3.4.js @@ -0,0 +1,2378 @@ +/* SockJS client, version 0.3.4, http://sockjs.org, MIT License + +Copyright (c) 2011-2012 VMware, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ + +// JSON2 by Douglas Crockford (minified). +var JSON;JSON||(JSON={}),function(){function str(a,b){var c,d,e,f,g=gap,h,i=b[a];i&&typeof i=="object"&&typeof i.toJSON=="function"&&(i=i.toJSON(a)),typeof rep=="function"&&(i=rep.call(b,a,i));switch(typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i)return"null";gap+=indent,h=[];if(Object.prototype.toString.apply(i)==="[object Array]"){f=i.length;for(c=0;c 1) { + this._listeners[eventType] = arr.slice(0, idx).concat( arr.slice(idx+1) ); + } else { + delete this._listeners[eventType]; + } + return; + } + return; +}; + +REventTarget.prototype.dispatchEvent = function (event) { + var t = event.type; + var args = Array.prototype.slice.call(arguments, 0); + if (this['on'+t]) { + this['on'+t].apply(this, args); + } + if (this._listeners && t in this._listeners) { + for(var i=0; i < this._listeners[t].length; i++) { + this._listeners[t][i].apply(this, args); + } + } +}; +// [*] End of lib/reventtarget.js + + +// [*] Including lib/simpleevent.js +/* + * ***** BEGIN LICENSE BLOCK ***** + * Copyright (c) 2011-2012 VMware, Inc. + * + * For the license see COPYING. + * ***** END LICENSE BLOCK ***** + */ + +var SimpleEvent = function(type, obj) { + this.type = type; + if (typeof obj !== 'undefined') { + for(var k in obj) { + if (!obj.hasOwnProperty(k)) continue; + this[k] = obj[k]; + } + } +}; + +SimpleEvent.prototype.toString = function() { + var r = []; + for(var k in this) { + if (!this.hasOwnProperty(k)) continue; + var v = this[k]; + if (typeof v === 'function') v = '[function]'; + r.push(k + '=' + v); + } + return 'SimpleEvent(' + r.join(', ') + ')'; +}; +// [*] End of lib/simpleevent.js + + +// [*] Including lib/eventemitter.js +/* + * ***** BEGIN LICENSE BLOCK ***** + * Copyright (c) 2011-2012 VMware, Inc. + * + * For the license see COPYING. + * ***** END LICENSE BLOCK ***** + */ + +var EventEmitter = function(events) { + var that = this; + that._events = events || []; + that._listeners = {}; +}; +EventEmitter.prototype.emit = function(type) { + var that = this; + that._verifyType(type); + if (that._nuked) return; + + var args = Array.prototype.slice.call(arguments, 1); + if (that['on'+type]) { + that['on'+type].apply(that, args); + } + if (type in that._listeners) { + for(var i = 0; i < that._listeners[type].length; i++) { + that._listeners[type][i].apply(that, args); + } + } +}; + +EventEmitter.prototype.on = function(type, callback) { + var that = this; + that._verifyType(type); + if (that._nuked) return; + + if (!(type in that._listeners)) { + that._listeners[type] = []; + } + that._listeners[type].push(callback); +}; + +EventEmitter.prototype._verifyType = function(type) { + var that = this; + if (utils.arrIndexOf(that._events, type) === -1) { + utils.log('Event ' + JSON.stringify(type) + + ' not listed ' + JSON.stringify(that._events) + + ' in ' + that); + } +}; + +EventEmitter.prototype.nuke = function() { + var that = this; + that._nuked = true; + for(var i=0; i= 3000 && code <= 4999); +}; + +// See: http://www.erg.abdn.ac.uk/~gerrit/dccp/notes/ccid2/rto_estimator/ +// and RFC 2988. +utils.countRTO = function (rtt) { + var rto; + if (rtt > 100) { + rto = 3 * rtt; // rto > 300msec + } else { + rto = rtt + 200; // 200msec < rto <= 300msec + } + return rto; +} + +utils.log = function() { + if (_window.console && console.log && console.log.apply) { + console.log.apply(console, arguments); + } +}; + +utils.bind = function(fun, that) { + if (fun.bind) { + return fun.bind(that); + } else { + return function() { + return fun.apply(that, arguments); + }; + } +}; + +utils.flatUrl = function(url) { + return url.indexOf('?') === -1 && url.indexOf('#') === -1; +}; + +utils.amendUrl = function(url) { + var dl = _document.location; + if (!url) { + throw new Error('Wrong url for SockJS'); + } + if (!utils.flatUrl(url)) { + throw new Error('Only basic urls are supported in SockJS'); + } + + // '//abc' --> 'http://abc' + if (url.indexOf('//') === 0) { + url = dl.protocol + url; + } + // '/abc' --> 'http://localhost:80/abc' + if (url.indexOf('/') === 0) { + url = dl.protocol + '//' + dl.host + url; + } + // strip trailing slashes + url = url.replace(/[/]+$/,''); + return url; +}; + +// IE doesn't support [].indexOf. +utils.arrIndexOf = function(arr, obj){ + for(var i=0; i < arr.length; i++){ + if(arr[i] === obj){ + return i; + } + } + return -1; +}; + +utils.arrSkip = function(arr, obj) { + var idx = utils.arrIndexOf(arr, obj); + if (idx === -1) { + return arr.slice(); + } else { + var dst = arr.slice(0, idx); + return dst.concat(arr.slice(idx+1)); + } +}; + +// Via: https://gist.github.com/1133122/2121c601c5549155483f50be3da5305e83b8c5df +utils.isArray = Array.isArray || function(value) { + return {}.toString.call(value).indexOf('Array') >= 0 +}; + +utils.delay = function(t, fun) { + if(typeof t === 'function') { + fun = t; + t = 0; + } + return setTimeout(fun, t); +}; + + +// Chars worth escaping, as defined by Douglas Crockford: +// https://github.com/douglascrockford/JSON-js/blob/47a9882cddeb1e8529e07af9736218075372b8ac/json2.js#L196 +var json_escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + json_lookup = { +"\u0000":"\\u0000","\u0001":"\\u0001","\u0002":"\\u0002","\u0003":"\\u0003", +"\u0004":"\\u0004","\u0005":"\\u0005","\u0006":"\\u0006","\u0007":"\\u0007", +"\b":"\\b","\t":"\\t","\n":"\\n","\u000b":"\\u000b","\f":"\\f","\r":"\\r", +"\u000e":"\\u000e","\u000f":"\\u000f","\u0010":"\\u0010","\u0011":"\\u0011", +"\u0012":"\\u0012","\u0013":"\\u0013","\u0014":"\\u0014","\u0015":"\\u0015", +"\u0016":"\\u0016","\u0017":"\\u0017","\u0018":"\\u0018","\u0019":"\\u0019", +"\u001a":"\\u001a","\u001b":"\\u001b","\u001c":"\\u001c","\u001d":"\\u001d", +"\u001e":"\\u001e","\u001f":"\\u001f","\"":"\\\"","\\":"\\\\", +"\u007f":"\\u007f","\u0080":"\\u0080","\u0081":"\\u0081","\u0082":"\\u0082", +"\u0083":"\\u0083","\u0084":"\\u0084","\u0085":"\\u0085","\u0086":"\\u0086", +"\u0087":"\\u0087","\u0088":"\\u0088","\u0089":"\\u0089","\u008a":"\\u008a", +"\u008b":"\\u008b","\u008c":"\\u008c","\u008d":"\\u008d","\u008e":"\\u008e", +"\u008f":"\\u008f","\u0090":"\\u0090","\u0091":"\\u0091","\u0092":"\\u0092", +"\u0093":"\\u0093","\u0094":"\\u0094","\u0095":"\\u0095","\u0096":"\\u0096", +"\u0097":"\\u0097","\u0098":"\\u0098","\u0099":"\\u0099","\u009a":"\\u009a", +"\u009b":"\\u009b","\u009c":"\\u009c","\u009d":"\\u009d","\u009e":"\\u009e", +"\u009f":"\\u009f","\u00ad":"\\u00ad","\u0600":"\\u0600","\u0601":"\\u0601", +"\u0602":"\\u0602","\u0603":"\\u0603","\u0604":"\\u0604","\u070f":"\\u070f", +"\u17b4":"\\u17b4","\u17b5":"\\u17b5","\u200c":"\\u200c","\u200d":"\\u200d", +"\u200e":"\\u200e","\u200f":"\\u200f","\u2028":"\\u2028","\u2029":"\\u2029", +"\u202a":"\\u202a","\u202b":"\\u202b","\u202c":"\\u202c","\u202d":"\\u202d", +"\u202e":"\\u202e","\u202f":"\\u202f","\u2060":"\\u2060","\u2061":"\\u2061", +"\u2062":"\\u2062","\u2063":"\\u2063","\u2064":"\\u2064","\u2065":"\\u2065", +"\u2066":"\\u2066","\u2067":"\\u2067","\u2068":"\\u2068","\u2069":"\\u2069", +"\u206a":"\\u206a","\u206b":"\\u206b","\u206c":"\\u206c","\u206d":"\\u206d", +"\u206e":"\\u206e","\u206f":"\\u206f","\ufeff":"\\ufeff","\ufff0":"\\ufff0", +"\ufff1":"\\ufff1","\ufff2":"\\ufff2","\ufff3":"\\ufff3","\ufff4":"\\ufff4", +"\ufff5":"\\ufff5","\ufff6":"\\ufff6","\ufff7":"\\ufff7","\ufff8":"\\ufff8", +"\ufff9":"\\ufff9","\ufffa":"\\ufffa","\ufffb":"\\ufffb","\ufffc":"\\ufffc", +"\ufffd":"\\ufffd","\ufffe":"\\ufffe","\uffff":"\\uffff"}; + +// Some extra characters that Chrome gets wrong, and substitutes with +// something else on the wire. +var extra_escapable = /[\x00-\x1f\ud800-\udfff\ufffe\uffff\u0300-\u0333\u033d-\u0346\u034a-\u034c\u0350-\u0352\u0357-\u0358\u035c-\u0362\u0374\u037e\u0387\u0591-\u05af\u05c4\u0610-\u0617\u0653-\u0654\u0657-\u065b\u065d-\u065e\u06df-\u06e2\u06eb-\u06ec\u0730\u0732-\u0733\u0735-\u0736\u073a\u073d\u073f-\u0741\u0743\u0745\u0747\u07eb-\u07f1\u0951\u0958-\u095f\u09dc-\u09dd\u09df\u0a33\u0a36\u0a59-\u0a5b\u0a5e\u0b5c-\u0b5d\u0e38-\u0e39\u0f43\u0f4d\u0f52\u0f57\u0f5c\u0f69\u0f72-\u0f76\u0f78\u0f80-\u0f83\u0f93\u0f9d\u0fa2\u0fa7\u0fac\u0fb9\u1939-\u193a\u1a17\u1b6b\u1cda-\u1cdb\u1dc0-\u1dcf\u1dfc\u1dfe\u1f71\u1f73\u1f75\u1f77\u1f79\u1f7b\u1f7d\u1fbb\u1fbe\u1fc9\u1fcb\u1fd3\u1fdb\u1fe3\u1feb\u1fee-\u1fef\u1ff9\u1ffb\u1ffd\u2000-\u2001\u20d0-\u20d1\u20d4-\u20d7\u20e7-\u20e9\u2126\u212a-\u212b\u2329-\u232a\u2adc\u302b-\u302c\uaab2-\uaab3\uf900-\ufa0d\ufa10\ufa12\ufa15-\ufa1e\ufa20\ufa22\ufa25-\ufa26\ufa2a-\ufa2d\ufa30-\ufa6d\ufa70-\ufad9\ufb1d\ufb1f\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4e\ufff0-\uffff]/g, + extra_lookup; + +// JSON Quote string. Use native implementation when possible. +var JSONQuote = (JSON && JSON.stringify) || function(string) { + json_escapable.lastIndex = 0; + if (json_escapable.test(string)) { + string = string.replace(json_escapable, function(a) { + return json_lookup[a]; + }); + } + return '"' + string + '"'; +}; + +// This may be quite slow, so let's delay until user actually uses bad +// characters. +var unroll_lookup = function(escapable) { + var i; + var unrolled = {} + var c = [] + for(i=0; i<65536; i++) { + c.push( String.fromCharCode(i) ); + } + escapable.lastIndex = 0; + c.join('').replace(escapable, function (a) { + unrolled[ a ] = '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + return ''; + }); + escapable.lastIndex = 0; + return unrolled; +}; + +// Quote string, also taking care of unicode characters that browsers +// often break. Especially, take care of unicode surrogates: +// http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Surrogates +utils.quote = function(string) { + var quoted = JSONQuote(string); + + // In most cases this should be very fast and good enough. + extra_escapable.lastIndex = 0; + if(!extra_escapable.test(quoted)) { + return quoted; + } + + if(!extra_lookup) extra_lookup = unroll_lookup(extra_escapable); + + return quoted.replace(extra_escapable, function(a) { + return extra_lookup[a]; + }); +} + +var _all_protocols = ['websocket', + 'xdr-streaming', + 'xhr-streaming', + 'iframe-eventsource', + 'iframe-htmlfile', + 'xdr-polling', + 'xhr-polling', + 'iframe-xhr-polling', + 'jsonp-polling']; + +utils.probeProtocols = function() { + var probed = {}; + for(var i=0; i<_all_protocols.length; i++) { + var protocol = _all_protocols[i]; + // User can have a typo in protocol name. + probed[protocol] = SockJS[protocol] && + SockJS[protocol].enabled(); + } + return probed; +}; + +utils.detectProtocols = function(probed, protocols_whitelist, info) { + var pe = {}, + protocols = []; + if (!protocols_whitelist) protocols_whitelist = _all_protocols; + for(var i=0; i 0) { + maybe_push(protos); + } + } + } + + // 1. Websocket + if (info.websocket !== false) { + maybe_push(['websocket']); + } + + // 2. Streaming + if (pe['xhr-streaming'] && !info.null_origin) { + protocols.push('xhr-streaming'); + } else { + if (pe['xdr-streaming'] && !info.cookie_needed && !info.null_origin) { + protocols.push('xdr-streaming'); + } else { + maybe_push(['iframe-eventsource', + 'iframe-htmlfile']); + } + } + + // 3. Polling + if (pe['xhr-polling'] && !info.null_origin) { + protocols.push('xhr-polling'); + } else { + if (pe['xdr-polling'] && !info.cookie_needed && !info.null_origin) { + protocols.push('xdr-polling'); + } else { + maybe_push(['iframe-xhr-polling', + 'jsonp-polling']); + } + } + return protocols; +} +// [*] End of lib/utils.js + + +// [*] Including lib/dom.js +/* + * ***** BEGIN LICENSE BLOCK ***** + * Copyright (c) 2011-2012 VMware, Inc. + * + * For the license see COPYING. + * ***** END LICENSE BLOCK ***** + */ + +// May be used by htmlfile jsonp and transports. +var MPrefix = '_sockjs_global'; +utils.createHook = function() { + var window_id = 'a' + utils.random_string(8); + if (!(MPrefix in _window)) { + var map = {}; + _window[MPrefix] = function(window_id) { + if (!(window_id in map)) { + map[window_id] = { + id: window_id, + del: function() {delete map[window_id];} + }; + } + return map[window_id]; + } + } + return _window[MPrefix](window_id); +}; + + + +utils.attachMessage = function(listener) { + utils.attachEvent('message', listener); +}; +utils.attachEvent = function(event, listener) { + if (typeof _window.addEventListener !== 'undefined') { + _window.addEventListener(event, listener, false); + } else { + // IE quirks. + // According to: http://stevesouders.com/misc/test-postmessage.php + // the message gets delivered only to 'document', not 'window'. + _document.attachEvent("on" + event, listener); + // I get 'window' for ie8. + _window.attachEvent("on" + event, listener); + } +}; + +utils.detachMessage = function(listener) { + utils.detachEvent('message', listener); +}; +utils.detachEvent = function(event, listener) { + if (typeof _window.addEventListener !== 'undefined') { + _window.removeEventListener(event, listener, false); + } else { + _document.detachEvent("on" + event, listener); + _window.detachEvent("on" + event, listener); + } +}; + + +var on_unload = {}; +// Things registered after beforeunload are to be called immediately. +var after_unload = false; + +var trigger_unload_callbacks = function() { + for(var ref in on_unload) { + on_unload[ref](); + delete on_unload[ref]; + }; +}; + +var unload_triggered = function() { + if(after_unload) return; + after_unload = true; + trigger_unload_callbacks(); +}; + +// 'unload' alone is not reliable in opera within an iframe, but we +// can't use `beforeunload` as IE fires it on javascript: links. +utils.attachEvent('unload', unload_triggered); + +utils.unload_add = function(listener) { + var ref = utils.random_string(8); + on_unload[ref] = listener; + if (after_unload) { + utils.delay(trigger_unload_callbacks); + } + return ref; +}; +utils.unload_del = function(ref) { + if (ref in on_unload) + delete on_unload[ref]; +}; + + +utils.createIframe = function (iframe_url, error_callback) { + var iframe = _document.createElement('iframe'); + var tref, unload_ref; + var unattach = function() { + clearTimeout(tref); + // Explorer had problems with that. + try {iframe.onload = null;} catch (x) {} + iframe.onerror = null; + }; + var cleanup = function() { + if (iframe) { + unattach(); + // This timeout makes chrome fire onbeforeunload event + // within iframe. Without the timeout it goes straight to + // onunload. + setTimeout(function() { + if(iframe) { + iframe.parentNode.removeChild(iframe); + } + iframe = null; + }, 0); + utils.unload_del(unload_ref); + } + }; + var onerror = function(r) { + if (iframe) { + cleanup(); + error_callback(r); + } + }; + var post = function(msg, origin) { + try { + // When the iframe is not loaded, IE raises an exception + // on 'contentWindow'. + if (iframe && iframe.contentWindow) { + iframe.contentWindow.postMessage(msg, origin); + } + } catch (x) {}; + }; + + iframe.src = iframe_url; + iframe.style.display = 'none'; + iframe.style.position = 'absolute'; + iframe.onerror = function(){onerror('onerror');}; + iframe.onload = function() { + // `onload` is triggered before scripts on the iframe are + // executed. Give it few seconds to actually load stuff. + clearTimeout(tref); + tref = setTimeout(function(){onerror('onload timeout');}, 2000); + }; + _document.body.appendChild(iframe); + tref = setTimeout(function(){onerror('timeout');}, 15000); + unload_ref = utils.unload_add(cleanup); + return { + post: post, + cleanup: cleanup, + loaded: unattach + }; +}; + +utils.createHtmlfile = function (iframe_url, error_callback) { + var doc = new ActiveXObject('htmlfile'); + var tref, unload_ref; + var iframe; + var unattach = function() { + clearTimeout(tref); + }; + var cleanup = function() { + if (doc) { + unattach(); + utils.unload_del(unload_ref); + iframe.parentNode.removeChild(iframe); + iframe = doc = null; + CollectGarbage(); + } + }; + var onerror = function(r) { + if (doc) { + cleanup(); + error_callback(r); + } + }; + var post = function(msg, origin) { + try { + // When the iframe is not loaded, IE raises an exception + // on 'contentWindow'. + if (iframe && iframe.contentWindow) { + iframe.contentWindow.postMessage(msg, origin); + } + } catch (x) {}; + }; + + doc.open(); + doc.write('' + + 'document.domain="' + document.domain + '";' + + ''); + doc.close(); + doc.parentWindow[WPrefix] = _window[WPrefix]; + var c = doc.createElement('div'); + doc.body.appendChild(c); + iframe = doc.createElement('iframe'); + c.appendChild(iframe); + iframe.src = iframe_url; + tref = setTimeout(function(){onerror('timeout');}, 15000); + unload_ref = utils.unload_add(cleanup); + return { + post: post, + cleanup: cleanup, + loaded: unattach + }; +}; +// [*] End of lib/dom.js + + +// [*] Including lib/dom2.js +/* + * ***** BEGIN LICENSE BLOCK ***** + * Copyright (c) 2011-2012 VMware, Inc. + * + * For the license see COPYING. + * ***** END LICENSE BLOCK ***** + */ + +var AbstractXHRObject = function(){}; +AbstractXHRObject.prototype = new EventEmitter(['chunk', 'finish']); + +AbstractXHRObject.prototype._start = function(method, url, payload, opts) { + var that = this; + + try { + that.xhr = new XMLHttpRequest(); + } catch(x) {}; + + if (!that.xhr) { + try { + that.xhr = new _window.ActiveXObject('Microsoft.XMLHTTP'); + } catch(x) {}; + } + if (_window.ActiveXObject || _window.XDomainRequest) { + // IE8 caches even POSTs + url += ((url.indexOf('?') === -1) ? '?' : '&') + 't='+(+new Date); + } + + // Explorer tends to keep connection open, even after the + // tab gets closed: http://bugs.jquery.com/ticket/5280 + that.unload_ref = utils.unload_add(function(){that._cleanup(true);}); + try { + that.xhr.open(method, url, true); + } catch(e) { + // IE raises an exception on wrong port. + that.emit('finish', 0, ''); + that._cleanup(); + return; + }; + + if (!opts || !opts.no_credentials) { + // Mozilla docs says https://developer.mozilla.org/en/XMLHttpRequest : + // "This never affects same-site requests." + that.xhr.withCredentials = 'true'; + } + if (opts && opts.headers) { + for(var key in opts.headers) { + that.xhr.setRequestHeader(key, opts.headers[key]); + } + } + + that.xhr.onreadystatechange = function() { + if (that.xhr) { + var x = that.xhr; + switch (x.readyState) { + case 3: + // IE doesn't like peeking into responseText or status + // on Microsoft.XMLHTTP and readystate=3 + try { + var status = x.status; + var text = x.responseText; + } catch (x) {}; + // IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450 + if (status === 1223) status = 204; + + // IE does return readystate == 3 for 404 answers. + if (text && text.length > 0) { + that.emit('chunk', status, text); + } + break; + case 4: + var status = x.status; + // IE returns 1223 for 204: http://bugs.jquery.com/ticket/1450 + if (status === 1223) status = 204; + + that.emit('finish', status, x.responseText); + that._cleanup(false); + break; + } + } + }; + that.xhr.send(payload); +}; + +AbstractXHRObject.prototype._cleanup = function(abort) { + var that = this; + if (!that.xhr) return; + utils.unload_del(that.unload_ref); + + // IE needs this field to be a function + that.xhr.onreadystatechange = function(){}; + + if (abort) { + try { + that.xhr.abort(); + } catch(x) {}; + } + that.unload_ref = that.xhr = null; +}; + +AbstractXHRObject.prototype.close = function() { + var that = this; + that.nuke(); + that._cleanup(true); +}; + +var XHRCorsObject = utils.XHRCorsObject = function() { + var that = this, args = arguments; + utils.delay(function(){that._start.apply(that, args);}); +}; +XHRCorsObject.prototype = new AbstractXHRObject(); + +var XHRLocalObject = utils.XHRLocalObject = function(method, url, payload) { + var that = this; + utils.delay(function(){ + that._start(method, url, payload, { + no_credentials: true + }); + }); +}; +XHRLocalObject.prototype = new AbstractXHRObject(); + + + +// References: +// http://ajaxian.com/archives/100-line-ajax-wrapper +// http://msdn.microsoft.com/en-us/library/cc288060(v=VS.85).aspx +var XDRObject = utils.XDRObject = function(method, url, payload) { + var that = this; + utils.delay(function(){that._start(method, url, payload);}); +}; +XDRObject.prototype = new EventEmitter(['chunk', 'finish']); +XDRObject.prototype._start = function(method, url, payload) { + var that = this; + var xdr = new XDomainRequest(); + // IE caches even POSTs + url += ((url.indexOf('?') === -1) ? '?' : '&') + 't='+(+new Date); + + var onerror = xdr.ontimeout = xdr.onerror = function() { + that.emit('finish', 0, ''); + that._cleanup(false); + }; + xdr.onprogress = function() { + that.emit('chunk', 200, xdr.responseText); + }; + xdr.onload = function() { + that.emit('finish', 200, xdr.responseText); + that._cleanup(false); + }; + that.xdr = xdr; + that.unload_ref = utils.unload_add(function(){that._cleanup(true);}); + try { + // Fails with AccessDenied if port number is bogus + that.xdr.open(method, url); + that.xdr.send(payload); + } catch(x) { + onerror(); + } +}; + +XDRObject.prototype._cleanup = function(abort) { + var that = this; + if (!that.xdr) return; + utils.unload_del(that.unload_ref); + + that.xdr.ontimeout = that.xdr.onerror = that.xdr.onprogress = + that.xdr.onload = null; + if (abort) { + try { + that.xdr.abort(); + } catch(x) {}; + } + that.unload_ref = that.xdr = null; +}; + +XDRObject.prototype.close = function() { + var that = this; + that.nuke(); + that._cleanup(true); +}; + +// 1. Is natively via XHR +// 2. Is natively via XDR +// 3. Nope, but postMessage is there so it should work via the Iframe. +// 4. Nope, sorry. +utils.isXHRCorsCapable = function() { + if (_window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()) { + return 1; + } + // XDomainRequest doesn't work if page is served from file:// + if (_window.XDomainRequest && _document.domain) { + return 2; + } + if (IframeTransport.enabled()) { + return 3; + } + return 4; +}; +// [*] End of lib/dom2.js + + +// [*] Including lib/sockjs.js +/* + * ***** BEGIN LICENSE BLOCK ***** + * Copyright (c) 2011-2012 VMware, Inc. + * + * For the license see COPYING. + * ***** END LICENSE BLOCK ***** + */ + +var SockJS = function(url, dep_protocols_whitelist, options) { + if (this === _window) { + // makes `new` optional + return new SockJS(url, dep_protocols_whitelist, options); + } + + var that = this, protocols_whitelist; + that._options = {devel: false, debug: false, protocols_whitelist: [], + info: undefined, rtt: undefined}; + if (options) { + utils.objectExtend(that._options, options); + } + that._base_url = utils.amendUrl(url); + that._server = that._options.server || utils.random_number_string(1000); + if (that._options.protocols_whitelist && + that._options.protocols_whitelist.length) { + protocols_whitelist = that._options.protocols_whitelist; + } else { + // Deprecated API + if (typeof dep_protocols_whitelist === 'string' && + dep_protocols_whitelist.length > 0) { + protocols_whitelist = [dep_protocols_whitelist]; + } else if (utils.isArray(dep_protocols_whitelist)) { + protocols_whitelist = dep_protocols_whitelist + } else { + protocols_whitelist = null; + } + if (protocols_whitelist) { + that._debug('Deprecated API: Use "protocols_whitelist" option ' + + 'instead of supplying protocol list as a second ' + + 'parameter to SockJS constructor.'); + } + } + that._protocols = []; + that.protocol = null; + that.readyState = SockJS.CONNECTING; + that._ir = createInfoReceiver(that._base_url); + that._ir.onfinish = function(info, rtt) { + that._ir = null; + if (info) { + if (that._options.info) { + // Override if user supplies the option + info = utils.objectExtend(info, that._options.info); + } + if (that._options.rtt) { + rtt = that._options.rtt; + } + that._applyInfo(info, rtt, protocols_whitelist); + that._didClose(); + } else { + that._didClose(1002, 'Can\'t connect to server', true); + } + }; +}; +// Inheritance +SockJS.prototype = new REventTarget(); + +SockJS.version = "0.3.4"; + +SockJS.CONNECTING = 0; +SockJS.OPEN = 1; +SockJS.CLOSING = 2; +SockJS.CLOSED = 3; + +SockJS.prototype._debug = function() { + if (this._options.debug) + utils.log.apply(utils, arguments); +}; + +SockJS.prototype._dispatchOpen = function() { + var that = this; + if (that.readyState === SockJS.CONNECTING) { + if (that._transport_tref) { + clearTimeout(that._transport_tref); + that._transport_tref = null; + } + that.readyState = SockJS.OPEN; + that.dispatchEvent(new SimpleEvent("open")); + } else { + // The server might have been restarted, and lost track of our + // connection. + that._didClose(1006, "Server lost session"); + } +}; + +SockJS.prototype._dispatchMessage = function(data) { + var that = this; + if (that.readyState !== SockJS.OPEN) + return; + that.dispatchEvent(new SimpleEvent("message", {data: data})); +}; + +SockJS.prototype._dispatchHeartbeat = function(data) { + var that = this; + if (that.readyState !== SockJS.OPEN) + return; + that.dispatchEvent(new SimpleEvent('heartbeat', {})); +}; + +SockJS.prototype._didClose = function(code, reason, force) { + var that = this; + if (that.readyState !== SockJS.CONNECTING && + that.readyState !== SockJS.OPEN && + that.readyState !== SockJS.CLOSING) + throw new Error('INVALID_STATE_ERR'); + if (that._ir) { + that._ir.nuke(); + that._ir = null; + } + + if (that._transport) { + that._transport.doCleanup(); + that._transport = null; + } + + var close_event = new SimpleEvent("close", { + code: code, + reason: reason, + wasClean: utils.userSetCode(code)}); + + if (!utils.userSetCode(code) && + that.readyState === SockJS.CONNECTING && !force) { + if (that._try_next_protocol(close_event)) { + return; + } + close_event = new SimpleEvent("close", {code: 2000, + reason: "All transports failed", + wasClean: false, + last_event: close_event}); + } + that.readyState = SockJS.CLOSED; + + utils.delay(function() { + that.dispatchEvent(close_event); + }); +}; + +SockJS.prototype._didMessage = function(data) { + var that = this; + var type = data.slice(0, 1); + switch(type) { + case 'o': + that._dispatchOpen(); + break; + case 'a': + var payload = JSON.parse(data.slice(1) || '[]'); + for(var i=0; i < payload.length; i++){ + that._dispatchMessage(payload[i]); + } + break; + case 'm': + var payload = JSON.parse(data.slice(1) || 'null'); + that._dispatchMessage(payload); + break; + case 'c': + var payload = JSON.parse(data.slice(1) || '[]'); + that._didClose(payload[0], payload[1]); + break; + case 'h': + that._dispatchHeartbeat(); + break; + } +}; + +SockJS.prototype._try_next_protocol = function(close_event) { + var that = this; + if (that.protocol) { + that._debug('Closed transport:', that.protocol, ''+close_event); + that.protocol = null; + } + if (that._transport_tref) { + clearTimeout(that._transport_tref); + that._transport_tref = null; + } + + while(1) { + var protocol = that.protocol = that._protocols.shift(); + if (!protocol) { + return false; + } + // Some protocols require access to `body`, what if were in + // the `head`? + if (SockJS[protocol] && + SockJS[protocol].need_body === true && + (!_document.body || + (typeof _document.readyState !== 'undefined' + && _document.readyState !== 'complete'))) { + that._protocols.unshift(protocol); + that.protocol = 'waiting-for-load'; + utils.attachEvent('load', function(){ + that._try_next_protocol(); + }); + return true; + } + + if (!SockJS[protocol] || + !SockJS[protocol].enabled(that._options)) { + that._debug('Skipping transport:', protocol); + } else { + var roundTrips = SockJS[protocol].roundTrips || 1; + var to = ((that._options.rto || 0) * roundTrips) || 5000; + that._transport_tref = utils.delay(to, function() { + if (that.readyState === SockJS.CONNECTING) { + // I can't understand how it is possible to run + // this timer, when the state is CLOSED, but + // apparently in IE everythin is possible. + that._didClose(2007, "Transport timeouted"); + } + }); + + var connid = utils.random_string(8); + var trans_url = that._base_url + '/' + that._server + '/' + connid; + that._debug('Opening transport:', protocol, ' url:'+trans_url, + ' RTO:'+that._options.rto); + that._transport = new SockJS[protocol](that, trans_url, + that._base_url); + return true; + } + } +}; + +SockJS.prototype.close = function(code, reason) { + var that = this; + if (code && !utils.userSetCode(code)) + throw new Error("INVALID_ACCESS_ERR"); + if(that.readyState !== SockJS.CONNECTING && + that.readyState !== SockJS.OPEN) { + return false; + } + that.readyState = SockJS.CLOSING; + that._didClose(code || 1000, reason || "Normal closure"); + return true; +}; + +SockJS.prototype.send = function(data) { + var that = this; + if (that.readyState === SockJS.CONNECTING) + throw new Error('INVALID_STATE_ERR'); + if (that.readyState === SockJS.OPEN) { + that._transport.doSend(utils.quote('' + data)); + } + return true; +}; + +SockJS.prototype._applyInfo = function(info, rtt, protocols_whitelist) { + var that = this; + that._options.info = info; + that._options.rtt = rtt; + that._options.rto = utils.countRTO(rtt); + that._options.info.null_origin = !_document.domain; + var probed = utils.probeProtocols(); + that._protocols = utils.detectProtocols(probed, protocols_whitelist, info); +}; +// [*] End of lib/sockjs.js + + +// [*] Including lib/trans-websocket.js +/* + * ***** BEGIN LICENSE BLOCK ***** + * Copyright (c) 2011-2012 VMware, Inc. + * + * For the license see COPYING. + * ***** END LICENSE BLOCK ***** + */ + +var WebSocketTransport = SockJS.websocket = function(ri, trans_url) { + var that = this; + var url = trans_url + '/websocket'; + if (url.slice(0, 5) === 'https') { + url = 'wss' + url.slice(5); + } else { + url = 'ws' + url.slice(4); + } + that.ri = ri; + that.url = url; + var Constructor = _window.WebSocket || _window.MozWebSocket; + + that.ws = new Constructor(that.url); + that.ws.onmessage = function(e) { + that.ri._didMessage(e.data); + }; + // Firefox has an interesting bug. If a websocket connection is + // created after onunload, it stays alive even when user + // navigates away from the page. In such situation let's lie - + // let's not open the ws connection at all. See: + // https://github.com/sockjs/sockjs-client/issues/28 + // https://bugzilla.mozilla.org/show_bug.cgi?id=696085 + that.unload_ref = utils.unload_add(function(){that.ws.close()}); + that.ws.onclose = function() { + that.ri._didMessage(utils.closeFrame(1006, "WebSocket connection broken")); + }; +}; + +WebSocketTransport.prototype.doSend = function(data) { + this.ws.send('[' + data + ']'); +}; + +WebSocketTransport.prototype.doCleanup = function() { + var that = this; + var ws = that.ws; + if (ws) { + ws.onmessage = ws.onclose = null; + ws.close(); + utils.unload_del(that.unload_ref); + that.unload_ref = that.ri = that.ws = null; + } +}; + +WebSocketTransport.enabled = function() { + return !!(_window.WebSocket || _window.MozWebSocket); +}; + +// In theory, ws should require 1 round trip. But in chrome, this is +// not very stable over SSL. Most likely a ws connection requires a +// separate SSL connection, in which case 2 round trips are an +// absolute minumum. +WebSocketTransport.roundTrips = 2; +// [*] End of lib/trans-websocket.js + + +// [*] Including lib/trans-sender.js +/* + * ***** BEGIN LICENSE BLOCK ***** + * Copyright (c) 2011-2012 VMware, Inc. + * + * For the license see COPYING. + * ***** END LICENSE BLOCK ***** + */ + +var BufferedSender = function() {}; +BufferedSender.prototype.send_constructor = function(sender) { + var that = this; + that.send_buffer = []; + that.sender = sender; +}; +BufferedSender.prototype.doSend = function(message) { + var that = this; + that.send_buffer.push(message); + if (!that.send_stop) { + that.send_schedule(); + } +}; + +// For polling transports in a situation when in the message callback, +// new message is being send. If the sending connection was started +// before receiving one, it is possible to saturate the network and +// timeout due to the lack of receiving socket. To avoid that we delay +// sending messages by some small time, in order to let receiving +// connection be started beforehand. This is only a halfmeasure and +// does not fix the big problem, but it does make the tests go more +// stable on slow networks. +BufferedSender.prototype.send_schedule_wait = function() { + var that = this; + var tref; + that.send_stop = function() { + that.send_stop = null; + clearTimeout(tref); + }; + tref = utils.delay(25, function() { + that.send_stop = null; + that.send_schedule(); + }); +}; + +BufferedSender.prototype.send_schedule = function() { + var that = this; + if (that.send_buffer.length > 0) { + var payload = '[' + that.send_buffer.join(',') + ']'; + that.send_stop = that.sender(that.trans_url, payload, function(success, abort_reason) { + that.send_stop = null; + if (success === false) { + that.ri._didClose(1006, 'Sending error ' + abort_reason); + } else { + that.send_schedule_wait(); + } + }); + that.send_buffer = []; + } +}; + +BufferedSender.prototype.send_destructor = function() { + var that = this; + if (that._send_stop) { + that._send_stop(); + } + that._send_stop = null; +}; + +var jsonPGenericSender = function(url, payload, callback) { + var that = this; + + if (!('_send_form' in that)) { + var form = that._send_form = _document.createElement('form'); + var area = that._send_area = _document.createElement('textarea'); + area.name = 'd'; + form.style.display = 'none'; + form.style.position = 'absolute'; + form.method = 'POST'; + form.enctype = 'application/x-www-form-urlencoded'; + form.acceptCharset = "UTF-8"; + form.appendChild(area); + _document.body.appendChild(form); + } + var form = that._send_form; + var area = that._send_area; + var id = 'a' + utils.random_string(8); + form.target = id; + form.action = url + '/jsonp_send?i=' + id; + + var iframe; + try { + // ie6 dynamic iframes with target="" support (thanks Chris Lambacher) + iframe = _document.createElement('