diff --git a/.mvn/jvm.config b/.mvn/jvm.config new file mode 100644 index 0000000000..32599cefea --- /dev/null +++ b/.mvn/jvm.config @@ -0,0 +1,10 @@ +--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED +--add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED +--add-opens jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED +--add-opens jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED diff --git a/pom.xml b/pom.xml index b259171a3c..9076835948 100644 --- a/pom.xml +++ b/pom.xml @@ -181,7 +181,40 @@ ${java.version} -parameters + + -XDcompilePolicy=simple + --should-stop=ifError=FLOW + + -Xplugin:ErrorProne + -Xep:CollectionUndefinedEquality:OFF + -Xep:DefaultCharset:OFF + -Xep:DirectInvocationOnMock:OFF + -Xep:EqualsGetClass:OFF + -Xep:Finally:OFF + -Xep:HidingField:OFF + -Xep:InlineMeSuggester:OFF + -Xep:JavaTimeDefaultTimeZone:OFF + -Xep:JdkObsolete:OFF + -Xep:MissingSummary:OFF + -Xep:MixedMutabilityReturnType:OFF + -Xep:MutablePublicArray:OFF + -Xep:NonAtomicVolatileUpdate:OFF + -Xep:ReferenceEquality:OFF + -Xep:StringCaseLocaleUsage:OFF + -Xep:StringSplitter:OFF + -Xep:SynchronizeOnNonFinalField:OFF + -Xep:UndefinedEquals:OFF + -Xep:UnnecessaryStringBuilder:OFF + + true + + + com.google.errorprone + error_prone_core + 2.38.0 + + diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/Entity.java b/spring-batch-core/src/main/java/org/springframework/batch/core/Entity.java index 6bcc5818ab..78e3e2bcb3 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/Entity.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/Entity.java @@ -146,7 +146,7 @@ public boolean equals(Object other) { @Override public int hashCode() { if (id == null) { - return super.hashCode(); + return System.identityHashCode(this); } return 39 + 87 * id.hashCode(); } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/JobExecution.java b/spring-batch-core/src/main/java/org/springframework/batch/core/JobExecution.java index c595f43e40..8a37b20bc3 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/JobExecution.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/JobExecution.java @@ -18,6 +18,7 @@ import java.io.IOException; import java.io.ObjectInputStream; +import java.time.Clock; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collection; @@ -203,7 +204,7 @@ public void upgradeStatus(BatchStatus status) { /** * Convenience getter for the {@code id} of the enclosing job. Useful for DAO * implementations. - * @return the @{code id} of the enclosing job. + * @return the {@code id} of the enclosing job. */ public Long getJobId() { if (jobInstance != null) { diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/JobParameters.java b/spring-batch-core/src/main/java/org/springframework/batch/core/JobParameters.java index a5e54b0c65..5ddf610506 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/JobParameters.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/JobParameters.java @@ -373,7 +373,7 @@ public String toString() { for (Map.Entry> entry : this.parameters.entrySet()) { parameters.add(String.format("'%s':'%s'", entry.getKey(), entry.getValue())); } - return new StringBuilder("{").append(String.join(",", parameters)).append("}").toString(); + return "{" + String.join(",", parameters) + "}"; } } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/StepExecution.java b/spring-batch-core/src/main/java/org/springframework/batch/core/StepExecution.java index 1bf5164778..5f3a3f2115 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/StepExecution.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/StepExecution.java @@ -492,7 +492,7 @@ public boolean equals(Object obj) { return super.equals(obj); } - return stepName.equals(other.getStepName()) && (jobExecutionId.equals(other.getJobExecutionId())) + return stepName.equals(other.getStepName()) && jobExecutionId.equals(other.getJobExecutionId()) && getId().equals(other.getId()); } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/annotation/BatchObservabilityBeanPostProcessor.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/annotation/BatchObservabilityBeanPostProcessor.java index bc3d35159e..9d2bfb844b 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/annotation/BatchObservabilityBeanPostProcessor.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/annotation/BatchObservabilityBeanPostProcessor.java @@ -50,11 +50,11 @@ public Object postProcessAfterInitialization(Object bean, String beanName) throw try { if (bean instanceof AbstractJob || bean instanceof AbstractStep) { ObservationRegistry observationRegistry = this.beanFactory.getBean(ObservationRegistry.class); - if (bean instanceof AbstractJob) { - ((AbstractJob) bean).setObservationRegistry(observationRegistry); + if (bean instanceof AbstractJob job) { + job.setObservationRegistry(observationRegistry); } - if (bean instanceof AbstractStep) { - ((AbstractStep) bean).setObservationRegistry(observationRegistry); + if (bean instanceof AbstractStep step) { + step.setObservationRegistry(observationRegistry); } } } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/annotation/BatchRegistrar.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/annotation/BatchRegistrar.java index 1c3164da6c..09aed271dc 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/annotation/BatchRegistrar.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/annotation/BatchRegistrar.java @@ -48,8 +48,6 @@ class BatchRegistrar implements ImportBeanDefinitionRegistrar { private static final Log LOGGER = LogFactory.getLog(BatchRegistrar.class); - private static final String MISSING_ANNOTATION_ERROR_MESSAGE = "EnableBatchProcessing is not present on importing class '%s' as expected"; - private static final String JOB_REPOSITORY = "jobRepository"; private static final String JOB_REGISTRY = "jobRegistry"; @@ -77,7 +75,8 @@ public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, B private void validateState(AnnotationMetadata importingClassMetadata) { if (!importingClassMetadata.isAnnotated(EnableBatchProcessing.class.getName())) { String className = importingClassMetadata.getClassName(); - String errorMessage = String.format(MISSING_ANNOTATION_ERROR_MESSAGE, className); + String errorMessage = "EnableBatchProcessing is not present on importing class '%s' as expected" + .formatted(className); throw new IllegalStateException(errorMessage); } } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/AbstractApplicationContextFactory.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/AbstractApplicationContextFactory.java index 535886f96c..9ef7ef72d0 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/AbstractApplicationContextFactory.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/AbstractApplicationContextFactory.java @@ -19,6 +19,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.List; import org.apache.commons.logging.Log; @@ -196,13 +197,11 @@ protected void prepareContext(ConfigurableApplicationContext parent, Configurabl protected void prepareBeanFactory(ConfigurableListableBeanFactory parent, ConfigurableListableBeanFactory beanFactory) { if (copyConfiguration && parent != null) { - List parentPostProcessors = new ArrayList<>(); - List childPostProcessors = new ArrayList<>(); - - childPostProcessors.addAll(beanFactory instanceof AbstractBeanFactory - ? ((AbstractBeanFactory) beanFactory).getBeanPostProcessors() : new ArrayList<>()); - parentPostProcessors.addAll(parent instanceof AbstractBeanFactory - ? ((AbstractBeanFactory) parent).getBeanPostProcessors() : new ArrayList<>()); + List childPostProcessors = new ArrayList<>( + beanFactory instanceof AbstractBeanFactory factory ? factory.getBeanPostProcessors() + : new ArrayList<>()); + List parentPostProcessors = new ArrayList<>(parent instanceof AbstractBeanFactory factory + ? factory.getBeanPostProcessors() : new ArrayList<>()); try { Class applicationContextAwareProcessorClass = ClassUtils.forName( @@ -237,8 +236,8 @@ protected void prepareBeanFactory(ConfigurableListableBeanFactory parent, beanFactory.copyConfigurationFrom(parent); - List beanPostProcessors = beanFactory instanceof AbstractBeanFactory - ? ((AbstractBeanFactory) beanFactory).getBeanPostProcessors() : new ArrayList<>(); + List beanPostProcessors = beanFactory instanceof AbstractBeanFactory abstractBeanFactory + ? abstractBeanFactory.getBeanPostProcessors() : new ArrayList<>(); beanPostProcessors.clear(); beanPostProcessors.addAll(aggregatedPostProcessors); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrar.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrar.java index e8496b83d6..c76ee7b9dd 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrar.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrar.java @@ -79,8 +79,8 @@ public void setApplicationContext(ApplicationContext applicationContext) { * use */ public void addApplicationContextFactory(ApplicationContextFactory applicationContextFactory) { - if (applicationContextFactory instanceof ApplicationContextAware) { - ((ApplicationContextAware) applicationContextFactory).setApplicationContext(applicationContext); + if (applicationContextFactory instanceof ApplicationContextAware applicationContextAware) { + applicationContextAware.setApplicationContext(applicationContext); } this.applicationContextFactories.add(applicationContextFactory); } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/DefaultJobLoader.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/DefaultJobLoader.java index 4dde8ea152..3cf8ee41e1 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/DefaultJobLoader.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/DefaultJobLoader.java @@ -255,11 +255,11 @@ private void doRegister(ConfigurableApplicationContext context, Job job) throws jobRegistry.register(jobFactory); if (stepRegistry != null) { - if (!(job instanceof StepLocator)) { + if (!(job instanceof StepLocator stepLocator)) { throw new UnsupportedOperationException("Cannot locate steps from a Job that is not a StepLocator: job=" + job.getName() + " does not implement StepLocator"); } - stepRegistry.register(job.getName(), getSteps((StepLocator) job, context)); + stepRegistry.register(job.getName(), getSteps(stepLocator, context)); } } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/GenericApplicationContextFactory.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/GenericApplicationContextFactory.java index a9074f6671..b523181eee 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/GenericApplicationContextFactory.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/GenericApplicationContextFactory.java @@ -126,7 +126,7 @@ protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { GenericApplicationContextFactory.this.prepareBeanFactory(parentBeanFactory, beanFactory); for (Class cls : getBeanFactoryPostProcessorClasses()) { for (String name : parent.getBeanNamesForType(cls)) { - beanFactory.registerSingleton(name, (parent.getBean(name))); + beanFactory.registerSingleton(name, parent.getBean(name)); } } } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/GroupAwareJob.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/GroupAwareJob.java index 2ea527202c..68dca95553 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/GroupAwareJob.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/support/GroupAwareJob.java @@ -99,8 +99,8 @@ public JobParametersValidator getJobParametersValidator() { @Override public boolean equals(Object obj) { - if (obj instanceof GroupAwareJob) { - return ((GroupAwareJob) obj).delegate.equals(delegate); + if (obj instanceof GroupAwareJob groupAwareJob) { + return groupAwareJob.delegate.equals(delegate); } return false; } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/AbstractFlowParser.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/AbstractFlowParser.java index 876a9ed2ce..c378258a91 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/AbstractFlowParser.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/AbstractFlowParser.java @@ -404,7 +404,7 @@ protected static Collection createTransition(FlowExecutionStatus endBuilder.addConstructorArgValue(exitCodeExists ? exitCode : status.getName()); String endName = (status == FlowExecutionStatus.STOPPED ? STOP_ELE - : status == FlowExecutionStatus.FAILED ? FAIL_ELE : END_ELE) + (endCounter++); + : status == FlowExecutionStatus.FAILED ? FAIL_ELE : END_ELE) + endCounter++; endBuilder.addConstructorArgValue(endName); endBuilder.addConstructorArgValue(abandon); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/AbstractStepParser.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/AbstractStepParser.java index c12eaf8633..84e85be51e 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/AbstractStepParser.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/AbstractStepParser.java @@ -118,16 +118,13 @@ protected AbstractBeanDefinition parseStep(Element stepElement, ParserContext pa new TaskletParser().parseTasklet(stepElement, nestedElement, bd, parserContext, stepUnderspecified); } else if (FLOW_ELE.equals(name)) { - boolean stepUnderspecified = CoreNamespaceUtils.isUnderspecified(stepElement); - parseFlow(stepElement, nestedElement, bd, parserContext, stepUnderspecified); + parseFlow(stepElement, nestedElement, bd); } else if (PARTITION_ELE.equals(name)) { - boolean stepUnderspecified = CoreNamespaceUtils.isUnderspecified(stepElement); - parsePartition(stepElement, nestedElement, bd, parserContext, stepUnderspecified, jobFactoryRef); + parsePartition(stepElement, nestedElement, bd, parserContext, jobFactoryRef); } else if (JOB_ELE.equals(name)) { - boolean stepUnderspecified = CoreNamespaceUtils.isUnderspecified(stepElement); - parseJob(stepElement, nestedElement, bd, parserContext, stepUnderspecified); + parseJob(nestedElement, bd, parserContext); } else if ("description".equals(name)) { bd.setDescription(nestedElement.getTextContent()); @@ -199,7 +196,7 @@ else if (ns.equals("http://www.springframework.org/schema/batch")) { } private void parsePartition(Element stepElement, Element partitionElement, AbstractBeanDefinition bd, - ParserContext parserContext, boolean stepUnderspecified, String jobFactoryRef) { + ParserContext parserContext, String jobFactoryRef) { bd.setBeanClass(StepParserStepFactoryBean.class); bd.setAttribute("isNamespaceStep", true); @@ -258,8 +255,7 @@ else if (inlineStepElement != null) { } - private void parseJob(Element stepElement, Element jobElement, AbstractBeanDefinition bd, - ParserContext parserContext, boolean stepUnderspecified) { + private void parseJob(Element jobElement, AbstractBeanDefinition bd, ParserContext parserContext) { bd.setBeanClass(StepParserStepFactoryBean.class); bd.setAttribute("isNamespaceStep", true); @@ -285,8 +281,7 @@ private void parseJob(Element stepElement, Element jobElement, AbstractBeanDefin } - private void parseFlow(Element stepElement, Element flowElement, AbstractBeanDefinition bd, - ParserContext parserContext, boolean stepUnderspecified) { + private void parseFlow(Element stepElement, Element flowElement, AbstractBeanDefinition bd) { bd.setBeanClass(StepParserStepFactoryBean.class); bd.setAttribute("isNamespaceStep", true); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/CoreNamespacePostProcessor.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/CoreNamespacePostProcessor.java index 7f250d389c..31486f8cf6 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/CoreNamespacePostProcessor.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/CoreNamespacePostProcessor.java @@ -115,15 +115,13 @@ public Object postProcessBeforeInitialization(Object bean, String beanName) thro * @return the bean with default collaborators injected into it */ private Object injectDefaults(Object bean) { - if (bean instanceof JobParserJobFactoryBean) { - JobParserJobFactoryBean fb = (JobParserJobFactoryBean) bean; + if (bean instanceof JobParserJobFactoryBean fb) { JobRepository jobRepository = fb.getJobRepository(); if (jobRepository == null) { fb.setJobRepository((JobRepository) applicationContext.getBean(DEFAULT_JOB_REPOSITORY_NAME)); } } - else if (bean instanceof StepParserStepFactoryBean) { - StepParserStepFactoryBean fb = (StepParserStepFactoryBean) bean; + else if (bean instanceof StepParserStepFactoryBean fb) { JobRepository jobRepository = fb.getJobRepository(); if (jobRepository == null) { fb.setJobRepository((JobRepository) applicationContext.getBean(DEFAULT_JOB_REPOSITORY_NAME)); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/ExceptionElementParser.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/ExceptionElementParser.java index 382a7b6d97..de8aff9119 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/ExceptionElementParser.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/ExceptionElementParser.java @@ -32,8 +32,8 @@ public ManagedMap parse(Element element, ParserContex if (children.size() == 1) { ManagedMap map = new ManagedMap<>(); Element exceptionClassesElement = children.get(0); - addExceptionClasses("include", true, exceptionClassesElement, map, parserContext); - addExceptionClasses("exclude", false, exceptionClassesElement, map, parserContext); + addExceptionClasses("include", true, exceptionClassesElement, map); + addExceptionClasses("exclude", false, exceptionClassesElement, map); map.put(new TypedStringValue(ForceRollbackForWriteSkipException.class.getName(), Class.class), true); return map; } @@ -46,7 +46,7 @@ else if (children.size() > 1) { } private void addExceptionClasses(String elementName, boolean include, Element exceptionClassesElement, - ManagedMap map, ParserContext parserContext) { + ManagedMap map) { for (Element child : DomUtils.getChildElementsByTagName(exceptionClassesElement, elementName)) { String className = child.getAttribute("class"); map.put(new TypedStringValue(className, Class.class), include); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/JobParser.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/JobParser.java index 8254cd66d8..1fe24649f5 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/JobParser.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/JobParser.java @@ -103,7 +103,7 @@ protected void doParse(Element element, ParserContext parserContext, BeanDefinit builder.addPropertyValue("restartable", restartableAttribute); } - String incrementer = (element.getAttribute("incrementer")); + String incrementer = element.getAttribute("incrementer"); if (StringUtils.hasText(incrementer)) { builder.addPropertyReference("jobParametersIncrementer", incrementer); } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/SimpleFlowFactoryBean.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/SimpleFlowFactoryBean.java index 216935b2ef..85fc80fe1d 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/SimpleFlowFactoryBean.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/SimpleFlowFactoryBean.java @@ -205,7 +205,7 @@ public FlowExecutionStatus handle(FlowExecutor executor) throws Exception { @Override public Collection getFlows() { - return (state instanceof FlowHolder) ? ((FlowHolder) state).getFlows() : Collections.emptyList(); + return (state instanceof FlowHolder flowHolder) ? flowHolder.getFlows() : Collections.emptyList(); } } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/StepParserStepFactoryBean.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/StepParserStepFactoryBean.java index 187bda9a31..a1e3e95bd1 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/StepParserStepFactoryBean.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/StepParserStepFactoryBean.java @@ -273,8 +273,8 @@ protected void enhanceCommonStep(StepBuilderHelper builder) { builder.startLimit(startLimit); } for (Object listener : stepExecutionListeners) { - if (listener instanceof StepExecutionListener) { - builder.listener((StepExecutionListener) listener); + if (listener instanceof StepExecutionListener stepExecutionListener) { + builder.listener(stepExecutionListener); } } } @@ -566,16 +566,16 @@ private void validateDependency(String dependentName, Object dependentValue, Str * @return {@code true} if the object has a value */ private boolean isPresent(Object o) { - if (o instanceof Integer) { - return isPositive((Integer) o); + if (o instanceof Integer i) { + return isPositive(i); } - if (o instanceof Collection) { - return !((Collection) o).isEmpty(); + if (o instanceof Collection collection) { + return !collection.isEmpty(); } - if (o instanceof Map) { - return !((Map) o).isEmpty(); + if (o instanceof Map map) { + return !map.isEmpty(); } - return o != null; + return true; } /** diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/TaskletParser.java b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/TaskletParser.java index a1a6668579..0f316b81ed 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/TaskletParser.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/configuration/xml/TaskletParser.java @@ -213,7 +213,7 @@ private void handleExceptionElement(Element element, ParserContext parserContext ManagedList list = new ManagedList<>(); list.setMergeEnabled(exceptionClassesElement.hasAttribute(MERGE_ATTR) && Boolean.parseBoolean(exceptionClassesElement.getAttribute(MERGE_ATTR))); - addExceptionClasses("include", exceptionClassesElement, list, parserContext); + addExceptionClasses("include", exceptionClassesElement, list); propertyValues.addPropertyValue(propertyName, list); } else if (children.size() > 1) { @@ -224,7 +224,7 @@ else if (children.size() > 1) { } private void addExceptionClasses(String elementName, Element exceptionClassesElement, - ManagedList list, ParserContext parserContext) { + ManagedList list) { for (Element child : DomUtils.getChildElementsByTagName(exceptionClassesElement, elementName)) { String className = child.getAttribute("class"); list.add(new TypedStringValue(className, Class.class)); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/job/SimpleJob.java b/spring-batch-core/src/main/java/org/springframework/batch/core/job/SimpleJob.java index b22317ef28..4744473333 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/job/SimpleJob.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/job/SimpleJob.java @@ -79,8 +79,8 @@ public Collection getStepNames() { for (Step step : steps) { names.add(step.getName()); - if (step instanceof StepLocator) { - names.addAll(((StepLocator) step).getStepNames()); + if (step instanceof StepLocator stepLocator) { + names.addAll(stepLocator.getStepNames()); } } return names; @@ -100,8 +100,8 @@ public Step getStep(String stepName) { if (step.getName().equals(stepName)) { return step; } - else if (step instanceof StepLocator) { - Step result = ((StepLocator) step).getStep(stepName); + else if (step instanceof StepLocator stepLocator) { + Step result = stepLocator.getStep(stepName); if (result != null) { return result; } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/FlowBuilder.java b/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/FlowBuilder.java index 17d3559471..2f2b4aba1d 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/FlowBuilder.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/FlowBuilder.java @@ -238,8 +238,8 @@ protected Flow flow() { } flow = new SimpleFlow(name); // optimization for flows that only have one state that itself is a flow: - if (currentState instanceof FlowState && states.size() == 1) { - return ((FlowState) currentState).getFlows().iterator().next(); + if (currentState instanceof FlowState flowState && states.size() == 1) { + return flowState.getFlows().iterator().next(); } addDanglingEndStates(); flow.setStateTransitions(transitions); @@ -282,23 +282,21 @@ private void doFrom(Object input) { private State createState(Object input) { State result; - if (input instanceof Step) { + if (input instanceof Step step) { if (!states.containsKey(input)) { - Step step = (Step) input; - states.put(input, new StepState(prefix + "step" + (stepCounter++), step)); + states.put(input, new StepState(prefix + "step" + stepCounter++, step)); } result = states.get(input); } - else if (input instanceof JobExecutionDecider) { + else if (input instanceof JobExecutionDecider jobExecutionDecider) { if (!states.containsKey(input)) { - states.put(input, - new DecisionState((JobExecutionDecider) input, prefix + "decision" + (decisionCounter++))); + states.put(input, new DecisionState(jobExecutionDecider, prefix + "decision" + decisionCounter++)); } result = states.get(input); } - else if (input instanceof Flow) { + else if (input instanceof Flow f) { if (!states.containsKey(input)) { - states.put(input, new FlowState((Flow) input, prefix + "flow" + (flowCounter++))); + states.put(input, new FlowState(f, prefix + "flow" + flowCounter++)); } result = states.get(input); } @@ -311,7 +309,7 @@ else if (input instanceof Flow) { private SplitState createState(Collection flows, TaskExecutor executor, SplitState parentSplit) { if (!states.containsKey(flows)) { - states.put(flows, new SplitState(flows, prefix + "split" + (splitCounter++), parentSplit)); + states.put(flows, new SplitState(flows, prefix + "split" + splitCounter++, parentSplit)); } SplitState result = (SplitState) states.get(flows); if (executor != null) { @@ -392,7 +390,7 @@ protected void stop(String pattern) { } protected void stop(String pattern, State restart) { - EndState next = new EndState(FlowExecutionStatus.STOPPED, "STOPPED", prefix + "stop" + (endCounter++), true); + EndState next = new EndState(FlowExecutionStatus.STOPPED, "STOPPED", prefix + "stop" + endCounter++, true); addTransition(pattern, next); currentState = next; addTransition("*", restart); @@ -403,7 +401,7 @@ private void end(String pattern) { } private void end(String pattern, String code) { - addTransition(pattern, new EndState(FlowExecutionStatus.COMPLETED, code, prefix + "end" + (endCounter++))); + addTransition(pattern, new EndState(FlowExecutionStatus.COMPLETED, code, prefix + "end" + endCounter++)); } private void fail(String pattern) { @@ -634,11 +632,11 @@ public SplitBuilder(FlowBuilder parent, TaskExecutor executor) { */ public FlowBuilder add(Flow... flows) { Collection list = new ArrayList<>(Arrays.asList(flows)); - String name = "split" + (parent.splitCounter++); + String name = "split" + parent.splitCounter++; State one = parent.currentState; - if (one instanceof SplitState) { - parent.currentState = parent.createState(list, executor, (SplitState) one); + if (one instanceof SplitState splitState) { + parent.currentState = parent.createState(list, executor, splitState); return parent; } @@ -647,8 +645,8 @@ public FlowBuilder add(Flow... flows) { stateBuilder.currentState = one; list.add(stateBuilder.build()); } - else if (one instanceof FlowState && parent.states.size() == 1) { - list.add(((FlowState) one).getFlows().iterator().next()); + else if (one instanceof FlowState flowState && parent.states.size() == 1) { + list.add(flowState.getFlows().iterator().next()); } parent.currentState = parent.createState(list, executor, null); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/JobFlowBuilder.java b/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/JobFlowBuilder.java index db456d4863..f69a06285c 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/JobFlowBuilder.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/JobFlowBuilder.java @@ -63,9 +63,9 @@ public JobFlowBuilder(FlowJobBuilder parent, Flow flow) { public FlowJobBuilder build() { Flow flow = flow(); - if (flow instanceof InitializingBean) { + if (flow instanceof InitializingBean initializingBean) { try { - ((InitializingBean) flow).afterPropertiesSet(); + initializingBean.afterPropertiesSet(); } catch (Exception e) { throw new FlowBuilderException(e); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/SimpleJobBuilder.java b/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/SimpleJobBuilder.java index b714d484ea..2599b25b53 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/SimpleJobBuilder.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/job/builder/SimpleJobBuilder.java @@ -156,7 +156,7 @@ public SimpleJobBuilder next(Step step) { * @param executor instance of {@link TaskExecutor} to be used. * @return builder for fluent chaining */ - public JobFlowBuilder.SplitBuilder split(TaskExecutor executor) { + public FlowBuilder.SplitBuilder split(TaskExecutor executor) { for (Step step : steps) { if (builder == null) { builder = new JobFlowBuilder(new FlowJobBuilder(this), step); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/FlowJob.java b/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/FlowJob.java index 33e2f491fe..9c1f7ec9bb 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/FlowJob.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/FlowJob.java @@ -96,13 +96,13 @@ private void findSteps(Flow flow, Map map) { map.put(name, locator.getStep(name)); } } - else if (state instanceof StepHolder) { - Step step = ((StepHolder) state).getStep(); + else if (state instanceof StepHolder stepHolder) { + Step step = stepHolder.getStep(); String name = step.getName(); stepMap.put(name, step); } - else if (state instanceof FlowHolder) { - for (Flow subflow : ((FlowHolder) state).getFlows()) { + else if (state instanceof FlowHolder flowHolder) { + for (Flow subflow : flowHolder.getFlows()) { findSteps(subflow, map); } } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/JobFlowExecutor.java b/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/JobFlowExecutor.java index c1583e25f1..bf3cb8aa3f 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/JobFlowExecutor.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/JobFlowExecutor.java @@ -40,7 +40,7 @@ */ public class JobFlowExecutor implements FlowExecutor { - private final ThreadLocal stepExecutionHolder = new ThreadLocal<>(); + private static final ThreadLocal stepExecutionHolder = new ThreadLocal<>(); private final JobExecution execution; diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/SimpleFlow.java b/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/SimpleFlow.java index 1818d017fd..b16149e898 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/SimpleFlow.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/SimpleFlow.java @@ -243,9 +243,8 @@ protected State nextState(String stateName, FlowExecutionStatus status, StepExec } protected boolean isFlowContinued(State state, FlowExecutionStatus status, StepExecution stepExecution) { - boolean continued = true; - continued = state != null && status != FlowExecutionStatus.STOPPED; + boolean continued = state != null && status != FlowExecutionStatus.STOPPED; if (stepExecution != null) { Boolean reRun = (Boolean) stepExecution.getExecutionContext().get("batch.restart"); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/SplitState.java b/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/SplitState.java index 14f256adc8..8bedef1114 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/SplitState.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/SplitState.java @@ -129,8 +129,8 @@ public FlowExecutionStatus handle(final FlowExecutor executor) throws Exception catch (ExecutionException e) { // Unwrap the expected exceptions Throwable cause = e.getCause(); - if (cause instanceof Exception) { - exceptions.add((Exception) cause); + if (cause instanceof Exception exception) { + exceptions.add(exception); } else { exceptions.add(e); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/StepState.java b/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/StepState.java index 73d20b4193..45fc166af7 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/StepState.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/job/flow/support/state/StepState.java @@ -84,8 +84,8 @@ public Collection getStepNames() { names.add(step.getName()); - if (step instanceof StepLocator) { - names.addAll(((StepLocator) step).getStepNames()); + if (step instanceof StepLocator stepLocator) { + names.addAll(stepLocator.getStepNames()); } return names; @@ -98,8 +98,8 @@ public Step getStep(String stepName) throws NoSuchStepException { if (step.getName().equals(stepName)) { result = step; } - else if (step instanceof StepLocator) { - result = ((StepLocator) step).getStep(stepName); + else if (step instanceof StepLocator stepLocator) { + result = stepLocator.getStep(stepName); } return result; diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/CommandLineJobRunner.java b/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/CommandLineJobRunner.java index e03512d707..477316d417 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/CommandLineJobRunner.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/CommandLineJobRunner.java @@ -352,7 +352,7 @@ int start(String jobPath, String jobIdentifier, String[] parameters, Set try { job = jobLocator.getJob(jobName); } - catch (NoSuchJobException e) { + catch (NoSuchJobException ignored) { } } if (job == null) { diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/SimpleJobOperator.java b/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/SimpleJobOperator.java index ddaac05fb1..8b96135d42 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/SimpleJobOperator.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/SimpleJobOperator.java @@ -240,19 +240,19 @@ public boolean stop(long executionId) throws NoSuchJobExecutionException, JobExe try { Job job = jobRegistry.getJob(jobExecution.getJobInstance().getJobName()); - if (job instanceof StepLocator) {// can only process as StepLocator is the - // only way to get the step object + if (job instanceof StepLocator stepLocator) { + // can only process as StepLocator is the only way to get the step object // get the current stepExecution for (StepExecution stepExecution : jobExecution.getStepExecutions()) { if (stepExecution.getStatus().isRunning()) { try { // have the step execution that's running -> need to 'stop' it - Step step = ((StepLocator) job).getStep(stepExecution.getStepName()); - if (step instanceof TaskletStep) { - Tasklet tasklet = ((TaskletStep) step).getTasklet(); - if (tasklet instanceof StoppableTasklet) { + Step step = stepLocator.getStep(stepExecution.getStepName()); + if (step instanceof TaskletStep taskletStep) { + Tasklet tasklet = taskletStep.getTasklet(); + if (tasklet instanceof StoppableTasklet stoppableTasklet) { StepSynchronizationManager.register(stepExecution); - ((StoppableTasklet) tasklet).stop(); + stoppableTasklet.stop(); StepSynchronizationManager.release(); } } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/TaskExecutorJobLauncher.java b/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/TaskExecutorJobLauncher.java index 1576c57c41..f6994472f0 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/TaskExecutorJobLauncher.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/TaskExecutorJobLauncher.java @@ -173,11 +173,11 @@ public void run() { } private void rethrow(Throwable t) { - if (t instanceof RuntimeException) { - throw (RuntimeException) t; + if (t instanceof RuntimeException runtimeException) { + throw runtimeException; } - else if (t instanceof Error) { - throw (Error) t; + else if (t instanceof Error error) { + throw error; } throw new IllegalStateException(t); } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/TaskExecutorJobOperator.java b/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/TaskExecutorJobOperator.java index 8eb25f342a..3cfe24abb0 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/TaskExecutorJobOperator.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/launch/support/TaskExecutorJobOperator.java @@ -45,6 +45,7 @@ public class TaskExecutorJobOperator extends SimpleJobOperator { * Public setter for the {@link ListableJobLocator}. * @param jobRegistry the {@link ListableJobLocator} to set */ + @Override public void setJobRegistry(ListableJobLocator jobRegistry) { this.jobRegistry = jobRegistry; } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/listener/AbstractListenerFactoryBean.java b/spring-batch-core/src/main/java/org/springframework/batch/core/listener/AbstractListenerFactoryBean.java index 18c9e4cf2e..00ca69e6fd 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/listener/AbstractListenerFactoryBean.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/listener/AbstractListenerFactoryBean.java @@ -150,8 +150,8 @@ public Object getObject() { // create a proxy listener for only the interfaces that have methods to // be called ProxyFactory proxyFactory = new ProxyFactory(); - if (delegate instanceof Advised) { - proxyFactory.setTargetSource(((Advised) delegate).getTargetSource()); + if (delegate instanceof Advised advised) { + proxyFactory.setTargetSource(advised.getTargetSource()); } else { proxyFactory.setTarget(delegate); @@ -214,15 +214,13 @@ public static boolean isListener(Object target, Class listenerType, ListenerM if (listenerType.isInstance(target)) { return true; } - if (target instanceof Advised) { - TargetSource targetSource = ((Advised) target).getTargetSource(); - if (targetSource != null && targetSource.getTargetClass() != null - && listenerType.isAssignableFrom(targetSource.getTargetClass())) { + if (target instanceof Advised advised) { + TargetSource targetSource = advised.getTargetSource(); + if (targetSource.getTargetClass() != null && listenerType.isAssignableFrom(targetSource.getTargetClass())) { return true; } - if (targetSource != null && targetSource.getTargetClass() != null - && targetSource.getTargetClass().isInterface()) { + if (targetSource.getTargetClass() != null && targetSource.getTargetClass().isInterface()) { logger.warn(String.format( "%s is an interface. The implementing class will not be queried for annotation based listener configurations. If using @StepScope on a @Bean method, be sure to return the implementing class so listener annotations can be used.", targetSource.getTargetClass().getName())); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/listener/MethodInvokerMethodInterceptor.java b/spring-batch-core/src/main/java/org/springframework/batch/core/listener/MethodInvokerMethodInterceptor.java index b6cd083e9a..6e1ba9ea84 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/listener/MethodInvokerMethodInterceptor.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/listener/MethodInvokerMethodInterceptor.java @@ -68,12 +68,12 @@ public Object invoke(MethodInvocation invocation) throws Throwable { ExitStatus status = null; for (MethodInvoker invoker : invokers) { Object retVal = invoker.invokeMethod(invocation.getArguments()); - if (retVal instanceof ExitStatus) { + if (retVal instanceof ExitStatus exitStatus) { if (status != null) { - status = status.and((ExitStatus) retVal); + status = status.and(exitStatus); } else { - status = (ExitStatus) retVal; + status = exitStatus; } } } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/listener/MulticasterBatchListener.java b/spring-batch-core/src/main/java/org/springframework/batch/core/listener/MulticasterBatchListener.java index 81db370944..1fb24e8c4a 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/listener/MulticasterBatchListener.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/listener/MulticasterBatchListener.java @@ -78,11 +78,11 @@ public void setListeners(List listeners) { * @param listener the {@link StepListener} instance to be registered. */ public void register(StepListener listener) { - if (listener instanceof StepExecutionListener) { - this.stepListener.register((StepExecutionListener) listener); + if (listener instanceof StepExecutionListener stepExecutionListener) { + this.stepListener.register(stepExecutionListener); } - if (listener instanceof ChunkListener) { - this.chunkListener.register((ChunkListener) listener); + if (listener instanceof ChunkListener cl) { + this.chunkListener.register(cl); } if (listener instanceof ItemReadListener) { @SuppressWarnings("unchecked") @@ -323,8 +323,8 @@ public void afterChunkError(ChunkContext context) { */ private Throwable getTargetException(RuntimeException e) { Throwable cause = e.getCause(); - if (cause != null && cause instanceof InvocationTargetException) { - return ((InvocationTargetException) cause).getTargetException(); + if (cause instanceof InvocationTargetException invocationTargetException) { + return invocationTargetException.getTargetException(); } return e; } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/observability/BatchMetrics.java b/spring-batch-core/src/main/java/org/springframework/batch/core/observability/BatchMetrics.java index a0d6196b1a..7e5a9e7595 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/observability/BatchMetrics.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/observability/BatchMetrics.java @@ -176,7 +176,7 @@ public static String formatDuration(@Nullable Duration duration) { StringBuilder formattedDuration = new StringBuilder(); long hours = duration.toHours(); long minutes = duration.toMinutes(); - long seconds = duration.getSeconds(); + long seconds = duration.toSeconds(); long millis = duration.toMillis(); if (hours != 0) { formattedDuration.append(hours).append("h"); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/SimpleStepExecutionSplitter.java b/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/SimpleStepExecutionSplitter.java index 699e95fc12..bcb5d796a9 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/SimpleStepExecutionSplitter.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/partition/support/SimpleStepExecutionSplitter.java @@ -191,9 +191,9 @@ private Map getContexts(StepExecution stepExecution, i result = partitioner.partition(splitSize); } else { - if (partitioner instanceof PartitionNameProvider) { + if (partitioner instanceof PartitionNameProvider partitionNameProvider) { result = new HashMap<>(); - Collection names = ((PartitionNameProvider) partitioner).getPartitionNames(splitSize); + Collection names = partitionNameProvider.getPartitionNames(splitSize); for (String name : names) { /* * We need to return the same keys as the original (failed) execution, diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/Jackson2ExecutionContextStringSerializer.java b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/Jackson2ExecutionContextStringSerializer.java index 9890c09853..5786563707 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/Jackson2ExecutionContextStringSerializer.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/Jackson2ExecutionContextStringSerializer.java @@ -173,7 +173,8 @@ private JobParametersModule() { addSerializer(JobParameter.class, new JobParameterSerializer(JobParameter.class)); } - private abstract class JobParametersMixIn { + @SuppressWarnings("unused") + private abstract static class JobParametersMixIn { @JsonIgnore abstract boolean isEmpty(); @@ -183,7 +184,7 @@ private abstract class JobParametersMixIn { } - private class JobParameterSerializer extends StdSerializer { + private static class JobParameterSerializer extends StdSerializer { protected JobParameterSerializer(Class type) { super(type); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDao.java b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDao.java index 3e783ccb2c..ce1605f11d 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDao.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDao.java @@ -56,8 +56,10 @@ */ public class JdbcJobInstanceDao extends AbstractJdbcBatchMetadataDao implements JobInstanceDao, InitializingBean { + @SuppressWarnings("unused") private static final String STAR_WILDCARD = "*"; + @SuppressWarnings("unused") private static final String SQL_WILDCARD = "%"; private static final String CREATE_JOB_INSTANCE = """ diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/explore/support/SimpleJobExplorer.java b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/explore/support/SimpleJobExplorer.java index da3e70b1ce..6971f13c89 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/repository/explore/support/SimpleJobExplorer.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/repository/explore/support/SimpleJobExplorer.java @@ -110,7 +110,7 @@ public List findJobInstancesByJobName(String jobName, int start, in @Override @Deprecated(since = "6.0", forRemoval = true) public List findJobInstancesByName(String jobName, int start, int count) { - return this.jobInstanceDao.findJobInstancesByName(jobName, start, count); + return getJobInstances(jobName, start, count); } @Nullable diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/scope/BatchScopeSupport.java b/spring-batch-core/src/main/java/org/springframework/batch/core/scope/BatchScopeSupport.java index 7cf74c855c..1b8da10bf5 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/scope/BatchScopeSupport.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/scope/BatchScopeSupport.java @@ -185,8 +185,8 @@ protected Object resolveValue(Object value) { BeanDefinition definition = null; String beanName = null; - if (value instanceof BeanDefinition) { - definition = (BeanDefinition) value; + if (value instanceof BeanDefinition beanDefinition) { + definition = beanDefinition; beanName = BeanDefinitionReaderUtils.generateBeanName(definition, registry); } else if (value instanceof BeanDefinitionHolder holder) { diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/JobContext.java b/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/JobContext.java index 25e51964c7..a1fb643bde 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/JobContext.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/JobContext.java @@ -161,8 +161,8 @@ public void close() { } Exception error = errors.get(0); - if (error instanceof RuntimeException) { - throw (RuntimeException) error; + if (error instanceof RuntimeException runtimeException) { + throw runtimeException; } else { throw new UnexpectedJobExecutionException( diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/JobSynchronizationManager.java b/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/JobSynchronizationManager.java index 0471cb4143..677c3a1844 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/JobSynchronizationManager.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/JobSynchronizationManager.java @@ -60,12 +60,12 @@ public static JobContext getContext() { * Register a context with the current thread - always put a matching {@link #close()} * call in a finally block to ensure that the correct context is available in the * enclosing block. - * @param JobExecution the step context to register + * @param jobExecution the step context to register * @return a new {@link JobContext} or the current one if it has the same * {@link JobExecution} */ - public static JobContext register(JobExecution JobExecution) { - return manager.register(JobExecution); + public static JobContext register(JobExecution jobExecution) { + return manager.register(jobExecution); } /** diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/StepContext.java b/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/StepContext.java index a076b5bee9..02a39eb08a 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/StepContext.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/scope/context/StepContext.java @@ -197,8 +197,8 @@ public void close() { } Exception error = errors.get(0); - if (error instanceof RuntimeException) { - throw (RuntimeException) error; + if (error instanceof RuntimeException runtimeException) { + throw runtimeException; } else { throw new UnexpectedJobExecutionException( diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/AbstractStep.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/AbstractStep.java index c2339b95df..f8747a42b1 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/AbstractStep.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/AbstractStep.java @@ -81,6 +81,7 @@ public abstract class AbstractStep implements Step, InitializingBean, BeanNameAw private ObservationRegistry observationRegistry = ObservationRegistry.NOOP; + @SuppressWarnings("unused") private MeterRegistry meterRegistry = Metrics.globalRegistry; private BatchStepObservationConvention observationConvention = new DefaultBatchStepObservationConvention(); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/AbstractTaskletStepBuilder.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/AbstractTaskletStepBuilder.java index 3a5eb7ab0f..73cad957c6 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/AbstractTaskletStepBuilder.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/AbstractTaskletStepBuilder.java @@ -146,8 +146,8 @@ public TaskletStep build() { protected void registerStepListenerAsChunkListener() { for (StepExecutionListener stepExecutionListener : properties.getStepExecutionListeners()) { - if (stepExecutionListener instanceof ChunkListener) { - listener((ChunkListener) stepExecutionListener); + if (stepExecutionListener instanceof ChunkListener chunkListener) { + listener(chunkListener); } } } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/FaultTolerantStepBuilder.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/FaultTolerantStepBuilder.java index e4c24fb3b0..5207242187 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/FaultTolerantStepBuilder.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/FaultTolerantStepBuilder.java @@ -574,11 +574,10 @@ else if (limitCheckingItemSkipPolicy != null) { protected BatchRetryTemplate createRetryOperations() { RetryPolicy retryPolicy = this.retryPolicy; - SimpleRetryPolicy simpleRetryPolicy = null; Map, Boolean> map = new HashMap<>(retryableExceptionClasses); map.put(ForceRollbackForWriteSkipException.class, true); - simpleRetryPolicy = new SimpleRetryPolicy(retryLimit, map); + SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy(retryLimit, map); if (retryPolicy == null) { Assert.state(!(retryableExceptionClasses.isEmpty() && retryLimit > 0), @@ -601,10 +600,10 @@ else if ((!retryableExceptionClasses.isEmpty() && retryLimit > 0)) { // Coordinate the retry policy with the exception handler: RepeatOperations stepOperations = getStepOperations(); - if (stepOperations instanceof RepeatTemplate) { + if (stepOperations instanceof RepeatTemplate repeatTemplate) { SimpleRetryExceptionHandler exceptionHandler = new SimpleRetryExceptionHandler(retryPolicyWrapper, getExceptionHandler(), nonRetryableExceptionClasses); - ((RepeatTemplate) stepOperations).setExceptionHandler(exceptionHandler); + repeatTemplate.setExceptionHandler(exceptionHandler); } if (retryContextCache != null) { diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/SimpleStepBuilder.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/SimpleStepBuilder.java index fed10c44a1..76cec6cfd4 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/SimpleStepBuilder.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/builder/SimpleStepBuilder.java @@ -383,16 +383,16 @@ protected CompletionPolicy getChunkCompletionPolicy() { protected void registerAsStreamsAndListeners(ItemReader itemReader, ItemProcessor itemProcessor, ItemWriter itemWriter) { for (Object itemHandler : new Object[] { itemReader, itemWriter, itemProcessor }) { - if (itemHandler instanceof ItemStream) { - stream((ItemStream) itemHandler); + if (itemHandler instanceof ItemStream itemStream) { + stream(itemStream); } if (StepListenerFactoryBean.isListener(itemHandler)) { StepListener listener = StepListenerFactoryBean.getListener(itemHandler); - if (listener instanceof StepExecutionListener) { - listener((StepExecutionListener) listener); + if (listener instanceof StepExecutionListener stepExecutionListener) { + listener(stepExecutionListener); } - if (listener instanceof ChunkListener) { - listener((ChunkListener) listener); + if (listener instanceof ChunkListener chunkListener) { + listener(chunkListener); } if (listener instanceof ItemReadListener || listener instanceof ItemProcessListener || listener instanceof ItemWriteListener) { diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/factory/SimpleStepFactoryBean.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/factory/SimpleStepFactoryBean.java index d2d672676a..6bd4776033 100755 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/factory/SimpleStepFactoryBean.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/factory/SimpleStepFactoryBean.java @@ -107,7 +107,8 @@ public class SimpleStepFactoryBean implements FactoryBean, BeanNameA private CompletionPolicy chunkCompletionPolicy; - private int throttleLimit = TaskExecutorRepeatTemplate.DEFAULT_THROTTLE_LIMIT; + @SuppressWarnings("unused") + private final int throttleLimit = TaskExecutorRepeatTemplate.DEFAULT_THROTTLE_LIMIT; private boolean isReaderTransactionalQueue = false; diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkMonitor.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkMonitor.java index 47ac071075..edcb5b0a34 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkMonitor.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/ChunkMonitor.java @@ -58,7 +58,7 @@ public ChunkMonitorData(int offset, int chunkSize) { private final CompositeItemStream stream = new CompositeItemStream(); - private final ThreadLocal holder = new ThreadLocal<>(); + private static final ThreadLocal holder = new ThreadLocal<>(); private ItemReader reader; diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessor.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessor.java index ecb797111c..66b86029c6 100755 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessor.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/item/FaultTolerantChunkProcessor.java @@ -82,17 +82,17 @@ public void setKeyGenerator(KeyGenerator keyGenerator) { } /** - * @param SkipPolicy the {@link SkipPolicy} for item processing + * @param skipPolicy the {@link SkipPolicy} for item processing */ - public void setProcessSkipPolicy(SkipPolicy SkipPolicy) { - this.itemProcessSkipPolicy = SkipPolicy; + public void setProcessSkipPolicy(SkipPolicy skipPolicy) { + this.itemProcessSkipPolicy = skipPolicy; } /** - * @param SkipPolicy the {@link SkipPolicy} for item writing + * @param skipPolicy the {@link SkipPolicy} for item writing */ - public void setWriteSkipPolicy(SkipPolicy SkipPolicy) { - this.itemWriteSkipPolicy = SkipPolicy; + public void setWriteSkipPolicy(SkipPolicy skipPolicy) { + this.itemWriteSkipPolicy = skipPolicy; } /** @@ -489,7 +489,7 @@ private boolean shouldSkip(SkipPolicy policy, Throwable e, long skipCount) { throw ex; } catch (RuntimeException ex) { - throw new SkipListenerFailedException("Fatal exception in SkipPolicy.", ex, e); + throw new SkipListenerFailedException("Fatal exception in skipPolicy.", ex, e); } } @@ -526,11 +526,11 @@ private void checkSkipPolicy(Chunk.ChunkIterator inputIterator, Chunk.Chun throw new RetryException("Non-skippable exception in recoverer", e); } else { - if (e instanceof Exception) { - throw (Exception) e; + if (e instanceof Exception exception) { + throw exception; } - else if (e instanceof Error) { - throw (Error) e; + else if (e instanceof Error error) { + throw error; } else { throw new RetryException("Non-skippable throwable in recoverer", e); diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/skip/SkipPolicy.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/skip/SkipPolicy.java index 15486d82b7..e1eb831d7c 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/skip/SkipPolicy.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/skip/SkipPolicy.java @@ -28,9 +28,9 @@ public interface SkipPolicy { /** * Returns true or false, indicating whether or not processing should continue with - * the given throwable. Clients may use {@code skipCount<0} to probe for exception + * the given throwable. Clients may use {@code skipCount < 0} to probe for exception * types that are skippable, so implementations should be able to handle gracefully - * the case where {@code skipCount<0}. Implementations should avoid throwing any + * the case where {@code skipCount < 0}. Implementations should avoid throwing any * undeclared exceptions. * @param t exception encountered while processing * @param skipCount currently running count of skips diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/tasklet/MethodInvokingTaskletAdapter.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/tasklet/MethodInvokingTaskletAdapter.java index 86206538f4..9c7910b583 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/tasklet/MethodInvokingTaskletAdapter.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/tasklet/MethodInvokingTaskletAdapter.java @@ -59,8 +59,8 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext chunkCon * @return an {@link ExitStatus} consistent with the result */ protected ExitStatus mapResult(Object result) { - if (result instanceof ExitStatus) { - return (ExitStatus) result; + if (result instanceof ExitStatus exitStatus) { + return exitStatus; } return ExitStatus.COMPLETED; } diff --git a/spring-batch-core/src/main/java/org/springframework/batch/core/step/tasklet/TaskletStep.java b/spring-batch-core/src/main/java/org/springframework/batch/core/step/tasklet/TaskletStep.java index aaf192beb2..d25378ac44 100644 --- a/spring-batch-core/src/main/java/org/springframework/batch/core/step/tasklet/TaskletStep.java +++ b/spring-batch-core/src/main/java/org/springframework/batch/core/step/tasklet/TaskletStep.java @@ -142,8 +142,8 @@ public void setTransactionAttribute(TransactionAttribute transactionAttribute) { */ public void setTasklet(Tasklet tasklet) { this.tasklet = tasklet; - if (tasklet instanceof StepExecutionListener) { - registerStepExecutionListener((StepExecutionListener) tasklet); + if (tasklet instanceof StepExecutionListener stepExecutionListener) { + registerStepExecutionListener(stepExecutionListener); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/BatchRegistrarTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/BatchRegistrarTests.java index 2aee2be078..8c43dea1bb 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/BatchRegistrarTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/annotation/BatchRegistrarTests.java @@ -331,11 +331,11 @@ public JdbcTransactionManager transactionManager(DataSource dataSource) { } @Bean - public JobKeyGenerator jobKeyGenerator() { + public JobKeyGenerator jobKeyGenerator() { return new TestCustomJobKeyGenerator(); } - private class TestCustomJobKeyGenerator implements JobKeyGenerator { + private static class TestCustomJobKeyGenerator implements JobKeyGenerator { @Override public String generateKey(Object source) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/ApplicationContextJobFactoryTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/ApplicationContextJobFactoryTests.java index e12b9e8ffd..a24e1fb372 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/ApplicationContextJobFactoryTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/ApplicationContextJobFactoryTests.java @@ -69,8 +69,8 @@ private static class TestBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof JobSupport) { - ((JobSupport) bean).setName("bar"); + if (bean instanceof JobSupport jobSupport) { + jobSupport.setName("bar"); } return bean; } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrarTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrarTests.java index 61112f4768..d024c9f637 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrarTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/AutomaticJobRegistrarTests.java @@ -17,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -58,7 +59,7 @@ void setUp() { @Test void testOrderedImplemented() { - assertTrue(registrar instanceof Ordered); + assertInstanceOf(Ordered.class, registrar); assertEquals(Ordered.LOWEST_PRECEDENCE, registrar.getOrder()); registrar.setOrder(1); assertEquals(1, registrar.getOrder()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/DefaultBatchConfigurationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/DefaultBatchConfigurationTests.java index c1b50b4817..d4de304605 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/DefaultBatchConfigurationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/configuration/support/DefaultBatchConfigurationTests.java @@ -159,6 +159,7 @@ public JobRepository jobRepository() { } @Bean + @Override public JobRegistrySmartInitializingSingleton jobRegistrySmartInitializingSingleton(JobRegistry jobRegistry) { JobRegistrySmartInitializingSingleton smartInitializingSingleton = new JobRegistrySmartInitializingSingleton(); smartInitializingSingleton.setJobRegistry(jobRegistry); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/JobExplorerFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/JobExplorerFactoryBeanTests.java index 10bbcf325e..c751360967 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/JobExplorerFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/explore/support/JobExplorerFactoryBeanTests.java @@ -147,7 +147,7 @@ public void testCustomJobKeyGenerator() throws Exception { Assertions.assertEquals(CustomJobKeyGenerator.class, jobKeyGenerator.getClass()); } - class CustomJobKeyGenerator implements JobKeyGenerator { + static class CustomJobKeyGenerator implements JobKeyGenerator { @Override public String generateKey(String source) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobTests.java index 8de4d8cf26..5fa25df789 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/SimpleJobTests.java @@ -178,7 +178,7 @@ void testExitStatusReturned() { Step testStep = new Step() { @Override - public void execute(StepExecution stepExecution) throws JobInterruptedException { + public void execute(StepExecution stepExecution) { stepExecution.setExitStatus(customStatus); } @@ -192,10 +192,6 @@ public int getStartLimit() { return 1; } - @Override - public boolean isAllowStartIfComplete() { - return false; - } }; List steps = new ArrayList<>(); steps.add(testStep); @@ -496,8 +492,8 @@ void testGetMultipleJobParameters() throws Exception { List jobExecutionList = jobExplorer.getJobExecutions(jobexecution.getJobInstance()); - assertEquals(jobExecutionList.size(), 1); - assertEquals(jobExecutionList.get(0).getJobParameters().getString("JobExecutionParameter"), "first"); + assertEquals(1, jobExecutionList.size()); + assertEquals("first", jobExecutionList.get(0).getJobParameters().getString("JobExecutionParameter")); JobParameters secondJobParameters = new JobParametersBuilder() .addString("JobExecutionParameter", "second", false) @@ -507,9 +503,9 @@ void testGetMultipleJobParameters() throws Exception { jobExecutionList = jobExplorer.getJobExecutions(jobexecution.getJobInstance()); - assertEquals(jobExecutionList.size(), 2); - assertEquals(jobExecutionList.get(0).getJobParameters().getString("JobExecutionParameter"), "second"); - assertEquals(jobExecutionList.get(1).getJobParameters().getString("JobExecutionParameter"), "first"); + assertEquals(2, jobExecutionList.size()); + assertEquals("second", jobExecutionList.get(0).getJobParameters().getString("JobExecutionParameter")); + assertEquals("first", jobExecutionList.get(1).getJobParameters().getString("JobExecutionParameter")); } @@ -570,11 +566,11 @@ public void execute(StepExecution stepExecution) jobRepository.update(stepExecution); jobRepository.updateExecutionContext(stepExecution); - if (exception instanceof JobInterruptedException) { + if (exception instanceof JobInterruptedException jobInterruptedException) { stepExecution.setExitStatus(ExitStatus.FAILED); - stepExecution.setStatus(((JobInterruptedException) exception).getStatus()); + stepExecution.setStatus(jobInterruptedException.getStatus()); stepExecution.addFailureException(exception); - throw (JobInterruptedException) exception; + throw jobInterruptedException; } if (exception instanceof RuntimeException) { stepExecution.setExitStatus(ExitStatus.FAILED); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/FlowBuilderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/FlowBuilderTests.java index dd47b49999..bee66c02a2 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/FlowBuilderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/job/builder/FlowBuilderTests.java @@ -57,7 +57,7 @@ void testNext() throws Exception { .start(new JobFlowExecutor(jobRepository, new SimpleStepHandler(jobRepository), execution)); Iterator stepExecutions = execution.getStepExecutions().iterator(); - assertEquals(stepExecutions.next().getStepName(), "stepA"); + assertEquals("stepA", stepExecutions.next().getStepName()); assertFalse(stepExecutions.hasNext()); } @@ -74,9 +74,9 @@ void testMultipleNext() throws Exception { .start(new JobFlowExecutor(jobRepository, new SimpleStepHandler(jobRepository), execution)); Iterator stepExecutions = execution.getStepExecutions().iterator(); - assertEquals(stepExecutions.next().getStepName(), "stepA"); - assertEquals(stepExecutions.next().getStepName(), "stepB"); - assertEquals(stepExecutions.next().getStepName(), "stepC"); + assertEquals("stepA", stepExecutions.next().getStepName()); + assertEquals("stepB", stepExecutions.next().getStepName()); + assertEquals("stepC", stepExecutions.next().getStepName()); assertFalse(stepExecutions.hasNext()); } @@ -91,7 +91,7 @@ void testStart() throws Exception { .start(new JobFlowExecutor(jobRepository, new SimpleStepHandler(jobRepository), execution)); Iterator stepExecutions = execution.getStepExecutions().iterator(); - assertEquals(stepExecutions.next().getStepName(), "stepA"); + assertEquals("stepA", stepExecutions.next().getStepName()); assertFalse(stepExecutions.hasNext()); } @@ -106,7 +106,7 @@ void testFrom() throws Exception { .start(new JobFlowExecutor(jobRepository, new SimpleStepHandler(jobRepository), execution)); Iterator stepExecutions = execution.getStepExecutions().iterator(); - assertEquals(stepExecutions.next().getStepName(), "stepA"); + assertEquals("stepA", stepExecutions.next().getStepName()); assertFalse(stepExecutions.hasNext()); } @@ -118,23 +118,20 @@ void testTransitionOrdering() throws Exception { StepSupport stepA = new StepSupport("stepA") { @Override - public void execute(StepExecution stepExecution) - throws JobInterruptedException, UnexpectedJobExecutionException { + public void execute(StepExecution stepExecution) throws UnexpectedJobExecutionException { stepExecution.setExitStatus(ExitStatus.FAILED); } }; StepSupport stepB = new StepSupport("stepB") { @Override - public void execute(StepExecution stepExecution) - throws JobInterruptedException, UnexpectedJobExecutionException { + public void execute(StepExecution stepExecution) throws UnexpectedJobExecutionException { } }; StepSupport stepC = new StepSupport("stepC") { @Override - public void execute(StepExecution stepExecution) - throws JobInterruptedException, UnexpectedJobExecutionException { + public void execute(StepExecution stepExecution) throws UnexpectedJobExecutionException { } }; @@ -148,16 +145,15 @@ public void execute(StepExecution stepExecution) .start(new JobFlowExecutor(jobRepository, new SimpleStepHandler(jobRepository), execution)); Iterator stepExecutions = execution.getStepExecutions().iterator(); - assertEquals(stepExecutions.next().getStepName(), "stepA"); - assertEquals(stepExecutions.next().getStepName(), "stepC"); + assertEquals("stepA", stepExecutions.next().getStepName()); + assertEquals("stepC", stepExecutions.next().getStepName()); assertFalse(stepExecutions.hasNext()); } private static StepSupport createCompleteStep(String name) { return new StepSupport(name) { @Override - public void execute(StepExecution stepExecution) - throws JobInterruptedException, UnexpectedJobExecutionException { + public void execute(StepExecution stepExecution) throws UnexpectedJobExecutionException { stepExecution.upgradeStatus(BatchStatus.COMPLETED); stepExecution.setExitStatus(ExitStatus.COMPLETED); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobLauncherIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobLauncherIntegrationTests.java index 2111ebc35a..796750b860 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobLauncherIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/JobLauncherIntegrationTests.java @@ -66,7 +66,6 @@ private JobExecution launch(boolean start, long jobExecutionId) throws Exception if (start) { - Calendar c = Calendar.getInstance(); JobParametersBuilder builder = new JobParametersBuilder(); builder.addString("name", "foo"); JobParameters jobParameters = builder.toJobParameters(); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/CommandLineJobRunnerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/CommandLineJobRunnerTests.java index 448b4038b3..42f9e50e31 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/CommandLineJobRunnerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/launch/support/CommandLineJobRunnerTests.java @@ -138,8 +138,8 @@ void testWrongJobName() throws Exception { assertEquals(1, StubSystemExiter.status); String errorMessage = CommandLineJobRunner.getErrorMessage(); assertTrue( - (errorMessage.contains("No bean named 'no-such-job' is defined") - || (errorMessage.contains("No bean named 'no-such-job' available"))), + errorMessage.contains("No bean named 'no-such-job' is defined") + || errorMessage.contains("No bean named 'no-such-job' available"), "Wrong error message: " + errorMessage); } @@ -217,7 +217,7 @@ public int read() { void testWithStdinParameters() throws Throwable { String[] args = new String[] { jobPath, jobName }; System.setIn(new InputStream() { - final char[] input = ("foo=bar\nspam=bucket").toCharArray(); + final char[] input = "foo=bar\nspam=bucket".toCharArray(); int index = 0; @@ -248,7 +248,7 @@ void testWithInvalidParameters() throws Throwable { @Test void testStop() throws Throwable { String[] args = new String[] { jobPath, "-stop", jobName }; - StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(3L, jobName)); + StubJobExplorer.jobInstances = List.of(new JobInstance(3L, jobName)); CommandLineJobRunner.main(args); assertEquals(1, StubSystemExiter.status); } @@ -256,7 +256,7 @@ void testStop() throws Throwable { @Test void testStopFailed() throws Throwable { String[] args = new String[] { jobPath, "-stop", jobName }; - StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(0L, jobName)); + StubJobExplorer.jobInstances = List.of(new JobInstance(0L, jobName)); CommandLineJobRunner.main(args); assertEquals(1, StubSystemExiter.status); } @@ -264,7 +264,7 @@ void testStopFailed() throws Throwable { @Test void testStopFailedAndRestarted() throws Throwable { String[] args = new String[] { jobPath, "-stop", jobName }; - StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(5L, jobName)); + StubJobExplorer.jobInstances = List.of(new JobInstance(5L, jobName)); CommandLineJobRunner.main(args); assertEquals(1, StubSystemExiter.status); } @@ -273,7 +273,7 @@ void testStopFailedAndRestarted() throws Throwable { void testStopRestarted() throws Throwable { String[] args = new String[] { jobPath, "-stop", jobName }; JobInstance jobInstance = new JobInstance(3L, jobName); - StubJobExplorer.jobInstances = Arrays.asList(jobInstance); + StubJobExplorer.jobInstances = List.of(jobInstance); CommandLineJobRunner.main(args); assertEquals(1, StubSystemExiter.status); } @@ -281,7 +281,7 @@ void testStopRestarted() throws Throwable { @Test void testAbandon() throws Throwable { String[] args = new String[] { jobPath, "-abandon", jobName }; - StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(2L, jobName)); + StubJobExplorer.jobInstances = List.of(new JobInstance(2L, jobName)); CommandLineJobRunner.main(args); assertEquals(0, StubSystemExiter.status); } @@ -289,7 +289,7 @@ void testAbandon() throws Throwable { @Test void testAbandonRunning() throws Throwable { String[] args = new String[] { jobPath, "-abandon", jobName }; - StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(3L, jobName)); + StubJobExplorer.jobInstances = List.of(new JobInstance(3L, jobName)); CommandLineJobRunner.main(args); assertEquals(1, StubSystemExiter.status); } @@ -297,7 +297,7 @@ void testAbandonRunning() throws Throwable { @Test void testAbandonAbandoned() throws Throwable { String[] args = new String[] { jobPath, "-abandon", jobName }; - StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(4L, jobName)); + StubJobExplorer.jobInstances = List.of(new JobInstance(4L, jobName)); CommandLineJobRunner.main(args); assertEquals(1, StubSystemExiter.status); } @@ -307,7 +307,7 @@ void testRestart() throws Throwable { String[] args = new String[] { jobPath, "-restart", jobName }; JobParameters jobParameters = new JobParametersBuilder().addString("foo", "bar").toJobParameters(); JobInstance jobInstance = new JobInstance(0L, jobName); - StubJobExplorer.jobInstances = Arrays.asList(jobInstance); + StubJobExplorer.jobInstances = List.of(jobInstance); StubJobExplorer.jobParameters = jobParameters; CommandLineJobRunner.main(args); assertEquals(0, StubSystemExiter.status); @@ -342,7 +342,7 @@ void testRestartExecutionNotFailed() throws Throwable { @Test void testRestartNotFailed() throws Throwable { String[] args = new String[] { jobPath, "-restart", jobName }; - StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(123L, jobName)); + StubJobExplorer.jobInstances = List.of(new JobInstance(123L, jobName)); CommandLineJobRunner.main(args); assertEquals(1, StubSystemExiter.status); String errorMessage = CommandLineJobRunner.getErrorMessage(); @@ -353,13 +353,12 @@ void testRestartNotFailed() throws Throwable { @Test void testNext() throws Throwable { String[] args = new String[] { jobPath, "-next", jobName, "bar=foo" }; - JobParameters jobParameters = new JobParametersBuilder().addString("foo", "bar") - .addString("bar", "foo") - .toJobParameters(); - StubJobExplorer.jobInstances = Arrays.asList(new JobInstance(2L, jobName)); + StubJobExplorer.jobInstances = List.of(new JobInstance(2L, jobName)); CommandLineJobRunner.main(args); assertEquals(0, StubSystemExiter.status); - jobParameters = new JobParametersBuilder().addString("foo", "spam").addString("bar", "foo").toJobParameters(); + JobParameters jobParameters = new JobParametersBuilder().addString("foo", "spam") + .addString("bar", "foo") + .toJobParameters(); assertEquals(jobParameters, StubJobLauncher.jobParameters); } @@ -482,25 +481,25 @@ public JobExecution getJobExecution(@Nullable Long executionId) { @Override public List getJobExecutions(JobInstance jobInstance) { if (jobInstance.getId() == 0) { - return Arrays.asList(createJobExecution(jobInstance, BatchStatus.FAILED)); + return List.of(createJobExecution(jobInstance, BatchStatus.FAILED)); } if (jobInstance.getId() == 1) { return null; } if (jobInstance.getId() == 2) { - return Arrays.asList(createJobExecution(jobInstance, BatchStatus.STOPPED)); + return List.of(createJobExecution(jobInstance, BatchStatus.STOPPED)); } if (jobInstance.getId() == 3) { - return Arrays.asList(createJobExecution(jobInstance, BatchStatus.STARTED)); + return List.of(createJobExecution(jobInstance, BatchStatus.STARTED)); } if (jobInstance.getId() == 4) { - return Arrays.asList(createJobExecution(jobInstance, BatchStatus.ABANDONED)); + return List.of(createJobExecution(jobInstance, BatchStatus.ABANDONED)); } if (jobInstance.getId() == 5) { return Arrays.asList(createJobExecution(jobInstance, BatchStatus.STARTED), createJobExecution(jobInstance, BatchStatus.FAILED)); } - return Arrays.asList(createJobExecution(jobInstance, BatchStatus.COMPLETED)); + return List.of(createJobExecution(jobInstance, BatchStatus.COMPLETED)); } private JobExecution createJobExecution(JobInstance jobInstance, BatchStatus status) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemReadListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemReadListenerTests.java index ac9bd41bac..68b12d9dc0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemReadListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemReadListenerTests.java @@ -17,7 +17,7 @@ import static org.mockito.Mockito.mock; -import java.util.ArrayList; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -67,11 +67,7 @@ void testOnReadError() { @Test void testSetListeners() { - compositeListener.setListeners(new ArrayList<>() { - { - add(listener); - } - }); + compositeListener.setListeners(List.of(listener)); listener.beforeRead(); compositeListener.beforeRead(); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemWriteListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemWriteListenerTests.java index 6531b4ef35..5e166c790e 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemWriteListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/CompositeItemWriteListenerTests.java @@ -15,7 +15,7 @@ */ package org.springframework.batch.core.listener; -import java.util.ArrayList; +import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -69,11 +69,7 @@ void testOnWriteError() { @Test void testSetListeners() { - compositeListener.setListeners(new ArrayList<>() { - { - add(listener); - } - }); + compositeListener.setListeners(List.of(listener)); Chunk item = Chunk.of(new Object()); listener.beforeWrite(item); compositeListener.beforeWrite(item); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/MulticasterBatchListenerTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/MulticasterBatchListenerTests.java index 0a8fedd77f..60a3673429 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/MulticasterBatchListenerTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/MulticasterBatchListenerTests.java @@ -16,6 +16,7 @@ package org.springframework.batch.core.listener; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -459,7 +460,7 @@ void testBeforeReadFails_withAnnotatedListener() { Exception exception = assertThrows(StepListenerFailedException.class, multicast::beforeRead); Throwable cause = exception.getCause(); String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, cause); assertEquals("listener error", message, "Wrong message: " + message); } @@ -471,7 +472,7 @@ void testAfterReadFails_withAnnotatedListener() { Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.afterRead(null)); Throwable cause = exception.getCause(); String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, cause); assertEquals("listener error", message, "Wrong message: " + message); } @@ -483,7 +484,7 @@ void testBeforeProcessFails_withAnnotatedListener() { Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.beforeProcess(null)); Throwable cause = exception.getCause(); String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, cause); assertEquals("listener error", message, "Wrong message: " + message); } @@ -495,7 +496,7 @@ void testAfterProcessFails_withAnnotatedListener() { Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.afterProcess(null, null)); Throwable cause = exception.getCause(); String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, cause); assertEquals("listener error", message, "Wrong message: " + message); } @@ -507,7 +508,7 @@ void testBeforeWriteFails_withAnnotatedListener() { Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.beforeWrite(null)); Throwable cause = exception.getCause(); String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, cause); assertEquals("listener error", message, "Wrong message: " + message); } @@ -519,7 +520,7 @@ void testAfterWriteFails_withAnnotatedListener() { Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.afterWrite(null)); Throwable cause = exception.getCause(); String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, cause); assertEquals("listener error", message, "Wrong message: " + message); } @@ -531,7 +532,7 @@ void testBeforeChunkFails_withAnnotatedListener() { Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.beforeChunk(null)); Throwable cause = exception.getCause(); String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, cause); assertEquals("listener error", message, "Wrong message: " + message); } @@ -543,7 +544,7 @@ void testAfterChunkFails_withAnnotatedListener() { Exception exception = assertThrows(StepListenerFailedException.class, () -> multicast.afterChunk(null)); Throwable cause = exception.getCause(); String message = cause.getMessage(); - assertTrue(cause instanceof IllegalStateException); + assertInstanceOf(IllegalStateException.class, cause); assertEquals("listener error", message, "Wrong message: " + message); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java index f01c8b2fa4..83f8b1613d 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/listener/StepListenerFactoryBeanTests.java @@ -58,6 +58,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.springframework.batch.core.listener.StepListenerMetaData.AFTER_STEP; @@ -156,7 +157,7 @@ void testVanillaInterface() { MultipleAfterStep delegate = new MultipleAfterStep(); factoryBean.setDelegate(delegate); Object listener = factoryBean.getObject(); - assertTrue(listener instanceof StepExecutionListener); + assertInstanceOf(StepExecutionListener.class, listener); ((StepExecutionListener) listener).beforeStep(stepExecution); assertEquals(1, delegate.callcount); } @@ -167,7 +168,7 @@ void testVanillaInterfaceWithProxy() { ProxyFactory factory = new ProxyFactory(delegate); factoryBean.setDelegate(factory.getProxy()); Object listener = factoryBean.getObject(); - assertTrue(listener instanceof StepExecutionListener); + assertInstanceOf(StepExecutionListener.class, listener); ((StepExecutionListener) listener).beforeStep(stepExecution); assertEquals(1, delegate.callcount); } @@ -176,7 +177,7 @@ void testVanillaInterfaceWithProxy() { void testFactoryMethod() { MultipleAfterStep delegate = new MultipleAfterStep(); Object listener = StepListenerFactoryBean.getListener(delegate); - assertTrue(listener instanceof StepExecutionListener); + assertInstanceOf(StepExecutionListener.class, listener); assertFalse(listener instanceof ChunkListener); ((StepExecutionListener) listener).beforeStep(stepExecution); assertEquals(1, delegate.callcount); @@ -186,7 +187,7 @@ void testFactoryMethod() { void testAnnotationsWithOrdered() { Object delegate = new Ordered() { @BeforeStep - public void foo(StepExecution execution) { + public void foo(@SuppressWarnings("unused") StepExecution execution) { } @Override @@ -195,7 +196,7 @@ public int getOrder() { } }; StepListener listener = StepListenerFactoryBean.getListener(delegate); - assertTrue(listener instanceof Ordered, "Listener is not of correct type"); + assertInstanceOf(Ordered.class, listener, "Listener is not of correct type"); assertEquals(3, ((Ordered) listener).getOrder()); } @@ -203,15 +204,15 @@ public int getOrder() { void testProxiedAnnotationsFactoryMethod() { Object delegate = new InitializingBean() { @BeforeStep - public void foo(StepExecution execution) { + public void foo(@SuppressWarnings("unused") StepExecution execution) { } @Override - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() { } }; ProxyFactory factory = new ProxyFactory(delegate); - assertTrue(StepListenerFactoryBean.getListener(factory.getProxy()) instanceof StepExecutionListener, + assertInstanceOf(StepExecutionListener.class, StepListenerFactoryBean.getListener(factory.getProxy()), "Listener is not of correct type"); } @@ -224,7 +225,7 @@ void testInterfaceIsListener() { void testAnnotationsIsListener() { assertTrue(StepListenerFactoryBean.isListener(new Object() { @BeforeStep - public void foo(StepExecution execution) { + public void foo(@SuppressWarnings("unused") StepExecution execution) { } })); } @@ -242,11 +243,11 @@ void testProxyWithNoTarget() { void testProxiedAnnotationsIsListener() { Object delegate = new InitializingBean() { @BeforeStep - public void foo(StepExecution execution) { + public void foo(@SuppressWarnings("unused") StepExecution execution) { } @Override - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() { } }; ProxyFactory factory = new ProxyFactory(delegate); @@ -264,7 +265,7 @@ void testMixedIsListener() { void testNonListener() { Object delegate = new Object(); factoryBean.setDelegate(delegate); - assertTrue(factoryBean.getObject() instanceof StepListener); + assertInstanceOf(StepListener.class, factoryBean.getObject()); } @Test @@ -303,7 +304,7 @@ public void aMethod(Chunk chunk) { void testWrongSignatureAnnotation() { AbstractTestComponent delegate = new AbstractTestComponent() { @AfterWrite - public void aMethod(Integer item) { + public void aMethod(@SuppressWarnings("unused") Integer item) { executed = true; } }; diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/MinMaxPartitioner.java b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/MinMaxPartitioner.java index d46112f34c..76f5b7c4f9 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/partition/MinMaxPartitioner.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/partition/MinMaxPartitioner.java @@ -34,7 +34,7 @@ public Map partition(int gridSize) { int range = total / gridSize; int i = 0; for (ExecutionContext context : partition.values()) { - int min = (i++) * range; + int min = i++ * range; int max = Math.min(total, i * range); context.putInt("min", min); context.putInt("max", max); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobDaoTests.java index d4381fb949..9ac7e479c7 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobDaoTests.java @@ -52,7 +52,7 @@ public abstract class AbstractJobDaoTests { protected JobExecutionDao jobExecutionDao; protected JobParameters jobParameters = new JobParametersBuilder().addString("job.key", "jobKey") - .addLong("long", (long) 1) + .addLong("long", 1L) .addDouble("double", 7.7) .toJobParameters(); @@ -191,7 +191,7 @@ void testSaveJobExecution() { void testUpdateInvalidJobExecution() { // id is invalid - JobExecution execution = new JobExecution(jobInstance, (long) 29432, jobParameters); + JobExecution execution = new JobExecution(jobInstance, 29432L, jobParameters); execution.incrementVersion(); assertThrows(NoSuchObjectException.class, () -> jobExecutionDao.updateJobExecution(execution)); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobInstanceDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobInstanceDaoTests.java index 9f463d7362..5a815e04b7 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobInstanceDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractJobInstanceDaoTests.java @@ -239,7 +239,7 @@ void testCreateDuplicateInstance() { @Test void testCreationAddsVersion() { - JobInstance jobInstance = new JobInstance((long) 1, "testVersionAndId"); + JobInstance jobInstance = new JobInstance(1L, "testVersionAndId"); assertNull(jobInstance.getVersion()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractStepExecutionDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractStepExecutionDaoTests.java index 2e0c6c5a10..4fa4316c20 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractStepExecutionDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/AbstractStepExecutionDaoTests.java @@ -224,7 +224,7 @@ void testSaveAndFindExecution() { @Transactional @Test void testGetForNotExistingJobExecution() { - assertNull(dao.getStepExecution(new JobExecution(jobInstance, (long) 777, new JobParameters()), 11L)); + assertNull(dao.getStepExecution(new JobExecution(jobInstance, 777L, new JobParameters()), 11L)); } /** @@ -233,7 +233,7 @@ void testGetForNotExistingJobExecution() { @Transactional @Test void testSaveExecutionWithIdAlreadySet() { - stepExecution.setId((long) 7); + stepExecution.setId(7L); assertThrows(IllegalArgumentException.class, () -> dao.saveStepExecution(stepExecution)); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDaoTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDaoTests.java index e1a6f0dbd9..b9e95e6da5 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDaoTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/dao/JdbcJobInstanceDaoTests.java @@ -95,7 +95,7 @@ void testJobInstanceWildcard() { dao.createJobInstance("anotherJob", new JobParameters()); dao.createJobInstance("someJob", new JobParameters()); - List jobInstances = dao.findJobInstancesByName("*Job", 0, 2); + List jobInstances = dao.getJobInstances("*Job", 0, 2); assertEquals(2, jobInstances.size()); for (JobInstance instance : jobInstances) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/JobRepositoryFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/JobRepositoryFactoryBeanTests.java index a8669c4c37..fd7d0ee845 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/JobRepositoryFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/JobRepositoryFactoryBeanTests.java @@ -311,8 +311,7 @@ public void testCustomTransactionAttributesSource() throws Exception { Advisor[] advisors = target.getAdvisors(); for (Advisor advisor : advisors) { if (advisor.getAdvice() instanceof TransactionInterceptor transactionInterceptor) { - Assertions.assertEquals(transactionAttributeSource, - transactionInterceptor.getTransactionAttributeSource()); + assertEquals(transactionAttributeSource, transactionInterceptor.getTransactionAttributeSource()); } } } @@ -334,19 +333,21 @@ void testCustomLobType() throws Exception { @Test public void testDefaultJobKeyGenerator() throws Exception { testCreateRepository(); - JobKeyGenerator jobKeyGenerator = (JobKeyGenerator) ReflectionTestUtils.getField(factory, "jobKeyGenerator"); - Assertions.assertEquals(DefaultJobKeyGenerator.class, jobKeyGenerator.getClass()); + @SuppressWarnings("rawtypes") + JobKeyGenerator jobKeyGenerator = (JobKeyGenerator) ReflectionTestUtils.getField(factory, "jobKeyGenerator"); + assertEquals(DefaultJobKeyGenerator.class, jobKeyGenerator.getClass()); } @Test public void testCustomJobKeyGenerator() throws Exception { factory.setJobKeyGenerator(new CustomJobKeyGenerator()); testCreateRepository(); - JobKeyGenerator jobKeyGenerator = (JobKeyGenerator) ReflectionTestUtils.getField(factory, "jobKeyGenerator"); - Assertions.assertEquals(CustomJobKeyGenerator.class, jobKeyGenerator.getClass()); + @SuppressWarnings("rawtypes") + JobKeyGenerator jobKeyGenerator = (JobKeyGenerator) ReflectionTestUtils.getField(factory, "jobKeyGenerator"); + assertEquals(CustomJobKeyGenerator.class, jobKeyGenerator.getClass()); } - class CustomJobKeyGenerator implements JobKeyGenerator { + static class CustomJobKeyGenerator implements JobKeyGenerator { @Override public String generateKey(String source) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryTests.java index 5b903d0f14..8556dd22e8 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/repository/support/SimpleJobRepositoryTests.java @@ -140,6 +140,7 @@ void testGetJobNames() { verify(this.jobInstanceDao).getJobNames(); } + @SuppressWarnings("removal") @Test void testFindJobInstancesByName() { // given @@ -151,9 +152,10 @@ void testFindJobInstancesByName() { this.jobRepository.findJobInstancesByName(jobName, start, count); // then - verify(this.jobInstanceDao).findJobInstancesByName(jobName, start, count); + verify(this.jobInstanceDao).getJobInstances(jobName, start, count); } + @SuppressWarnings("removal") @Test void testFindJobExecutions() { // when diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/StepLocatorStepFactoryBeanTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/StepLocatorStepFactoryBeanTests.java index 7af0831ce5..5a5550927c 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/StepLocatorStepFactoryBeanTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/StepLocatorStepFactoryBeanTests.java @@ -74,7 +74,7 @@ public void execute(StepExecution stepExecution) throws JobInterruptedException @Test void testGetObjectType() { - assertTrue((new StepLocatorStepFactoryBean()).getObjectType().isAssignableFrom(Step.class)); + assertTrue(new StepLocatorStepFactoryBean().getObjectType().isAssignableFrom(Step.class)); } } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/AbstractExceptionThrowingItemHandlerStub.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/AbstractExceptionThrowingItemHandlerStub.java index f7bdfaeaf4..466f7bbf14 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/AbstractExceptionThrowingItemHandlerStub.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/AbstractExceptionThrowingItemHandlerStub.java @@ -66,11 +66,11 @@ public void clearFailures() { protected void checkFailure(T item) throws Exception { if (isFailure(item)) { Throwable t = getException("Intended Failure: " + item); - if (t instanceof Exception) { - throw (Exception) t; + if (t instanceof Exception e) { + throw e; } - if (t instanceof Error) { - throw (Error) t; + if (t instanceof Error error) { + throw error; } throw new IllegalStateException("Unexpected non-Error Throwable"); } diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProviderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProviderTests.java index a1b45c1fee..1e0076dbf5 100755 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProviderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantChunkProviderTests.java @@ -54,12 +54,8 @@ void testProvide() throws Exception { @Test void testProvideWithOverflow() throws Exception { - provider = new FaultTolerantChunkProvider<>(new ItemReader<>() { - @Nullable - @Override - public String read() throws Exception, UnexpectedInputException, ParseException { - throw new RuntimeException("Planned"); - } + provider = new FaultTolerantChunkProvider<>(() -> { + throw new RuntimeException("Planned"); }, new RepeatTemplate()); provider.setSkipPolicy(new LimitCheckingItemSkipPolicy(Integer.MAX_VALUE, Collections., Boolean>singletonMap(Exception.class, Boolean.TRUE))); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanNonBufferingTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanNonBufferingTests.java index 78e138272c..01f09822f7 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanNonBufferingTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanNonBufferingTests.java @@ -87,7 +87,6 @@ void setUp() throws Exception { */ @Test void testSkip() throws Exception { - @SuppressWarnings("unchecked") SkipListener skipListener = mock(); skipListener.onSkipInWrite("3", exception); skipListener.onSkipInWrite("4", exception); @@ -142,7 +141,7 @@ public SkipWriterStub(Collection failures) { } @Override - public void write(Chunk items) throws Exception { + public void write(Chunk items) { logger.debug("Writing: " + items); for (String item : items) { if (failures.contains(item)) { diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRetryTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRetryTests.java index 10100b569c..6adc396b32 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRetryTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/FaultTolerantStepFactoryBeanRetryTests.java @@ -661,19 +661,15 @@ void testCacheLimitWithRetry() throws Exception { factory.setSkipLimit(10); // set the cache limit stupidly low factory.setRetryContextCache(new MapRetryContextCache(0)); - ItemReader provider = new ItemReader<>() { - @Nullable - @Override - public String read() { - String item = String.valueOf(count); - provided.add(item); - count++; - if (count >= 10) { - // prevent infinite loop in worst case scenario - return null; - } - return item; + ItemReader provider = () -> { + String item = String.valueOf(count); + provided.add(item); + count++; + if (count >= 10) { + // prevent infinite loop in worst case scenario + return null; } + return item; }; ItemWriter itemWriter = chunk -> { processed.addAll(chunk.getItems()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProviderTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProviderTests.java index 0525a0cb4e..2368a9ca66 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProviderTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/item/SimpleChunkProviderTests.java @@ -49,14 +49,12 @@ void testProvide() throws Exception { void testProvideWithOverflow() throws Exception { provider = new SimpleChunkProvider<>(new ListItemReader<>(Arrays.asList("foo", "bar")), new RepeatTemplate()) { @Override - protected String read(StepContribution contribution, Chunk chunk) - throws SkipOverflowException, Exception { + protected String read(StepContribution contribution, Chunk chunk) { chunk.skip(new RuntimeException("Planned")); throw new SkipOverflowException("Overflow"); } }; - Chunk chunk = null; - chunk = provider.provide(contribution); + Chunk chunk = provider.provide(contribution); assertNotNull(chunk); assertEquals(0, chunk.getItems().size()); assertEquals(1, chunk.getErrors().size()); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/ConfigurableSystemProcessExitCodeMapperTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/ConfigurableSystemProcessExitCodeMapperTests.java index 7e23e13dfa..4a10f757cf 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/ConfigurableSystemProcessExitCodeMapperTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/ConfigurableSystemProcessExitCodeMapperTests.java @@ -36,16 +36,13 @@ class ConfigurableSystemProcessExitCodeMapperTests { */ @Test void testMapping() { - Map mappings = new HashMap<>() { - { - put(0, ExitStatus.COMPLETED); - put(1, ExitStatus.FAILED); - put(2, ExitStatus.EXECUTING); - put(3, ExitStatus.NOOP); - put(4, ExitStatus.UNKNOWN); - put(ConfigurableSystemProcessExitCodeMapper.ELSE_KEY, ExitStatus.UNKNOWN); - } - }; + Map mappings = Map.of( // + 0, ExitStatus.COMPLETED, // + 1, ExitStatus.FAILED, // + 2, ExitStatus.EXECUTING, // + 3, ExitStatus.NOOP, // + 4, ExitStatus.UNKNOWN, // + ConfigurableSystemProcessExitCodeMapper.ELSE_KEY, ExitStatus.UNKNOWN); mapper.setMappings(mappings); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java index 1e008d43c8..44e2367901 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/StepExecutorInterruptionTests.java @@ -103,22 +103,18 @@ void testInterruptStep() throws Exception { RepeatTemplate template = new RepeatTemplate(); // N.B, If we don't set the completion policy it might run forever template.setCompletionPolicy(new SimpleCompletionPolicy(2)); - step.setTasklet(new TestingChunkOrientedTasklet<>(new ItemReader<>() { - @Nullable - @Override - public Object read() throws Exception { - // do something non-trivial (and not Thread.sleep()) - double foo = 1; - for (int i = 2; i < 250; i++) { - foo = foo * i; - } - - if (foo != 1) { - return foo; - } - else { - return null; - } + step.setTasklet(new TestingChunkOrientedTasklet<>(() -> { + // do something non-trivial (and not Thread.sleep()) + double foo = 1; + for (int i = 2; i < 250; i++) { + foo = foo * i; + } + + if (foo != 1) { + return foo; + } + else { + return null; } }, itemWriter, template)); @@ -166,13 +162,7 @@ public void release() { Thread processingThread = createThread(stepExecution); - step.setTasklet(new TestingChunkOrientedTasklet<>(new ItemReader<>() { - @Nullable - @Override - public Object read() throws Exception { - return null; - } - }, itemWriter)); + step.setTasklet(new TestingChunkOrientedTasklet<>(() -> null, itemWriter)); processingThread.start(); Thread.sleep(100); @@ -212,12 +202,8 @@ public void release() { } }); - step.setTasklet(new TestingChunkOrientedTasklet<>(new ItemReader<>() { - @Nullable - @Override - public Object read() throws Exception { - throw new RuntimeException("Planned!"); - } + step.setTasklet(new TestingChunkOrientedTasklet<>(() -> { + throw new RuntimeException("Planned!"); }, itemWriter)); jobRepository.add(stepExecution); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/SystemCommandTaskletIntegrationTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/SystemCommandTaskletIntegrationTests.java index 8d85218c1f..2849d45e0f 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/SystemCommandTaskletIntegrationTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/SystemCommandTaskletIntegrationTests.java @@ -184,7 +184,7 @@ void testInterruption() throws Exception { * Command Runner is required to be set. */ @Test - public void testCommandRunnerNotSet() throws Exception { + public void testCommandRunnerNotSet() { tasklet.setCommandRunner(null); assertThrows(IllegalStateException.class, tasklet::afterPropertiesSet); } @@ -194,7 +194,10 @@ public void testCommandRunnerNotSet() throws Exception { */ @Test void testCommandNotSet() { - tasklet.setCommand(null); + tasklet.setCommand(); + assertThrows(IllegalStateException.class, tasklet::afterPropertiesSet); + + tasklet.setCommand((String[]) null); assertThrows(IllegalStateException.class, tasklet::afterPropertiesSet); tasklet.setCommand(""); diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java index 0d9400e6b2..3611c4f9ce 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/step/tasklet/TaskletStepTests.java @@ -242,14 +242,8 @@ void testRepository() throws Exception { @Test void testIncrementRollbackCount() { - ItemReader itemReader = new ItemReader<>() { - - @Nullable - @Override - public String read() throws Exception { - throw new RuntimeException(); - } - + ItemReader itemReader = () -> { + throw new RuntimeException(); }; step.setTasklet(new TestingChunkOrientedTasklet<>(itemReader, itemWriter)); @@ -268,14 +262,8 @@ public String read() throws Exception { @Test void testExitCodeDefaultClassification() { - ItemReader itemReader = new ItemReader<>() { - - @Nullable - @Override - public String read() throws Exception { - throw new RuntimeException(); - - } + ItemReader itemReader = () -> { + throw new RuntimeException(); }; @@ -295,14 +283,8 @@ public String read() throws Exception { @Test void testExitCodeCustomClassification() { - ItemReader itemReader = new ItemReader<>() { - - @Nullable - @Override - public String read() throws Exception { - throw new RuntimeException(); - - } + ItemReader itemReader = () -> { + throw new RuntimeException(); }; @@ -407,13 +389,7 @@ void testNoSaveExecutionAttributesRestartableJob() { */ @Test void testRestartJobOnNonRestartableTasklet() throws Exception { - step.setTasklet(new TestingChunkOrientedTasklet<>(new ItemReader<>() { - @Nullable - @Override - public String read() throws Exception { - return "foo"; - } - }, itemWriter)); + step.setTasklet(new TestingChunkOrientedTasklet<>(() -> "foo", itemWriter)); JobExecution jobExecution = new JobExecution(jobInstance, jobParameters); StepExecution stepExecution = new StepExecution(step.getName(), jobExecution); @@ -599,14 +575,8 @@ void testStatusForInterruptedException() throws Exception { step.setInterruptionPolicy(interruptionPolicy); - ItemReader itemReader = new ItemReader<>() { - - @Nullable - @Override - public String read() throws Exception { - throw new RuntimeException(); - - } + ItemReader itemReader = () -> { + throw new RuntimeException(); }; @@ -627,13 +597,9 @@ public String read() throws Exception { @Test void testStatusForNormalFailure() throws Exception { - ItemReader itemReader = new ItemReader<>() { - @Nullable - @Override - public String read() throws Exception { - // Trigger a rollback - throw new RuntimeException("Foo"); - } + ItemReader itemReader = () -> { + // Trigger a rollback + throw new RuntimeException("Foo"); }; step.setTasklet(new TestingChunkOrientedTasklet<>(itemReader, itemWriter)); @@ -652,13 +618,9 @@ public String read() throws Exception { @Test void testStatusForErrorFailure() throws Exception { - ItemReader itemReader = new ItemReader<>() { - @Nullable - @Override - public String read() throws Exception { - // Trigger a rollback - throw new Error("Foo"); - } + ItemReader itemReader = () -> { + // Trigger a rollback + throw new Error("Foo"); }; step.setTasklet(new TestingChunkOrientedTasklet<>(itemReader, itemWriter)); @@ -678,13 +640,9 @@ public String read() throws Exception { @Test void testStatusForResetFailedException() throws Exception { - ItemReader itemReader = new ItemReader<>() { - @Nullable - @Override - public String read() throws Exception { - // Trigger a rollback - throw new RuntimeException("Foo"); - } + ItemReader itemReader = () -> { + // Trigger a rollback + throw new RuntimeException("Foo"); }; step.setTasklet(new TestingChunkOrientedTasklet<>(itemReader, itemWriter)); step.setTransactionManager(new ResourcelessTransactionManager() { diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/Chunk.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/Chunk.java index 52895ca79d..c8347996db 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/Chunk.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/Chunk.java @@ -26,7 +26,7 @@ /** * Encapsulation of a list of items to be processed and possibly a list of failed items to - * be skipped. To mark an item as skipped clients should iterate over the chunk using the + * be skipped. To mark an item as skipped, clients should iterate over the chunk using the * {@link #iterator()} method, and if there is a failure call * {@link Chunk.ChunkIterator#remove()} on the iterator. The skipped items are then * available through the chunk. @@ -130,7 +130,7 @@ public void skip(Exception e) { } /** - * @return true if there are no items in the chunk + * @return {@code true} if there are no items in the chunk */ public boolean isEmpty() { return items.isEmpty(); diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/AbstractMethodInvokingDelegator.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/AbstractMethodInvokingDelegator.java index c60d31ef34..4a0665ab12 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/AbstractMethodInvokingDelegator.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/AbstractMethodInvokingDelegator.java @@ -29,9 +29,9 @@ import org.springframework.util.StringUtils; /** - * Superclass for delegating classes which dynamically call a custom method of injected - * object. Provides convenient API for dynamic method invocation shielding subclasses from - * low-level details and exception handling. + * Superclass for delegating classes which dynamically call a custom method of an injected + * object. Provides a convenient API for dynamic method invocation shielding subclasses + * from low-level details and exception handling. *

* {@link Exception}s thrown by a successfully invoked delegate method are re-thrown * without wrapping. In case the delegate method throws a {@link Throwable} that doesn't @@ -164,7 +164,7 @@ private boolean targetClassDeclaresTargetMethod() { if (arguments[j] == null) { continue; } - if (!(ClassUtils.isAssignableValue(params[j], arguments[j]))) { + if (!ClassUtils.isAssignableValue(params[j], arguments[j])) { argumentsMatchParameters = false; } } @@ -205,7 +205,7 @@ public void setTargetMethod(String targetMethod) { * will be supplied at runtime. */ public void setArguments(Object[] arguments) { - this.arguments = arguments == null ? null : Arrays.asList(arguments).toArray(); + this.arguments = arguments == null ? null : arguments.clone(); } /** diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/PropertyExtractingDelegatingItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/PropertyExtractingDelegatingItemWriter.java index 75b35c7dab..ea1be22468 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/PropertyExtractingDelegatingItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/adapter/PropertyExtractingDelegatingItemWriter.java @@ -77,8 +77,7 @@ public void afterPropertiesSet() throws Exception { * e.g. address.city */ public void setFieldsUsedAsTargetMethodArguments(String[] fieldsUsedAsMethodArguments) { - this.fieldsUsedAsTargetMethodArguments = Arrays.asList(fieldsUsedAsMethodArguments) - .toArray(new String[fieldsUsedAsMethodArguments.length]); + this.fieldsUsedAsTargetMethodArguments = fieldsUsedAsMethodArguments.clone(); } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/RepositoryItemReader.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/RepositoryItemReader.java index 98ce9941f3..2e12b299c0 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/RepositoryItemReader.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/data/RepositoryItemReader.java @@ -44,7 +44,7 @@ /** *

* A {@link org.springframework.batch.item.ItemReader} that reads records utilizing a - * {@link org.springframework.data.repository.PagingAndSortingRepository}. + * {@link PagingAndSortingRepository}. *

* *

@@ -54,9 +54,8 @@ *

* *

- * The reader must be configured with a - * {@link org.springframework.data.repository.PagingAndSortingRepository}, a - * {@link org.springframework.data.domain.Sort}, and a pageSize greater than 0. + * The reader must be configured with a {@link PagingAndSortingRepository}, a + * {@link Sort}, and a pageSize greater than 0. *

* *

@@ -134,8 +133,7 @@ public void setPageSize(int pageSize) { } /** - * The {@link org.springframework.data.repository.PagingAndSortingRepository} - * implementation used to read input from. + * The {@link PagingAndSortingRepository} implementation used to read input from. * @param repository underlying repository for input to be read from. */ public void setRepository(PagingAndSortingRepository repository) { diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/AbstractCursorItemReader.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/AbstractCursorItemReader.java index 92e23beb83..534339748d 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/AbstractCursorItemReader.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/AbstractCursorItemReader.java @@ -400,8 +400,8 @@ protected void doClose() throws Exception { this.con.setAutoCommit(this.initialConnectionAutoCommit); } - if (useSharedExtendedConnection && dataSource instanceof ExtendedConnectionDataSourceProxy) { - ((ExtendedConnectionDataSourceProxy) dataSource).stopCloseSuppression(this.con); + if (useSharedExtendedConnection && dataSource instanceof ExtendedConnectionDataSourceProxy dataSourceProxy) { + dataSourceProxy.stopCloseSuppression(this.con); if (!TransactionSynchronizationManager.isActualTransactionActive()) { DataSourceUtils.releaseConnection(con, dataSource); } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/AbstractSqlPagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/AbstractSqlPagingQueryProvider.java index dc78066fc5..b60cdfadf9 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/AbstractSqlPagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/AbstractSqlPagingQueryProvider.java @@ -146,7 +146,7 @@ public void setSortKeys(Map sortKeys) { /** * A Map<String, Boolean> of sort columns as the key and boolean for * ascending/descending (ascending = true). - * @return sortKey key to use to sort and limit page content + * @return keys to use to sort and limit page content */ @Override public Map getSortKeys() { @@ -214,7 +214,7 @@ public void init(DataSource dataSource) throws Exception { /** * Method generating the query string to be used for retrieving the pages following - * the first page. This method must be implemented in sub classes. + * the first page. This method must be implemented in subclasses. * @param pageSize number of rows to read per page * @return query string */ diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/Db2PagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/Db2PagingQueryProvider.java index 660eb430b9..8bafc6906f 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/Db2PagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/Db2PagingQueryProvider.java @@ -45,7 +45,7 @@ public String generateRemainingPagesQuery(int pageSize) { } private String buildLimitClause(int pageSize) { - return new StringBuilder().append("FETCH FIRST ").append(pageSize).append(" ROWS ONLY").toString(); + return "FETCH FIRST " + pageSize + " ROWS ONLY"; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/DerbyPagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/DerbyPagingQueryProvider.java index 015454f90e..ec640e0088 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/DerbyPagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/DerbyPagingQueryProvider.java @@ -46,7 +46,7 @@ public String generateRemainingPagesQuery(int pageSize) { } private String buildLimitClause(int pageSize) { - return new StringBuilder("FETCH FIRST ").append(pageSize).append(" ROWS ONLY").toString(); + return "FETCH FIRST " + pageSize + " ROWS ONLY"; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/H2PagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/H2PagingQueryProvider.java index 5f358b7cd2..3de7e01f9a 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/H2PagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/H2PagingQueryProvider.java @@ -38,7 +38,7 @@ public String generateRemainingPagesQuery(int pageSize) { } private String buildLimitClause(int pageSize) { - return new StringBuilder().append("FETCH NEXT ").append(pageSize).append(" ROWS ONLY").toString(); + return "FETCH NEXT " + pageSize + " ROWS ONLY"; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/HanaPagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/HanaPagingQueryProvider.java index 54bd06d23d..c74298b300 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/HanaPagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/HanaPagingQueryProvider.java @@ -44,7 +44,7 @@ public String generateRemainingPagesQuery(int pageSize) { } private String buildLimitClause(int pageSize) { - return new StringBuilder().append("LIMIT ").append(pageSize).toString(); + return "LIMIT " + pageSize; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/HsqlPagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/HsqlPagingQueryProvider.java index 49e3741a4f..94d17b3257 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/HsqlPagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/HsqlPagingQueryProvider.java @@ -46,7 +46,7 @@ public String generateRemainingPagesQuery(int pageSize) { } private String buildTopClause(int pageSize) { - return new StringBuilder().append("TOP ").append(pageSize).toString(); + return "TOP " + pageSize; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/MariaDBPagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/MariaDBPagingQueryProvider.java index 25f47b1506..cdbf4eb9d2 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/MariaDBPagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/MariaDBPagingQueryProvider.java @@ -44,7 +44,7 @@ public String generateRemainingPagesQuery(int pageSize) { } private String buildLimitClause(int pageSize) { - return new StringBuilder().append("LIMIT ").append(pageSize).toString(); + return "LIMIT " + pageSize; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/MySqlPagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/MySqlPagingQueryProvider.java index ad2eba7cf4..0b8448d4ca 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/MySqlPagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/MySqlPagingQueryProvider.java @@ -45,7 +45,7 @@ public String generateRemainingPagesQuery(int pageSize) { } private String buildLimitClause(int pageSize) { - return new StringBuilder().append("LIMIT ").append(pageSize).toString(); + return "LIMIT " + pageSize; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/OraclePagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/OraclePagingQueryProvider.java index 9958727437..5fd902821d 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/OraclePagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/OraclePagingQueryProvider.java @@ -38,7 +38,7 @@ public String generateRemainingPagesQuery(int pageSize) { } private String buildRowNumClause(int pageSize) { - return new StringBuilder().append("ROWNUM <= ").append(pageSize).toString(); + return "ROWNUM <= " + pageSize; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/PostgresPagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/PostgresPagingQueryProvider.java index 4b65d2e3d9..fb3406180f 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/PostgresPagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/PostgresPagingQueryProvider.java @@ -50,7 +50,7 @@ public String generateRemainingPagesQuery(int pageSize) { } private String buildLimitClause(int pageSize) { - return new StringBuilder().append("LIMIT ").append(pageSize).toString(); + return "LIMIT " + pageSize; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/SqlServerPagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/SqlServerPagingQueryProvider.java index b1c79763b1..5d0989f73d 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/SqlServerPagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/SqlServerPagingQueryProvider.java @@ -46,7 +46,7 @@ public String generateRemainingPagesQuery(int pageSize) { } private String buildTopClause(int pageSize) { - return new StringBuilder().append("TOP ").append(pageSize).toString(); + return "TOP " + pageSize; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/SqlitePagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/SqlitePagingQueryProvider.java index cc44ef6a4a..01406388a6 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/SqlitePagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/SqlitePagingQueryProvider.java @@ -45,7 +45,7 @@ public String generateRemainingPagesQuery(int pageSize) { } private String buildLimitClause(int pageSize) { - return new StringBuilder().append("LIMIT ").append(pageSize).toString(); + return "LIMIT " + pageSize; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/SybasePagingQueryProvider.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/SybasePagingQueryProvider.java index ade0af5266..26261d1246 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/SybasePagingQueryProvider.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/database/support/SybasePagingQueryProvider.java @@ -46,7 +46,7 @@ public String generateRemainingPagesQuery(int pageSize) { } private String buildTopClause(int pageSize) { - return new StringBuilder().append("TOP ").append(pageSize).toString(); + return "TOP " + pageSize; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/MultiResourceItemReader.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/MultiResourceItemReader.java index 341f4222eb..63ebf7617e 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/MultiResourceItemReader.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/MultiResourceItemReader.java @@ -141,8 +141,8 @@ private T readNextItem() throws Exception { private T readFromDelegate() throws Exception { T item = delegate.read(); - if (item instanceof ResourceAware) { - ((ResourceAware) item).setResource(resources[currentResource]); + if (item instanceof ResourceAware resourceAware) { + resourceAware.setResource(resources[currentResource]); } return item; } @@ -222,7 +222,7 @@ public void setDelegate(ResourceAwareItemReaderItemStream delegate) } /** - * Set the boolean indicating whether or not state should be saved in the provided + * Set the boolean indicating whether state should be saved in the provided * {@link ExecutionContext} during the {@link ItemStream} call to update. * @param saveState true to update ExecutionContext. False do not update * ExecutionContext. @@ -244,7 +244,7 @@ public void setComparator(Comparator comparator) { */ public void setResources(Resource[] resources) { Assert.notNull(resources, "The resources must not be null"); - this.resources = Arrays.asList(resources).toArray(new Resource[resources.length]); + this.resources = resources.clone(); } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/SimpleBinaryBufferedReaderFactory.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/SimpleBinaryBufferedReaderFactory.java index 6b8fede984..f41f4d1d8f 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/SimpleBinaryBufferedReaderFactory.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/SimpleBinaryBufferedReaderFactory.java @@ -53,7 +53,7 @@ public void setLineEnding(String lineEnding) { } @Override - public BufferedReader create(Resource resource, String encoding) throws UnsupportedEncodingException, IOException { + public BufferedReader create(Resource resource, String encoding) throws IOException { return new BinaryBufferedReader(new InputStreamReader(resource.getInputStream(), encoding), lineEnding); } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/mapping/BeanWrapperFieldSetMapper.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/mapping/BeanWrapperFieldSetMapper.java index 1364f71445..81bfa97739 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/mapping/BeanWrapperFieldSetMapper.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/mapping/BeanWrapperFieldSetMapper.java @@ -291,7 +291,7 @@ private String findPropertyName(Object bean, String key) { // looking for a match. if (index > 0) { prefix = key.substring(0, index); - suffix = key.substring(index + 1, key.length()); + suffix = key.substring(index + 1); String nestedName = findPropertyName(bean, prefix); if (nestedName == null) { return null; @@ -424,9 +424,7 @@ public boolean equals(Object obj) { } else if (!cls.equals(other.cls)) return false; - if (distance != other.distance) - return false; - return true; + return distance == other.distance; } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/AbstractLineTokenizer.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/AbstractLineTokenizer.java index 5f53e851d7..b4fa1572fe 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/AbstractLineTokenizer.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/AbstractLineTokenizer.java @@ -96,7 +96,7 @@ public void setNames(String... names) { } /** - * @return true if column names have been specified + * @return {@code true} if column names have been specified * @see #setNames(String[]) */ public boolean hasNames() { @@ -121,7 +121,7 @@ public FieldSet tokenize(@Nullable String line) { List tokens = new ArrayList<>(doTokenize(line)); // if names are set and strict flag is false - if ((names.length != 0) && (!strict)) { + if (names.length != 0 && !strict) { adjustTokenCountIfNecessary(tokens); } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/BeanWrapperFieldExtractor.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/BeanWrapperFieldExtractor.java index 083839d2ca..278e902bd4 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/BeanWrapperFieldExtractor.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/BeanWrapperFieldExtractor.java @@ -41,12 +41,9 @@ public class BeanWrapperFieldExtractor implements FieldExtractor, Initiali */ public void setNames(String[] names) { Assert.notNull(names, "Names must be non-null"); - this.names = Arrays.asList(names).toArray(new String[names.length]); + this.names = names.clone(); } - /** - * @see org.springframework.batch.item.file.transform.FieldExtractor#extract(java.lang.Object) - */ @Override public Object[] extract(T item) { List values = new ArrayList<>(); diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/ConversionException.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/ConversionException.java index 1f59b0174d..f7fcf437eb 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/ConversionException.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/ConversionException.java @@ -20,6 +20,7 @@ * @author Mahmoud Ben Hassine * */ +@SuppressWarnings("unused") // FIXME no usage - should it be deprecated for removal? public class ConversionException extends RuntimeException { /** diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/DefaultFieldSet.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/DefaultFieldSet.java index 540a8236aa..c1c1d1b489 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/DefaultFieldSet.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/DefaultFieldSet.java @@ -67,9 +67,9 @@ public class DefaultFieldSet implements FieldSet { */ public final void setNumberFormat(NumberFormat numberFormat) { this.numberFormat = numberFormat; - if (numberFormat instanceof DecimalFormat) { - grouping = String.valueOf(((DecimalFormat) numberFormat).getDecimalFormatSymbols().getGroupingSeparator()); - decimal = String.valueOf(((DecimalFormat) numberFormat).getDecimalFormatSymbols().getDecimalSeparator()); + if (numberFormat instanceof DecimalFormat decimalFormat) { + grouping = String.valueOf(decimalFormat.getDecimalFormatSymbols().getGroupingSeparator()); + decimal = String.valueOf(decimalFormat.getDecimalFormatSymbols().getDecimalSeparator()); } } @@ -533,8 +533,8 @@ private Date parseDate(String readAndTrim, DateFormat dateFormat) { } catch (ParseException e) { String pattern; - if (dateFormat instanceof SimpleDateFormat) { - pattern = ((SimpleDateFormat) dateFormat).toPattern(); + if (dateFormat instanceof SimpleDateFormat simpleDateFormat) { + pattern = simpleDateFormat.toPattern(); } else { pattern = dateFormat.toString(); diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/DelimitedLineTokenizer.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/DelimitedLineTokenizer.java index 7fdf1fe7e6..bb14e462dd 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/DelimitedLineTokenizer.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/DelimitedLineTokenizer.java @@ -168,7 +168,7 @@ else if (!isEnd) { fieldCount++; - if (isEnd && (isDelimiter)) { + if (isEnd && isDelimiter) { if (includedFields == null || includedFields.contains(fieldCount)) { tokens.add(""); } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/PassThroughFieldExtractor.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/PassThroughFieldExtractor.java index 98630c0216..f3b683a333 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/PassThroughFieldExtractor.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/PassThroughFieldExtractor.java @@ -59,8 +59,8 @@ public Object[] extract(T item) { return ((Map) item).values().toArray(); } - if (item instanceof FieldSet) { - return ((FieldSet) item).getValues(); + if (item instanceof FieldSet fieldSet) { + return fieldSet.getValues(); } return new Object[] { item }; diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/RangeArrayPropertyEditor.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/RangeArrayPropertyEditor.java index 67afcb946c..e382bfca8c 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/RangeArrayPropertyEditor.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/file/transform/RangeArrayPropertyEditor.java @@ -76,12 +76,12 @@ public void setAsText(String text) throws IllegalArgumentException { int min; int max; - if ((range.length == 1) && (StringUtils.hasText(range[0]))) { + if (range.length == 1 && StringUtils.hasText(range[0])) { min = Integer.parseInt(range[0].trim()); // correct max value will be assigned later ranges[i] = new Range(min); } - else if ((range.length == 2) && (StringUtils.hasText(range[0])) && (StringUtils.hasText(range[1]))) { + else if (range.length == 2 && StringUtils.hasText(range[0]) && StringUtils.hasText(range[1])) { min = Integer.parseInt(range[0].trim()); max = Integer.parseInt(range[1].trim()); ranges[i] = new Range(min, max); diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsMethodArgumentsKeyGenerator.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsMethodArgumentsKeyGenerator.java index 7cd35de364..45669fab80 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsMethodArgumentsKeyGenerator.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsMethodArgumentsKeyGenerator.java @@ -43,9 +43,9 @@ public class JmsMethodArgumentsKeyGenerator implements MethodArgumentsKeyGenerat @Override public Object getKey(Object[] items) { for (Object item : items) { - if (item instanceof Message) { + if (item instanceof Message message) { try { - return ((Message) item).getJMSMessageID(); + return message.getJMSMessageID(); } catch (JMSException e) { throw new UnexpectedInputException("Could not extract message ID", e); diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsMethodInvocationRecoverer.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsMethodInvocationRecoverer.java index 2afb4399eb..dd9dcd6b3e 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsMethodInvocationRecoverer.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsMethodInvocationRecoverer.java @@ -43,11 +43,10 @@ public void setJmsTemplate(JmsOperations jmsTemplate) { } /** - * Send one message per item in the arguments list using the default destination of - * the jms template. If the recovery is successful {@code null} is returned. + * Send one message per item in the argument list using the default destination of the + * jms template. If the recovery is successful {@code null} is returned. * - * @see org.springframework.retry.interceptor.MethodInvocationRecoverer#recover(Object[], - * Throwable) + * @see MethodInvocationRecoverer#recover(Object[], Throwable) */ @Override @Nullable diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsNewMethodArgumentsIdentifier.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsNewMethodArgumentsIdentifier.java index d5090673a1..6385e6d17f 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsNewMethodArgumentsIdentifier.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/jms/JmsNewMethodArgumentsIdentifier.java @@ -42,9 +42,9 @@ public class JmsNewMethodArgumentsIdentifier implements NewMethodArgumentsIde public boolean isNew(Object[] args) { for (Object item : args) { - if (item instanceof Message) { + if (item instanceof Message message) { try { - return !((Message) item).getJMSRedelivered(); + return !message.getJMSRedelivered(); } catch (JMSException e) { throw new UnexpectedInputException("Could not extract message ID", e); diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractFileItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractFileItemWriter.java index c3d3a00bbb..a726680f99 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractFileItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractFileItemWriter.java @@ -404,14 +404,12 @@ protected class OutputState { * @throws IOException If unable to get the offset position */ public long position() throws IOException { - long pos = 0; - if (fileChannel == null) { return 0; } outputBufferedWriter.flush(); - pos = fileChannel.position(); + long pos = fileChannel.position(); if (transactional) { pos += ((TransactionAwareBufferedWriter) outputBufferedWriter).getBufferSize(); } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractItemCountingItemStreamItemReader.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractItemCountingItemStreamItemReader.java index c25fc437ce..d289404c47 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractItemCountingItemStreamItemReader.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/AbstractItemCountingItemStreamItemReader.java @@ -91,8 +91,8 @@ public T read() throws Exception { } currentItemCount++; T item = doRead(); - if (item instanceof ItemCountAware) { - ((ItemCountAware) item).setItemCount(currentItemCount); + if (item instanceof ItemCountAware itemCountAware) { + itemCountAware.setItemCount(currentItemCount); } return item; } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/CompositeItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/CompositeItemWriter.java index 730213c965..74b5c64878 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/CompositeItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/CompositeItemWriter.java @@ -116,9 +116,9 @@ public void close() throws ItemStreamException { List exceptions = new ArrayList<>(); for (ItemWriter writer : delegates) { - if (!ignoreItemStream && (writer instanceof ItemStream)) { + if (!ignoreItemStream && (writer instanceof ItemStream itemStream)) { try { - ((ItemStream) writer).close(); + itemStream.close(); } catch (Exception e) { exceptions.add(e); @@ -137,8 +137,8 @@ public void close() throws ItemStreamException { @Override public void open(ExecutionContext executionContext) throws ItemStreamException { for (ItemWriter writer : delegates) { - if (!ignoreItemStream && (writer instanceof ItemStream)) { - ((ItemStream) writer).open(executionContext); + if (!ignoreItemStream && (writer instanceof ItemStream itemStream)) { + itemStream.open(executionContext); } } } @@ -146,8 +146,8 @@ public void open(ExecutionContext executionContext) throws ItemStreamException { @Override public void update(ExecutionContext executionContext) throws ItemStreamException { for (ItemWriter writer : delegates) { - if (!ignoreItemStream && (writer instanceof ItemStream)) { - ((ItemStream) writer).update(executionContext); + if (!ignoreItemStream && (writer instanceof ItemStream itemStream)) { + itemStream.update(executionContext); } } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ScriptItemProcessor.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ScriptItemProcessor.java index 44e563beed..8b86d78f13 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ScriptItemProcessor.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/ScriptItemProcessor.java @@ -138,11 +138,11 @@ public void afterPropertiesSet() throws Exception { Assert.state(scriptSource == null || script == null, "Either a script source or script file must be provided, not both"); - if (scriptSource != null && scriptEvaluator instanceof StandardScriptEvaluator) { + if (scriptSource != null && scriptEvaluator instanceof StandardScriptEvaluator standardScriptEvaluator) { Assert.state(StringUtils.hasLength(language), "Language must be provided when using the default ScriptEvaluator and raw source code"); - ((StandardScriptEvaluator) scriptEvaluator).setLanguage(language); + standardScriptEvaluator.setLanguage(language); } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/SingleItemPeekableItemReader.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/SingleItemPeekableItemReader.java index 84e751e7f6..e1d25c8f0b 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/SingleItemPeekableItemReader.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/support/SingleItemPeekableItemReader.java @@ -101,10 +101,10 @@ public T peek() throws Exception { @Override public void close() throws ItemStreamException { next = null; - if (delegate instanceof ItemStream) { - ((ItemStream) delegate).close(); + if (delegate instanceof ItemStream itemStream) { + itemStream.close(); } - executionContext = new ExecutionContext(); + this.executionContext = new ExecutionContext(); } /** @@ -117,10 +117,10 @@ public void close() throws ItemStreamException { @Override public void open(ExecutionContext executionContext) throws ItemStreamException { next = null; - if (delegate instanceof ItemStream) { - ((ItemStream) delegate).open(executionContext); + if (delegate instanceof ItemStream itemStream) { + itemStream.open(executionContext); } - executionContext = new ExecutionContext(); + this.executionContext = new ExecutionContext(); } /** @@ -144,8 +144,8 @@ public void update(ExecutionContext executionContext) throws ItemStreamException } private void updateDelegate(ExecutionContext executionContext) { - if (delegate instanceof ItemStream) { - ((ItemStream) delegate).update(executionContext); + if (delegate instanceof ItemStream itemStream) { + itemStream.update(executionContext); } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemReader.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemReader.java index c10cb1e75c..c225178dc6 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemReader.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemReader.java @@ -115,15 +115,14 @@ public void setUnmarshaller(Unmarshaller unmarshaller) { } /** - * @param fragmentRootElementName name of the root element of the fragment + * @param fragmentRootElementName the name of the fragment's root element */ public void setFragmentRootElementName(String fragmentRootElementName) { setFragmentRootElementNames(new String[] { fragmentRootElementName }); } /** - * @param fragmentRootElementNames list of the names of the root element of the - * fragment + * @param fragmentRootElementNames the names of the fragment's root element */ public void setFragmentRootElementNames(String[] fragmentRootElementNames) { this.fragmentRootElementNames = new ArrayList<>(); diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemWriter.java index 2c6e803773..5422c96c9d 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/StaxEventItemWriter.java @@ -813,8 +813,8 @@ private long getPosition() { try { eventWriter.flush(); position = channel.position(); - if (bufferedWriter instanceof TransactionAwareBufferedWriter) { - position += ((TransactionAwareBufferedWriter) bufferedWriter).getBufferSize(); + if (bufferedWriter instanceof TransactionAwareBufferedWriter transactionAwareBufferedWriter) { + position += transactionAwareBufferedWriter.getBufferSize(); } } catch (Exception e) { diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/stax/NoStartEndDocumentStreamWriter.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/stax/NoStartEndDocumentStreamWriter.java index cd44345f06..9879a26b43 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/stax/NoStartEndDocumentStreamWriter.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/xml/stax/NoStartEndDocumentStreamWriter.java @@ -35,7 +35,7 @@ public NoStartEndDocumentStreamWriter(XMLEventWriter wrappedEventWriter) { @Override public void add(XMLEvent event) throws XMLStreamException { - if ((!event.isStartDocument()) && (!event.isEndDocument())) { + if (!event.isStartDocument() && !event.isEndDocument()) { wrappedEventWriter.add(event); } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/context/SynchronizedAttributeAccessor.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/context/SynchronizedAttributeAccessor.java index af6bbe8c3d..0413baa10e 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/context/SynchronizedAttributeAccessor.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/context/SynchronizedAttributeAccessor.java @@ -53,11 +53,11 @@ public boolean equals(Object other) { return true; } AttributeAccessorSupport that; - if (other instanceof SynchronizedAttributeAccessor) { - that = ((SynchronizedAttributeAccessor) other).support; + if (other instanceof SynchronizedAttributeAccessor synchronizedAttributeAccessor) { + that = synchronizedAttributeAccessor.support; } - else if (other instanceof AttributeAccessorSupport) { - that = (AttributeAccessorSupport) other; + else if (other instanceof AttributeAccessorSupport attributeAccessorSupport) { + that = attributeAccessorSupport; } else { return false; diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/interceptor/RepeatOperationsInterceptor.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/interceptor/RepeatOperationsInterceptor.java index b390e7b3f2..de3df9427a 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/interceptor/RepeatOperationsInterceptor.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/interceptor/RepeatOperationsInterceptor.java @@ -74,9 +74,9 @@ public Object invoke(final MethodInvocation invocation) throws Throwable { repeatOperations.iterate(context -> { try { - MethodInvocation clone = invocation; - if (invocation instanceof ProxyMethodInvocation) { - clone = ((ProxyMethodInvocation) invocation).invocableClone(); + MethodInvocation clone; + if (invocation instanceof ProxyMethodInvocation proxyMethodInvocation) { + clone = proxyMethodInvocation.invocableClone(); } else { throw new IllegalStateException( @@ -97,12 +97,12 @@ public Object invoke(final MethodInvocation invocation) throws Throwable { return RepeatStatus.FINISHED; } } - catch (Throwable e) { - if (e instanceof Exception) { - throw (Exception) e; + catch (Throwable t) { + if (t instanceof Exception e) { + throw e; } else { - throw new RepeatOperationsInterceptorException("Unexpected error in batch interceptor", e); + throw new RepeatOperationsInterceptorException("Unexpected error in batch interceptor", t); } } }); @@ -122,7 +122,7 @@ public Object invoke(final MethodInvocation invocation) throws Throwable { } private boolean isComplete(Object result) { - return result == null || (result instanceof Boolean) && !(Boolean) result; + return (result == null) || ((result instanceof Boolean b) && !b); } /** diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/policy/CompletionPolicySupport.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/policy/CompletionPolicySupport.java index a5acaf9358..9e375b0def 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/policy/CompletionPolicySupport.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/policy/CompletionPolicySupport.java @@ -73,8 +73,8 @@ public RepeatContext start(RepeatContext context) { */ @Override public void update(RepeatContext context) { - if (context instanceof RepeatContextSupport) { - ((RepeatContextSupport) context).increment(); + if (context instanceof RepeatContextSupport repeatContextSupport) { + repeatContextSupport.increment(); } } diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/RepeatTemplate.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/RepeatTemplate.java index 7b7af3fc68..1fc00e8bbb 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/RepeatTemplate.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/RepeatTemplate.java @@ -309,11 +309,11 @@ private void doHandle(Throwable throwable, RepeatContext context, Collection { diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/TaskExecutorRepeatTemplate.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/TaskExecutorRepeatTemplate.java index 005fefe4f7..3ee8e22617 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/TaskExecutorRepeatTemplate.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/TaskExecutorRepeatTemplate.java @@ -77,6 +77,7 @@ public void setTaskExecutor(TaskExecutor taskExecutor) { * need to synchronize access. * */ + @SuppressWarnings("removal") @Override protected RepeatStatus getNextResult(RepeatContext context, RepeatCallback callback, RepeatInternalState state) throws Throwable { @@ -134,6 +135,7 @@ protected RepeatStatus getNextResult(RepeatContext context, RepeatCallback callb * * @see org.springframework.batch.repeat.support.RepeatTemplate#waitForResults(org.springframework.batch.repeat.support.RepeatInternalState) */ + @SuppressWarnings("removal") @Override protected boolean waitForResults(RepeatInternalState state) { @@ -185,6 +187,7 @@ protected RepeatInternalState createInternalState(RepeatContext context) { * @author Dave Syer * */ + @SuppressWarnings("removal") private class ExecutingRunnable implements Runnable, ResultHolder { private final RepeatCallback callback; @@ -288,6 +291,7 @@ public RepeatContext getContext() { * @author Dave Syer * */ + @SuppressWarnings("removal") private static class ResultQueueInternalState extends RepeatInternalStateSupport { private final ResultQueue results; diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/ThrottleLimitResultQueue.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/ThrottleLimitResultQueue.java index 0fd0c215c9..6637f7951b 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/ThrottleLimitResultQueue.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/repeat/support/ThrottleLimitResultQueue.java @@ -29,6 +29,7 @@ * @author Mahmoud Ben Hassine * @deprecated since 5.0 with no replacement. Scheduled for removal in 6.0. */ +@SuppressWarnings("removal") @Deprecated(since = "5.0", forRemoval = true) public class ThrottleLimitResultQueue implements ResultQueue { diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/MethodInvokerUtils.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/MethodInvokerUtils.java index b824b36aea..10603064fa 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/MethodInvokerUtils.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/MethodInvokerUtils.java @@ -116,7 +116,7 @@ public static MethodInvoker getMethodInvokerForInterface(Class cls, String me public static MethodInvoker getMethodInvokerByAnnotation(final Class annotationType, final Object target, final Class... expectedParamTypes) { MethodInvoker mi = MethodInvokerUtils.getMethodInvokerByAnnotation(annotationType, target); - final Class targetClass = (target instanceof Advised) ? ((Advised) target).getTargetSource().getTargetClass() + final Class targetClass = (target instanceof Advised advised) ? advised.getTargetSource().getTargetClass() : target.getClass(); if (mi != null) { ReflectionUtils.doWithMethods(targetClass, method -> { @@ -156,7 +156,7 @@ public static MethodInvoker getMethodInvokerByAnnotation(final Class targetClass = (target instanceof Advised) ? ((Advised) target).getTargetSource().getTargetClass() + final Class targetClass = (target instanceof Advised advised) ? advised.getTargetSource().getTargetClass() : target.getClass(); if (targetClass == null) { // Proxy with no target cannot have annotations diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/PatternMatcher.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/PatternMatcher.java index f5f5434401..e4fdabe1a1 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/PatternMatcher.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/PatternMatcher.java @@ -46,8 +46,8 @@ public PatternMatcher(Map map) { } /** - * Lifted from AntPathMatcher in Spring Core. Tests whether or not a string matches - * against a pattern. The pattern may contain two special characters:
+ * Lifted from AntPathMatcher in Spring Core. Tests whether a string matches against a + * pattern. The pattern may contain two special characters:
* '*' means zero or more characters
* '?' means one and only one character * @param pattern pattern to match against. Must not be null. diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/SimpleMethodInvoker.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/SimpleMethodInvoker.java index a7d0856239..926dca6284 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/SimpleMethodInvoker.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/SimpleMethodInvoker.java @@ -135,7 +135,7 @@ public boolean equals(Object obj) { if (obj == this) { return true; } - return (rhs.method.equals(this.method)) && (rhs.object.equals(this.object)); + return rhs.method.equals(this.method) && rhs.object.equals(this.object); } @Override diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/transaction/TransactionAwareProxyFactory.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/transaction/TransactionAwareProxyFactory.java index c7ffbc5e3c..3a1db67527 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/transaction/TransactionAwareProxyFactory.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/support/transaction/TransactionAwareProxyFactory.java @@ -86,26 +86,26 @@ private TransactionAwareProxyFactory(T target, boolean appendOnly) { */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected final T begin(T target) { - // Unfortunately in Java 5 this method has to synchronized + // Unfortunately in Java 5 this method has to be synchronized // (works OK without in Java 6). synchronized (target) { - if (target instanceof List) { + if (target instanceof List list) { if (appendOnly) { return (T) new ArrayList(); } - return (T) new ArrayList((List) target); + return (T) new ArrayList(list); } - else if (target instanceof Set) { + else if (target instanceof Set set) { if (appendOnly) { return (T) new HashSet(); } - return (T) new HashSet((Set) target); + return (T) new HashSet(set); } - else if (target instanceof Map) { + else if (target instanceof Map map) { if (appendOnly) { return (T) new HashMap(); } - return (T) new HashMap((Map) target); + return (T) new HashMap(map); } else { throw new UnsupportedOperationException("Cannot copy target for this type: " + target.getClass()); @@ -124,11 +124,11 @@ protected void commit(T copy, T target) { // Unfortunately in Java 5 this method has to be synchronized // (works OK without in Java 6). synchronized (target) { - if (target instanceof Collection) { + if (target instanceof Collection collection) { if (!appendOnly) { - ((Collection) target).clear(); + collection.clear(); } - ((Collection) target).addAll((Collection) copy); + collection.addAll((Collection) copy); } else { if (!appendOnly) { @@ -239,11 +239,11 @@ public Object invoke(MethodInvocation invocation) throws Throwable { if (appendOnly) { String methodName = invocation.getMethod().getName(); - if ((result == null && methodName.equals("get")) - || (Boolean.FALSE.equals(result) && (methodName.startsWith("contains")) + if (((result == null) && methodName.equals("get")) + || ((Boolean.FALSE.equals(result) && methodName.startsWith("contains")) || (Boolean.TRUE.equals(result) && methodName.startsWith("isEmpty")))) { - // In appendOnly mode the result of a get might not be - // in the cache... + // In appendOnly mode, the result of a get might not be in the + // cache... return invocation.proceed(); } if (result instanceof Collection) { diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/container/jms/BatchMessageListenerContainer.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/container/jms/BatchMessageListenerContainer.java index df3c584f8c..5fab1c2686 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/container/jms/BatchMessageListenerContainer.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/container/jms/BatchMessageListenerContainer.java @@ -103,15 +103,15 @@ protected void handleListenerException(Throwable ex) { return; } logger.debug("Re-throwing exception in container."); - if (ex instanceof RuntimeException) { + if (ex instanceof RuntimeException runtimeException) { // We need to re-throw so that an enclosing non-JMS transaction can // rollback... - throw (RuntimeException) ex; + throw runtimeException; } - else if (ex instanceof Error) { - // Just re-throw Error instances because otherwise unit tests just - // swallow exceptions from EasyMock and JUnit. - throw (Error) ex; + else if (ex instanceof Error error) { + // Just re-throw Error instances because otherwise unit tests just swallow + // exceptions from EasyMock and JUnit. + throw error; } } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/container/jms/BatchMessageListenerContainerTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/container/jms/BatchMessageListenerContainerTests.java index 8ad90b66b8..fdc8769288 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/container/jms/BatchMessageListenerContainerTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/container/jms/BatchMessageListenerContainerTests.java @@ -121,8 +121,7 @@ void testNonTransactionalReceiveAndExecuteWithCallbackThrowingError() throws Exc private BatchMessageListenerContainer getContainer(RepeatTemplate template) { ConnectionFactory connectionFactory = mock(); // Yuck: we need to turn these method in base class to no-ops because the invoker - // is a private class - // we can't create for test purposes... + // is a private class we can't create for test purposes... BatchMessageListenerContainer container = new BatchMessageListenerContainer() { @Override protected void messageReceived(Object invoker, Session session) { @@ -141,12 +140,12 @@ protected void noMessageReceived(Object invoker, Session session) { return container; } - private boolean doTestWithException(final Throwable t, boolean expectRollback, int expectGetTransactionCount) + private boolean doTestWithException(Throwable t, boolean expectRollback, int expectGetTransactionCount) throws JMSException, IllegalAccessException { container.setAcceptMessagesWhileStopping(true); container.setMessageListener((MessageListener) arg0 -> { - if (t instanceof RuntimeException) - throw (RuntimeException) t; + if (t instanceof RuntimeException runtimeException) + throw runtimeException; else throw (Error) t; }); @@ -159,16 +158,14 @@ private boolean doTestWithException(final Throwable t, boolean expectRollback, i when(session.getTransacted()).thenReturn(true); } - // Expect only one call to consumer (chunk size is 2, but first one - // rolls back terminating batch)... + // Expect only one call to consumer (chunk size is 2, but first one rolls back + // terminating batch)... when(consumer.receive(1000)).thenReturn(message); if (expectRollback) { session.rollback(); } - boolean received = doExecute(session, consumer); - - return received; + return doExecute(session, consumer); } private boolean doExecute(Session session, MessageConsumer consumer) throws IllegalAccessException { diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/example/AvroTestUtils.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/example/AvroTestUtils.java index 63182ec246..bc7d6df8a1 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/example/AvroTestUtils.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/example/AvroTestUtils.java @@ -42,6 +42,7 @@ public static void main(String... args) { createTestData(); } catch (Exception e) { + // ignored } } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/example/User.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/example/User.java index 0416ff9ec8..ddf84d5a1b 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/example/User.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/avro/example/User.java @@ -119,15 +119,18 @@ public User(CharSequence name, Integer favorite_number, CharSequence favorite_co this.favorite_color = favorite_color; } + @Override public SpecificData getSpecificData() { return MODEL$; } + @Override public org.apache.avro.Schema getSchema() { return SCHEMA$; } // Used by DatumWriter. Applications should not call. + @Override public Object get(int field$) { return switch (field$) { case 0 -> name; @@ -138,7 +141,7 @@ public Object get(int field$) { } // Used by DatumReader. Applications should not call. - @SuppressWarnings(value = "unchecked") + @Override public void put(int field$, Object value$) { switch (field$) { case 0 -> name = (CharSequence) value$; @@ -476,7 +479,7 @@ public void customEncode(org.apache.avro.io.Encoder out) throws java.io.IOExcept public void customDecode(org.apache.avro.io.ResolvingDecoder in) throws java.io.IOException { org.apache.avro.Schema.Field[] fieldOrder = in.readFieldOrderIfDiff(); if (fieldOrder == null) { - this.name = in.readString(this.name instanceof Utf8 ? (Utf8) this.name : null); + this.name = in.readString(this.name instanceof Utf8 utf8 ? utf8 : null); if (in.readIndex() != 0) { in.readNull(); @@ -491,15 +494,14 @@ public void customDecode(org.apache.avro.io.ResolvingDecoder in) throws java.io. this.favorite_color = null; } else { - this.favorite_color = in - .readString(this.favorite_color instanceof Utf8 ? (Utf8) this.favorite_color : null); + this.favorite_color = in.readString(this.favorite_color instanceof Utf8 utf8 ? utf8 : null); } } else { for (int i = 0; i < 3; i++) { switch (fieldOrder[i].pos()) { - case 0 -> this.name = in.readString(this.name instanceof Utf8 ? (Utf8) this.name : null); + case 0 -> this.name = in.readString(this.name instanceof Utf8 utf8 ? utf8 : null); case 1 -> { if (in.readIndex() != 0) { in.readNull(); @@ -515,8 +517,7 @@ public void customDecode(org.apache.avro.io.ResolvingDecoder in) throws java.io. this.favorite_color = null; } else { - this.favorite_color = in - .readString(this.favorite_color instanceof Utf8 ? (Utf8) this.favorite_color : null); + this.favorite_color = in.readString(this.favorite_color instanceof Utf8 utf8 ? utf8 : null); } } default -> throw new java.io.IOException("Corrupt ResolvingDecoder."); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/MongoCursorItemReaderTest.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/MongoCursorItemReaderTest.java index 8cb6bf84c7..f76f0fed13 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/MongoCursorItemReaderTest.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/MongoCursorItemReaderTest.java @@ -204,7 +204,7 @@ void testQueryWithLimit() throws Exception { @Test void testQueryWithMaxTime() throws Exception { - reader.setMaxTime(Duration.ofMillis(3000)); + reader.setMaxTime(Duration.ofSeconds(3)); ArgumentCaptor queryContainer = ArgumentCaptor.forClass(Query.class); when(template.stream(queryContainer.capture(), eq(String.class))).thenReturn(Stream.of()); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/MongoCursorItemReaderBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/MongoCursorItemReaderBuilderTests.java index f8dcfa6e32..94937673e4 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/MongoCursorItemReaderBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/data/builder/MongoCursorItemReaderBuilderTests.java @@ -45,7 +45,7 @@ void testBuild() { Map sorts = mock(); int batchSize = 100; int limit = 10000; - Duration maxTime = Duration.ofMillis(1000); + Duration maxTime = Duration.ofSeconds(1); // when MongoCursorItemReader reader = new MongoCursorItemReaderBuilder().name("reader") diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/ExtendedConnectionDataSourceProxyTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/ExtendedConnectionDataSourceProxyTests.java index 3b83e488ce..df04ab7aff 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/ExtendedConnectionDataSourceProxyTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/ExtendedConnectionDataSourceProxyTests.java @@ -278,38 +278,38 @@ private static class DataSourceStub implements DataSource, Supported { private static final String UNWRAP_ERROR_MESSAGE = "supplied type is not implemented by this class"; @Override - public Connection getConnection() throws SQLException { + public Connection getConnection() { throw new UnsupportedOperationException(); } @Override - public Connection getConnection(String username, String password) throws SQLException { + public Connection getConnection(String username, String password) { throw new UnsupportedOperationException(); } @Override - public PrintWriter getLogWriter() throws SQLException { + public PrintWriter getLogWriter() { throw new UnsupportedOperationException(); } @Override - public int getLoginTimeout() throws SQLException { + public int getLoginTimeout() { throw new UnsupportedOperationException(); } @Override - public void setLogWriter(PrintWriter out) throws SQLException { + public void setLogWriter(PrintWriter out) { throw new UnsupportedOperationException(); } @Override - public void setLoginTimeout(int seconds) throws SQLException { + public void setLoginTimeout(int seconds) { throw new UnsupportedOperationException(); } @Override - public boolean isWrapperFor(Class iface) throws SQLException { - if (iface.equals(Supported.class) || (iface.equals(DataSource.class))) { + public boolean isWrapperFor(Class iface) { + if (iface.equals(Supported.class) || iface.equals(DataSource.class)) { return true; } return false; diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaNativeQueryProviderIntegrationTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaNativeQueryProviderIntegrationTests.java index 959db5e22e..f8373e7de4 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaNativeQueryProviderIntegrationTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/database/JpaNativeQueryProviderIntegrationTests.java @@ -71,7 +71,7 @@ void shouldRetrieveAndMapAllFoos() throws Exception { @SuppressWarnings("unchecked") List actualFoos = query.getResultList(); - assertEquals(actualFoos, expectedFoos); + assertEquals(expectedFoos, actualFoos); } @Test @@ -96,7 +96,7 @@ void shouldExecuteParameterizedQuery() throws Exception { @SuppressWarnings("unchecked") List actualFoos = query.getResultList(); - assertEquals(actualFoos, expectedFoos); + assertEquals(expectedFoos, actualFoos); } } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/SimpleBinaryBufferedReaderFactoryTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/SimpleBinaryBufferedReaderFactoryTests.java index 202fcc6476..49700060bc 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/SimpleBinaryBufferedReaderFactoryTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/SimpleBinaryBufferedReaderFactoryTests.java @@ -93,7 +93,7 @@ void testCreateWithFalseMixedCharacterLineEnding() throws Exception { SimpleBinaryBufferedReaderFactory factory = new SimpleBinaryBufferedReaderFactory(); factory.setLineEnding("#@"); @SuppressWarnings("resource") - BufferedReader reader = factory.create(new ByteArrayResource(("a##@").getBytes()), "UTF-8"); + BufferedReader reader = factory.create(new ByteArrayResource("a##@".getBytes()), "UTF-8"); assertEquals("a#", reader.readLine()); assertNull(reader.readLine()); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/FlatFileItemReaderBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/FlatFileItemReaderBuilderTests.java index e6c6f6c2de..d1890ef383 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/FlatFileItemReaderBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/FlatFileItemReaderBuilderTests.java @@ -44,6 +44,7 @@ import org.springframework.test.util.ReflectionTestUtils; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -579,15 +580,16 @@ record Person(int id, String name) { // then Object lineMapper = ReflectionTestUtils.getField(reader, "lineMapper"); assertNotNull(lineMapper); - assertTrue(lineMapper instanceof DefaultLineMapper); + assertInstanceOf(DefaultLineMapper.class, lineMapper); Object fieldSetMapper = ReflectionTestUtils.getField(lineMapper, "fieldSetMapper"); assertNotNull(fieldSetMapper); - assertTrue(fieldSetMapper instanceof RecordFieldSetMapper); + assertInstanceOf(RecordFieldSetMapper.class, fieldSetMapper); } @Test void testSetupWithClassTargetType() { // given + @SuppressWarnings("unused") class Person { int id; @@ -607,10 +609,10 @@ class Person { // then Object lineMapper = ReflectionTestUtils.getField(reader, "lineMapper"); assertNotNull(lineMapper); - assertTrue(lineMapper instanceof DefaultLineMapper); + assertInstanceOf(DefaultLineMapper.class, lineMapper); Object fieldSetMapper = ReflectionTestUtils.getField(lineMapper, "fieldSetMapper"); assertNotNull(fieldSetMapper); - assertTrue(fieldSetMapper instanceof BeanWrapperFieldSetMapper); + assertInstanceOf(BeanWrapperFieldSetMapper.class, fieldSetMapper); } private Resource getResource(String contents) { diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/FlatFileItemWriterBuilderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/FlatFileItemWriterBuilderTests.java index 0b37305559..ad8083c4d2 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/FlatFileItemWriterBuilderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/file/builder/FlatFileItemWriterBuilderTests.java @@ -38,6 +38,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -347,16 +348,18 @@ record Person(int id, String name) { // then Object lineAggregator = ReflectionTestUtils.getField(writer, "lineAggregator"); assertNotNull(lineAggregator); - assertTrue(lineAggregator instanceof DelimitedLineAggregator); + assertInstanceOf(DelimitedLineAggregator.class, lineAggregator); Object fieldExtractor = ReflectionTestUtils.getField(lineAggregator, "fieldExtractor"); assertNotNull(fieldExtractor); - assertTrue(fieldExtractor instanceof RecordFieldExtractor); + assertInstanceOf(RecordFieldExtractor.class, fieldExtractor); } @Test void testSetupDelimitedLineAggregatorWithClassItemType() throws IOException { // given WritableResource output = new FileSystemResource(File.createTempFile("foo", "txt")); + + @SuppressWarnings("unused") class Person { int id; @@ -376,10 +379,10 @@ class Person { // then Object lineAggregator = ReflectionTestUtils.getField(writer, "lineAggregator"); assertNotNull(lineAggregator); - assertTrue(lineAggregator instanceof DelimitedLineAggregator); + assertInstanceOf(DelimitedLineAggregator.class, lineAggregator); Object fieldExtractor = ReflectionTestUtils.getField(lineAggregator, "fieldExtractor"); assertNotNull(fieldExtractor); - assertTrue(fieldExtractor instanceof BeanWrapperFieldExtractor); + assertInstanceOf(BeanWrapperFieldExtractor.class, fieldExtractor); } @Test @@ -388,7 +391,7 @@ void testSetupDelimitedLineAggregatorWithNoItemType() throws IOException { WritableResource output = new FileSystemResource(File.createTempFile("foo", "txt")); // when - FlatFileItemWriter writer = new FlatFileItemWriterBuilder<>().name("personWriter") + FlatFileItemWriter writer = new FlatFileItemWriterBuilder<>().name("personWriter") .resource(output) .delimited() .names("id", "name") @@ -397,10 +400,10 @@ void testSetupDelimitedLineAggregatorWithNoItemType() throws IOException { // then Object lineAggregator = ReflectionTestUtils.getField(writer, "lineAggregator"); assertNotNull(lineAggregator); - assertTrue(lineAggregator instanceof DelimitedLineAggregator); + assertInstanceOf(DelimitedLineAggregator.class, lineAggregator); Object fieldExtractor = ReflectionTestUtils.getField(lineAggregator, "fieldExtractor"); assertNotNull(fieldExtractor); - assertTrue(fieldExtractor instanceof BeanWrapperFieldExtractor); + assertInstanceOf(BeanWrapperFieldExtractor.class, fieldExtractor); } @Test @@ -422,16 +425,18 @@ record Person(int id, String name) { // then Object lineAggregator = ReflectionTestUtils.getField(writer, "lineAggregator"); assertNotNull(lineAggregator); - assertTrue(lineAggregator instanceof FormatterLineAggregator); + assertInstanceOf(FormatterLineAggregator.class, lineAggregator); Object fieldExtractor = ReflectionTestUtils.getField(lineAggregator, "fieldExtractor"); assertNotNull(fieldExtractor); - assertTrue(fieldExtractor instanceof RecordFieldExtractor); + assertInstanceOf(RecordFieldExtractor.class, fieldExtractor); } @Test void testSetupFormatterLineAggregatorWithClassItemType() throws IOException { // given WritableResource output = new FileSystemResource(File.createTempFile("foo", "txt")); + + @SuppressWarnings("unused") class Person { int id; @@ -452,10 +457,10 @@ class Person { // then Object lineAggregator = ReflectionTestUtils.getField(writer, "lineAggregator"); assertNotNull(lineAggregator); - assertTrue(lineAggregator instanceof FormatterLineAggregator); + assertInstanceOf(FormatterLineAggregator.class, lineAggregator); Object fieldExtractor = ReflectionTestUtils.getField(lineAggregator, "fieldExtractor"); assertNotNull(fieldExtractor); - assertTrue(fieldExtractor instanceof BeanWrapperFieldExtractor); + assertInstanceOf(BeanWrapperFieldExtractor.class, fieldExtractor); } @Test @@ -474,10 +479,10 @@ void testSetupFormatterLineAggregatorWithNoItemType() throws IOException { // then Object lineAggregator = ReflectionTestUtils.getField(writer, "lineAggregator"); assertNotNull(lineAggregator); - assertTrue(lineAggregator instanceof FormatterLineAggregator); + assertInstanceOf(FormatterLineAggregator.class, lineAggregator); Object fieldExtractor = ReflectionTestUtils.getField(lineAggregator, "fieldExtractor"); assertNotNull(fieldExtractor); - assertTrue(fieldExtractor instanceof BeanWrapperFieldExtractor); + assertInstanceOf(BeanWrapperFieldExtractor.class, fieldExtractor); } private void validateBuilderFlags(FlatFileItemWriter writer, String encoding) { diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/function/PredicateFilteringItemProcessorTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/function/PredicateFilteringItemProcessorTests.java index aa6b79d456..9b74b40f21 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/function/PredicateFilteringItemProcessorTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/function/PredicateFilteringItemProcessorTests.java @@ -15,8 +15,6 @@ */ package org.springframework.batch.item.function; -import java.util.function.Predicate; - import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -27,8 +25,6 @@ */ class PredicateFilteringItemProcessorTests { - private final Predicate foos = item -> item.startsWith("foo"); - @Test void testMandatoryPredicate() { Assertions.assertThrows(IllegalArgumentException.class, () -> new PredicateFilteringItemProcessor(null), @@ -38,7 +34,8 @@ void testMandatoryPredicate() { @Test void testProcess() throws Exception { // given - PredicateFilteringItemProcessor processor = new PredicateFilteringItemProcessor<>(this.foos); + PredicateFilteringItemProcessor processor = new PredicateFilteringItemProcessor<>( + item -> item.startsWith("foo")); // when & then Assertions.assertNull(processor.process("foo1")); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemReaderTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemReaderTests.java index 19bfb27626..c1a5ecad43 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemReaderTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemReaderTests.java @@ -700,8 +700,7 @@ private List readRecordsInsideFragment(XMLEventReader eventReader, QNa List events = new ArrayList<>(); do { eventInsideFragment = eventReader.peek(); - if (eventInsideFragment instanceof EndElement - && fragmentName.equals(((EndElement) eventInsideFragment).getName())) { + if (eventInsideFragment instanceof EndElement endElement && fragmentName.equals(endElement.getName())) { break; } events.add(eventReader.nextEvent()); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemWriterTests.java index 08fada774e..9f2085f7f4 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/xml/StaxEventItemWriterTests.java @@ -387,7 +387,7 @@ void testWriteWithHeader() throws Exception { writer.open(executionContext); writer.write(items); String content = getOutputFileContent(); - assertTrue(content.contains(("
")), "Wrong content: " + content); + assertTrue(content.contains("
"), "Wrong content: " + content); assertTrue(content.contains(TEST_STRING), "Wrong content: " + content); } @@ -612,10 +612,10 @@ void testWriteRootTagWithNamespace() throws Exception { writer.write(items); writer.close(); String content = getOutputFileContent(); - assertTrue(content.contains(("")), + assertTrue(content.contains(""), "Wrong content: " + content); assertTrue(content.contains(TEST_STRING), "Wrong content: " + content); - assertTrue(content.contains(("")), "Wrong content: " + content); + assertTrue(content.contains(""), "Wrong content: " + content); } /** @@ -631,11 +631,11 @@ void testWriteRootTagWithNamespaceAndPrefix() throws Exception { writer.write(items); writer.close(); String content = getOutputFileContent(); - assertTrue(content.contains(("")), + assertTrue(content.contains(""), "Wrong content: " + content); assertTrue(content.contains(NS_TEST_STRING), "Wrong content: " + content); - assertTrue(content.contains(("")), "Wrong content: " + content); - assertTrue(content.contains((""), "Wrong content: " + content); + assertTrue(content.contains("")), + ""), "Wrong content: " + content); assertTrue(content.contains(FOO_TEST_STRING), "Wrong content: " + content); - assertTrue(content.contains(("")), "Wrong content: " + content); - assertTrue(content.contains((""), "Wrong content: " + content); + assertTrue(content.contains("")), "Wrong content: " + content); + assertEquals(1, StringUtils.countOccurrencesOf(content, "
"), "Wrong content: " + content); assertEquals(1, StringUtils.countOccurrencesOf(content, TEST_STRING), "Wrong content: " + content); } @@ -183,7 +183,7 @@ void testWriteWithHeaderAfterFlushAndRollback() throws Exception { })); writer.close(); String content = outputFileContent(); - assertEquals(1, StringUtils.countOccurrencesOf(content, ("
")), "Wrong content: " + content); + assertEquals(1, StringUtils.countOccurrencesOf(content, "
"), "Wrong content: " + content); assertEquals(1, StringUtils.countOccurrencesOf(content, TEST_STRING), "Wrong content: " + content); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/jms/ExternalRetryInBatchTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/jms/ExternalRetryInBatchTests.java index 2bad8747d6..01718ce33a 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/jms/ExternalRetryInBatchTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/jms/ExternalRetryInBatchTests.java @@ -70,14 +70,10 @@ void onSetUp() { JdbcTestUtils.deleteFromTables(jdbcTemplate, "T_BARS"); jmsTemplate.convertAndSend("queue", "foo"); jmsTemplate.convertAndSend("queue", "bar"); - provider = new ItemReader<>() { - @Nullable - @Override - public String read() { - String text = (String) jmsTemplate.receiveAndConvert("queue"); - list.add(text); - return text; - } + provider = () -> { + String text = (String) jmsTemplate.receiveAndConvert("queue"); + list.add(text); + return text; }; retryTemplate = new RetryTemplate(); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/exception/SimpleLimitExceptionHandlerTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/exception/SimpleLimitExceptionHandlerTests.java index e064c604c5..d5cd02e00c 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/exception/SimpleLimitExceptionHandlerTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/exception/SimpleLimitExceptionHandlerTests.java @@ -24,6 +24,8 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -152,19 +154,14 @@ void testExceptionNotThrownBelowLimit() throws Throwable { handler.setLimit(EXCEPTION_LIMIT); handler.afterPropertiesSet(); - @SuppressWarnings("serial") - List throwables = new ArrayList<>() { - { - for (int i = 0; i < (EXCEPTION_LIMIT); i++) { - add(new RuntimeException("below exception limit")); - } - } - }; + List exceptions = IntStream.range(0, EXCEPTION_LIMIT) + .mapToObj(__ -> new RuntimeException("below exception limit")) + .toList(); RepeatContextSupport context = new RepeatContextSupport(null); - for (Throwable throwable : throwables) { - assertDoesNotThrow(() -> handler.handleException(context, throwable)); + for (RuntimeException exception : exceptions) { + assertDoesNotThrow(() -> handler.handleException(context, exception)); } } @@ -180,22 +177,17 @@ void testExceptionThrownAboveLimit() throws Throwable { handler.setLimit(EXCEPTION_LIMIT); handler.afterPropertiesSet(); - @SuppressWarnings("serial") - List throwables = new ArrayList<>() { - { - for (int i = 0; i < (EXCEPTION_LIMIT); i++) { - add(new RuntimeException("below exception limit")); - } - } - }; + List exceptions = IntStream.range(0, EXCEPTION_LIMIT) + .mapToObj(__ -> new RuntimeException("below exception limit")) + .collect(Collectors.toCollection(ArrayList::new)); - throwables.add(new RuntimeException("above exception limit")); + exceptions.add(new RuntimeException("above exception limit")); RepeatContextSupport context = new RepeatContextSupport(null); Exception expected = assertThrows(RuntimeException.class, () -> { - for (Throwable throwable : throwables) { - handler.handleException(context, throwable); + for (Throwable exception : exceptions) { + handler.handleException(context, exception); } }); assertEquals("above exception limit", expected.getMessage()); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/ResultHolderResultQueueTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/ResultHolderResultQueueTests.java index 0f793a3b23..9d516b3e8f 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/ResultHolderResultQueueTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/ResultHolderResultQueueTests.java @@ -22,6 +22,7 @@ import org.springframework.batch.repeat.RepeatContext; import org.springframework.batch.repeat.RepeatStatus; +@SuppressWarnings("removal") class ResultHolderResultQueueTests { private final ResultHolderResultQueue queue = new ResultHolderResultQueue(10); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/ThrottleLimitResultQueueTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/ThrottleLimitResultQueueTests.java index a93896492e..68fe02f30e 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/ThrottleLimitResultQueueTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/repeat/support/ThrottleLimitResultQueueTests.java @@ -29,6 +29,7 @@ * @author Mahmoud Ben Hassine * */ +@SuppressWarnings("removal") class ThrottleLimitResultQueueTests { private final ThrottleLimitResultQueue queue = new ThrottleLimitResultQueue<>(1); diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/retry/jms/ExternalRetryTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/retry/jms/ExternalRetryTests.java index 4ec1aeb488..115e765f3b 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/retry/jms/ExternalRetryTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/retry/jms/ExternalRetryTests.java @@ -62,14 +62,10 @@ void onSetUp() { getMessages(); // drain queue JdbcTestUtils.deleteFromTables(jdbcTemplate, "T_BARS"); jmsTemplate.convertAndSend("queue", "foo"); - provider = new ItemReader<>() { - @Nullable - @Override - public String read() { - String text = (String) jmsTemplate.receiveAndConvert("queue"); - list.add(text); - return text; - } + provider = () -> { + String text = (String) jmsTemplate.receiveAndConvert("queue"); + list.add(text); + return text; }; retryTemplate = new RetryTemplate(); } diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/ConcurrentTransactionAwareProxyTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/ConcurrentTransactionAwareProxyTests.java index baef448a31..7cd708dd10 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/ConcurrentTransactionAwareProxyTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/transaction/ConcurrentTransactionAwareProxyTests.java @@ -108,7 +108,7 @@ void testConcurrentTransactionalMap() { @Test void testTransactionalContains() { final Map> map = TransactionAwareProxyFactory.createAppendOnlyTransactionalMap(); - boolean result = new TransactionTemplate(transactionManager).execute(status -> map.containsKey("foo")); + boolean result = new TransactionTemplate(transactionManager).execute(status -> map.containsKey(0L)); assertFalse(result); } @@ -177,7 +177,7 @@ private void testMap(final Map> map) throws Exception for (int i = 0; i < outerMax; i++) { for (int j = 0; j < numberOfKeys; j++) { - final long id = j * 1000 + 123L + i; + final long id = j * 1000L + 123L + i; completionService.submit(() -> { List list = new ArrayList<>(); diff --git a/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemWriter.java b/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemWriter.java index 58e9e9086a..b300409561 100644 --- a/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemWriter.java +++ b/spring-batch-integration/src/main/java/org/springframework/batch/integration/async/AsyncItemWriter.java @@ -75,10 +75,10 @@ public void write(Chunk> items) throws Exception { catch (ExecutionException e) { Throwable cause = e.getCause(); - if (cause instanceof Exception) { + if (cause instanceof Exception exception) { logger.debug("An exception was thrown while processing an item", e); - throw (Exception) cause; + throw exception; } else { throw e; diff --git a/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkMessageChannelItemWriter.java b/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkMessageChannelItemWriter.java index 4475e2d1a6..6d672b8978 100644 --- a/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkMessageChannelItemWriter.java +++ b/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/ChunkMessageChannelItemWriter.java @@ -260,11 +260,11 @@ protected void getNextResult() throws AsynchronousFailureException { * {@link AsynchronousFailureException}. */ protected static AsynchronousFailureException wrapIfNecessary(Throwable throwable) { - if (throwable instanceof Error) { - throw (Error) throwable; + if (throwable instanceof Error error) { + throw error; } - else if (throwable instanceof AsynchronousFailureException) { - return (AsynchronousFailureException) throwable; + else if (throwable instanceof AsynchronousFailureException exception) { + return exception; } else { return new AsynchronousFailureException("Exception in remote process", throwable); diff --git a/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/RemoteChunkHandlerFactoryBean.java b/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/RemoteChunkHandlerFactoryBean.java index 9def1ae7c3..882607fce5 100644 --- a/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/RemoteChunkHandlerFactoryBean.java +++ b/spring-batch-integration/src/main/java/org/springframework/batch/integration/chunk/RemoteChunkHandlerFactoryBean.java @@ -139,8 +139,8 @@ public ChunkHandler getObject() throws Exception { + "] because it already has a remote chunk writer. Use a local writer in the step."); replaceChunkProcessor((ChunkOrientedTasklet) tasklet, chunkWriter, stepContributionSource); - if (chunkWriter instanceof StepExecutionListener) { - step.registerStepExecutionListener((StepExecutionListener) chunkWriter); + if (chunkWriter instanceof StepExecutionListener stepExecutionListener) { + step.registerStepExecutionListener(stepExecutionListener); } ChunkProcessorChunkHandler handler = new ChunkProcessorChunkHandler<>(); diff --git a/spring-batch-integration/src/test/java/org/springframework/batch/integration/item/MessagingGatewayIntegrationTests.java b/spring-batch-integration/src/test/java/org/springframework/batch/integration/item/MessagingGatewayIntegrationTests.java index e3bbd18ced..49a044523f 100644 --- a/spring-batch-integration/src/test/java/org/springframework/batch/integration/item/MessagingGatewayIntegrationTests.java +++ b/spring-batch-integration/src/test/java/org/springframework/batch/integration/item/MessagingGatewayIntegrationTests.java @@ -92,7 +92,7 @@ public String transform(String input) { if (input.equals("filter")) { return null; } - return input + ": " + (count++); + return input + ": " + count++; } } diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/samples/chunking/ManagerConfiguration.java b/spring-batch-samples/src/main/java/org/springframework/batch/samples/chunking/ManagerConfiguration.java index d4e53aa5df..61e54f8ed6 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/samples/chunking/ManagerConfiguration.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/samples/chunking/ManagerConfiguration.java @@ -110,7 +110,7 @@ public ListItemReader itemReader() { @Bean public TaskletStep managerStep() { return this.managerStepBuilderFactory.get("managerStep") - .chunk(3) + .chunk(3) .reader(itemReader()) .outputChannel(requests()) .inputChannel(replies()) diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/CustomerCredit.java b/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/CustomerCredit.java index 2812aced71..55a22d5785 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/CustomerCredit.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/samples/domain/trade/CustomerCredit.java @@ -81,7 +81,7 @@ public CustomerCredit increaseCreditBy(BigDecimal sum) { @Override public boolean equals(Object o) { - return (o instanceof CustomerCredit) && ((CustomerCredit) o).id == id; + return (o instanceof CustomerCredit customerCredit) && customerCredit.id == id; } @Override diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multirecordtype/DelegatingTradeLineAggregator.java b/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multirecordtype/DelegatingTradeLineAggregator.java index 7aaa8b68af..53aa2418e0 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multirecordtype/DelegatingTradeLineAggregator.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/multirecordtype/DelegatingTradeLineAggregator.java @@ -32,11 +32,11 @@ public class DelegatingTradeLineAggregator implements LineAggregator { @Override public String aggregate(Object item) { - if (item instanceof Trade) { - return this.tradeLineAggregator.aggregate((Trade) item); + if (item instanceof Trade trade) { + return this.tradeLineAggregator.aggregate(trade); } - else if (item instanceof CustomerCredit) { - return this.customerLineAggregator.aggregate((CustomerCredit) item); + else if (item instanceof CustomerCredit customerCredit) { + return this.customerLineAggregator.aggregate(customerCredit); } else { throw new RuntimeException(); diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/validator/OrderValidator.java b/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/validator/OrderValidator.java index d3a2841896..c25cfee129 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/validator/OrderValidator.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/samples/file/patternmatching/internal/validator/OrderValidator.java @@ -256,8 +256,8 @@ protected void validateAddress(Address address, Errors errors, String prefix) { errors.rejectValue(prefix + ".zipCode", "error.baddress.zipcode.format"); } - if ((!StringUtils.hasText(address.getState()) && ("United States".equals(address.getCountry())) - || StringUtils.hasText(address.getState()) && address.getState().length() != 2)) { + if ((!StringUtils.hasText(address.getState()) && "United States".equals(address.getCountry())) + || (StringUtils.hasText(address.getState()) && (address.getState().length() != 2))) { errors.rejectValue(prefix + ".state", "error.baddress.state.length"); } diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/samples/misc/quartz/JobLauncherDetails.java b/spring-batch-samples/src/main/java/org/springframework/batch/samples/misc/quartz/JobLauncherDetails.java index 97a2f0ae01..117aa69f82 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/samples/misc/quartz/JobLauncherDetails.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/samples/misc/quartz/JobLauncherDetails.java @@ -92,8 +92,8 @@ private JobParameters getJobParametersFromJobMap(Map jobDataMap) for (Entry entry : jobDataMap.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); - if (value instanceof String && !key.equals(JOB_NAME)) { - builder.addString(key, (String) value); + if (value instanceof String s && !key.equals(JOB_NAME)) { + builder.addString(key, s); } else if (value instanceof Float || value instanceof Double) { builder.addDouble(key, ((Number) value).doubleValue()); @@ -101,8 +101,8 @@ else if (value instanceof Float || value instanceof Double) { else if (value instanceof Integer || value instanceof Long) { builder.addLong(key, ((Number) value).longValue()); } - else if (value instanceof Date) { - builder.addDate(key, (Date) value); + else if (value instanceof Date date) { + builder.addDate(key, date); } else { log.debug("JobDataMap contains values which are not job parameters (ignoring)."); diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/samples/partitioning/remote/BasicPartitioner.java b/spring-batch-samples/src/main/java/org/springframework/batch/samples/partitioning/remote/BasicPartitioner.java index 99a5b50b60..b0e6dd86ce 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/samples/partitioning/remote/BasicPartitioner.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/samples/partitioning/remote/BasicPartitioner.java @@ -35,7 +35,7 @@ public Map partition(int gridSize) { Map partitions = super.partition(gridSize); int i = 0; for (ExecutionContext context : partitions.values()) { - context.put(PARTITION_KEY, PARTITION_KEY + (i++)); + context.put(PARTITION_KEY, PARTITION_KEY + i++); } return partitions; } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/samples/compositewriter/CompositeItemWriterSampleFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/samples/compositewriter/CompositeItemWriterSampleFunctionalTests.java index 5b909167da..1f49b10b23 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/samples/compositewriter/CompositeItemWriterSampleFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/samples/compositewriter/CompositeItemWriterSampleFunctionalTests.java @@ -74,15 +74,12 @@ void testJobLaunch() throws Exception { } private void checkOutputTable(int before) { - final List trades = new ArrayList<>() { - { - add(new Trade("UK21341EAH41", 211, new BigDecimal("31.11"), "customer1")); - add(new Trade("UK21341EAH42", 212, new BigDecimal("32.11"), "customer2")); - add(new Trade("UK21341EAH43", 213, new BigDecimal("33.11"), "customer3")); - add(new Trade("UK21341EAH44", 214, new BigDecimal("34.11"), "customer4")); - add(new Trade("UK21341EAH45", 215, new BigDecimal("35.11"), "customer5")); - } - }; + final List trades = List.of( // + new Trade("UK21341EAH41", 211, new BigDecimal("31.11"), "customer1"), + new Trade("UK21341EAH42", 212, new BigDecimal("32.11"), "customer2"), + new Trade("UK21341EAH43", 213, new BigDecimal("33.11"), "customer3"), + new Trade("UK21341EAH44", 214, new BigDecimal("34.11"), "customer4"), + new Trade("UK21341EAH45", 215, new BigDecimal("35.11"), "customer5")); int after = JdbcTestUtils.countRowsInTable(jdbcTemplate, "TRADE"); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/samples/file/patternmatching/PatternMatchingJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/samples/file/patternmatching/PatternMatchingJobFunctionalTests.java index 6d6df834e4..cb7250feeb 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/samples/file/patternmatching/PatternMatchingJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/samples/file/patternmatching/PatternMatchingJobFunctionalTests.java @@ -28,6 +28,8 @@ import org.springframework.core.io.FileSystemResource; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; +import static org.junit.jupiter.api.Assertions.assertLinesMatch; + @SpringJUnitConfig(locations = { "/org/springframework/batch/samples/file/patternmatching/job/multilineOrderJob.xml", "/simple-job-launcher-context.xml" }) class PatternMatchingJobFunctionalTests { @@ -44,7 +46,7 @@ void testJobLaunch() throws Exception { this.jobLauncherTestUtils.launchJob(); Path expectedFile = new ClassPathResource(EXPECTED).getFile().toPath(); Path actualFile = new FileSystemResource(ACTUAL).getFile().toPath(); - Assertions.assertLinesMatch(Files.lines(expectedFile), Files.lines(actualFile)); + assertLinesMatch(Files.lines(expectedFile), Files.lines(actualFile)); } } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/samples/filter/CustomerFilterJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/samples/filter/CustomerFilterJobFunctionalTests.java index 26aa4c3acf..4b3fdb5256 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/samples/filter/CustomerFilterJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/samples/filter/CustomerFilterJobFunctionalTests.java @@ -81,8 +81,8 @@ void tearDown() { void testFilterJob() throws Exception { JobExecution jobExecution = jobLauncherTestUtils.launchJob(); - customers = Arrays.asList(new Customer("customer1", (credits.get("customer1"))), - new Customer("customer2", (credits.get("customer2"))), new Customer("customer3", 100500), + customers = Arrays.asList(new Customer("customer1", credits.get("customer1")), + new Customer("customer2", credits.get("customer2")), new Customer("customer3", 100500), new Customer("customer4", credits.get("customer4")), new Customer("customer5", 32345), new Customer("customer6", 123456)); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/samples/partition/file/PartitionFileJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/samples/partition/file/PartitionFileJobFunctionalTests.java index 7b02c19379..7030bb80df 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/samples/partition/file/PartitionFileJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/samples/partition/file/PartitionFileJobFunctionalTests.java @@ -85,7 +85,6 @@ void testUpdateCredit() throws Exception { int itemCount = inputs.size(); assertTrue(itemCount > 0, "No entries were available in the input"); - inputs.iterator(); for (int i = 0; i < itemCount; i++) { assertEquals(inputs.get(i).getCredit().add(CustomerCreditIncreaseProcessor.FIXED_AMOUNT).intValue(), outputs.get(i).getCredit().intValue()); @@ -110,8 +109,8 @@ private Set getCredits(ItemReader reader) throws * Open the reader if applicable. */ private void open(ItemReader reader) { - if (reader instanceof ItemStream) { - ((ItemStream) reader).open(new ExecutionContext()); + if (reader instanceof ItemStream itemStream) { + itemStream.open(new ExecutionContext()); } } @@ -119,8 +118,8 @@ private void open(ItemReader reader) { * Close the reader if applicable. */ private void close(ItemReader reader) { - if (reader instanceof ItemStream) { - ((ItemStream) reader).close(); + if (reader instanceof ItemStream itemStream) { + itemStream.close(); } } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/samples/partition/jdbc/PartitionJdbcJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/samples/partition/jdbc/PartitionJdbcJobFunctionalTests.java index 97719a96d7..ec380e81a7 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/samples/partition/jdbc/PartitionJdbcJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/samples/partition/jdbc/PartitionJdbcJobFunctionalTests.java @@ -85,7 +85,6 @@ void testUpdateCredit() throws Exception { int itemCount = inputs.size(); assertTrue(itemCount > 0, "Input from reader has no entries."); - inputs.iterator(); for (int i = 0; i < itemCount; i++) { assertEquals(inputs.get(i).getCredit().add(CustomerCreditIncreaseProcessor.FIXED_AMOUNT).intValue(), outputs.get(i).getCredit().intValue()); @@ -109,8 +108,8 @@ private Set getCredits(ItemReader reader) throws * Open the reader if applicable. */ private void open(ItemReader reader) { - if (reader instanceof ItemStream) { - ((ItemStream) reader).open(new ExecutionContext()); + if (reader instanceof ItemStream itemStream) { + itemStream.open(new ExecutionContext()); } } @@ -118,8 +117,8 @@ private void open(ItemReader reader) { * Close the reader if applicable. */ private void close(ItemReader reader) { - if (reader instanceof ItemStream) { - ((ItemStream) reader).close(); + if (reader instanceof ItemStream itemStream) { + itemStream.close(); } } diff --git a/spring-batch-test/src/main/java/org/springframework/batch/test/JobRepositoryTestUtils.java b/spring-batch-test/src/main/java/org/springframework/batch/test/JobRepositoryTestUtils.java index d6a7b07327..8a50ccf40b 100644 --- a/spring-batch-test/src/main/java/org/springframework/batch/test/JobRepositoryTestUtils.java +++ b/spring-batch-test/src/main/java/org/springframework/batch/test/JobRepositoryTestUtils.java @@ -159,16 +159,16 @@ public void removeJobExecutions() { for (String jobName : jobNames) { int start = 0; int count = 100; - List jobInstances = this.jobRepository.findJobInstancesByName(jobName, start, count); + List jobInstances = this.jobRepository.getJobInstances(jobName, start, count); while (!jobInstances.isEmpty()) { for (JobInstance jobInstance : jobInstances) { - List jobExecutions = this.jobRepository.findJobExecutions(jobInstance); + List jobExecutions = this.jobRepository.getJobExecutions(jobInstance); if (jobExecutions != null && !jobExecutions.isEmpty()) { removeJobExecutions(jobExecutions); } } start += count; - jobInstances = this.jobRepository.findJobInstancesByName(jobName, start, count); + jobInstances = this.jobRepository.getJobInstances(jobName, start, count); } } }