Merge pull request #31916 from quaff

* pr/31916:
  Upgrade copyright year of changed files
  Polish "Replace if with switch where feasible"
  Replace if with switch where feasible
  Use Map.computeIfAbsent() where feasible
  Polish "Use Object.equals() where feasible"
  Use Object.equals() where feasible
  Polish "Use diamond operator where feasible"
  Use diamond operator where feasible
  Use auto boxing and unboxing where feasible
  Use enhanced for loop where feasible
  Polish "Use text block where feasible"
  Use text block where feasible
  Polish "Use String.repeat() where feasible"
  Use String.repeat() where feasible
  Polish "Remove unnecessary final modifier"
  Remove unnecessary final modifier

Closes gh-31916
This commit is contained in:
Stéphane Nicoll 2023-12-28 13:47:08 +01:00
commit c7d2d6716d
64 changed files with 283 additions and 315 deletions

View File

@ -201,9 +201,8 @@ class ConfigBeanDefinitionParser implements BeanDefinitionParser {
List<BeanReference> beanReferences = new ArrayList<>();
List<Element> declareParents = DomUtils.getChildElementsByTagName(aspectElement, DECLARE_PARENTS);
for (int i = METHOD_INDEX; i < declareParents.size(); i++) {
Element declareParentsElement = declareParents.get(i);
beanDefinitions.add(parseDeclareParents(declareParentsElement, parserContext));
for (Element declareParent : declareParents) {
beanDefinitions.add(parseDeclareParents(declareParent, parserContext));
}
// We have to parse "advice" and all the advice kinds in one loop, to get the
@ -405,24 +404,14 @@ class ConfigBeanDefinitionParser implements BeanDefinitionParser {
*/
private Class<?> getAdviceClass(Element adviceElement, ParserContext parserContext) {
String elementName = parserContext.getDelegate().getLocalName(adviceElement);
if (BEFORE.equals(elementName)) {
return AspectJMethodBeforeAdvice.class;
}
else if (AFTER.equals(elementName)) {
return AspectJAfterAdvice.class;
}
else if (AFTER_RETURNING_ELEMENT.equals(elementName)) {
return AspectJAfterReturningAdvice.class;
}
else if (AFTER_THROWING_ELEMENT.equals(elementName)) {
return AspectJAfterThrowingAdvice.class;
}
else if (AROUND.equals(elementName)) {
return AspectJAroundAdvice.class;
}
else {
throw new IllegalArgumentException("Unknown advice kind [" + elementName + "].");
}
return switch (elementName) {
case BEFORE -> AspectJMethodBeforeAdvice.class;
case AFTER -> AspectJAfterAdvice.class;
case AFTER_RETURNING_ELEMENT -> AspectJAfterReturningAdvice.class;
case AFTER_THROWING_ELEMENT -> AspectJAfterThrowingAdvice.class;
case AROUND -> AspectJAroundAdvice.class;
default -> throw new IllegalArgumentException("Unknown advice kind [" + elementName + "].");
};
}
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -221,7 +221,7 @@ public class AnnotationAsyncExecutionAspectTests {
@Async public Future<Integer> incrementReturningAFuture() {
counter++;
return new AsyncResult<Integer>(5);
return new AsyncResult<>(5);
}
/**
@ -256,7 +256,7 @@ public class AnnotationAsyncExecutionAspectTests {
public Future<Integer> incrementReturningAFuture() {
counter++;
return new AsyncResult<Integer>(5);
return new AsyncResult<>(5);
}
}
@ -265,12 +265,12 @@ public class AnnotationAsyncExecutionAspectTests {
@Async
public Future<Thread> defaultWork() {
return new AsyncResult<Thread>(Thread.currentThread());
return new AsyncResult<>(Thread.currentThread());
}
@Async("e1")
public ListenableFuture<Thread> e1Work() {
return new AsyncResult<Thread>(Thread.currentThread());
return new AsyncResult<>(Thread.currentThread());
}
@Async("e1")

View File

@ -581,7 +581,7 @@ public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccess
*/
@Override
public boolean isLazyInit() {
return (this.lazyInit != null && this.lazyInit.booleanValue());
return (this.lazyInit != null && this.lazyInit);
}
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -59,7 +59,7 @@ public class BeanDefinitionDefaults {
* @return whether to apply lazy-init semantics ({@code false} by default)
*/
public boolean isLazyInit() {
return (this.lazyInit != null && this.lazyInit.booleanValue());
return (this.lazyInit != null && this.lazyInit);
}
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -284,11 +284,7 @@ public class FactoryBeanTests {
if (bean instanceof FactoryBean) {
return bean;
}
AtomicInteger c = count.get(beanName);
if (c == null) {
c = new AtomicInteger();
count.put(beanName, c);
}
AtomicInteger c = count.computeIfAbsent(beanName, k -> new AtomicInteger());
c.incrementAndGet();
return bean;
}

View File

@ -58,9 +58,10 @@ public class PropertiesEditorTests {
@Test
public void handlesEqualsInValue() {
String s = "foo=bar\n" +
"me=mi\n" +
"x=y=z";
String s = """
foo=bar
me=mi
x=y=z""";
PropertiesEditor pe= new PropertiesEditor();
pe.setAsText(s);
Properties p = (Properties) pe.getValue();
@ -98,12 +99,14 @@ public class PropertiesEditorTests {
*/
@Test
public void ignoresCommentLinesAndEmptyLines() {
String s = "#Ignore this comment\n" +
"foo=bar\n" +
"#Another=comment more junk /\n" +
"me=mi\n" +
"x=x\n" +
"\n";
String s = """
#Ignore this comment
foo=bar
#Another=comment more junk /
me=mi
x=x
""";
PropertiesEditor pe= new PropertiesEditor();
pe.setAsText(s);
Properties p = (Properties) pe.getValue();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -23,7 +23,6 @@ import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ -268,8 +267,8 @@ public class GenericBean<T> {
public void setCustomEnumSetMismatch(Set<String> customEnumSet) {
this.customEnumSet = new HashSet<>(customEnumSet.size());
for (Iterator<String> iterator = customEnumSet.iterator(); iterator.hasNext(); ) {
this.customEnumSet.add(CustomEnum.valueOf(iterator.next()));
for (String customEnumName : customEnumSet) {
this.customEnumSet.add(CustomEnum.valueOf(customEnumName));
}
}

View File

@ -16,6 +16,8 @@
package org.springframework.beans.testfixture.beans;
import java.util.Objects;
import org.springframework.lang.Nullable;
/**
@ -47,14 +49,8 @@ public class Pet {
if (o == null || getClass() != o.getClass()) {
return false;
}
final Pet pet = (Pet) o;
if (name != null ? !name.equals(pet.name) : pet.name != null) {
return false;
}
return true;
Pet pet = (Pet) o;
return Objects.equals(this.name, pet.name);
}
@Override

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -182,17 +182,11 @@ public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser {
if (element.hasAttribute(SCOPED_PROXY_ATTRIBUTE)) {
String mode = element.getAttribute(SCOPED_PROXY_ATTRIBUTE);
if ("targetClass".equals(mode)) {
scanner.setScopedProxyMode(ScopedProxyMode.TARGET_CLASS);
}
else if ("interfaces".equals(mode)) {
scanner.setScopedProxyMode(ScopedProxyMode.INTERFACES);
}
else if ("no".equals(mode)) {
scanner.setScopedProxyMode(ScopedProxyMode.NO);
}
else {
throw new IllegalArgumentException("scoped-proxy only supports 'no', 'interfaces' and 'targetClass'");
switch (mode) {
case "targetClass" -> scanner.setScopedProxyMode(ScopedProxyMode.TARGET_CLASS);
case "interfaces" -> scanner.setScopedProxyMode(ScopedProxyMode.INTERFACES);
case "no" -> scanner.setScopedProxyMode(ScopedProxyMode.NO);
default -> throw new IllegalArgumentException("scoped-proxy only supports 'no', 'interfaces' and 'targetClass'");
}
}
}
@ -234,28 +228,28 @@ public class ComponentScanBeanDefinitionParser implements BeanDefinitionParser {
String filterType = element.getAttribute(FILTER_TYPE_ATTRIBUTE);
String expression = element.getAttribute(FILTER_EXPRESSION_ATTRIBUTE);
expression = parserContext.getReaderContext().getEnvironment().resolvePlaceholders(expression);
if ("annotation".equals(filterType)) {
return new AnnotationTypeFilter((Class<Annotation>) ClassUtils.forName(expression, classLoader));
}
else if ("assignable".equals(filterType)) {
return new AssignableTypeFilter(ClassUtils.forName(expression, classLoader));
}
else if ("aspectj".equals(filterType)) {
return new AspectJTypeFilter(expression, classLoader);
}
else if ("regex".equals(filterType)) {
return new RegexPatternTypeFilter(Pattern.compile(expression));
}
else if ("custom".equals(filterType)) {
Class<?> filterClass = ClassUtils.forName(expression, classLoader);
if (!TypeFilter.class.isAssignableFrom(filterClass)) {
throw new IllegalArgumentException(
"Class is not assignable to [" + TypeFilter.class.getName() + "]: " + expression);
switch (filterType) {
case "annotation" -> {
return new AnnotationTypeFilter((Class<Annotation>) ClassUtils.forName(expression, classLoader));
}
return (TypeFilter) BeanUtils.instantiateClass(filterClass);
}
else {
throw new IllegalArgumentException("Unsupported filter type: " + filterType);
case "assignable" -> {
return new AssignableTypeFilter(ClassUtils.forName(expression, classLoader));
}
case "aspectj" -> {
return new AspectJTypeFilter(expression, classLoader);
}
case "regex" -> {
return new RegexPatternTypeFilter(Pattern.compile(expression));
}
case "custom" -> {
Class<?> filterClass = ClassUtils.forName(expression, classLoader);
if (!TypeFilter.class.isAssignableFrom(filterClass)) {
throw new IllegalArgumentException(
"Class is not assignable to [" + TypeFilter.class.getName() + "]: " + expression);
}
return (TypeFilter) BeanUtils.instantiateClass(filterClass);
}
default -> throw new IllegalArgumentException("Unsupported filter type: " + filterType);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -61,22 +61,13 @@ public class ExecutorBeanDefinitionParser extends AbstractSingleBeanDefinitionPa
return;
}
String prefix = "java.util.concurrent.ThreadPoolExecutor.";
String policyClassName;
if (rejectionPolicy.equals("ABORT")) {
policyClassName = prefix + "AbortPolicy";
}
else if (rejectionPolicy.equals("CALLER_RUNS")) {
policyClassName = prefix + "CallerRunsPolicy";
}
else if (rejectionPolicy.equals("DISCARD")) {
policyClassName = prefix + "DiscardPolicy";
}
else if (rejectionPolicy.equals("DISCARD_OLDEST")) {
policyClassName = prefix + "DiscardOldestPolicy";
}
else {
policyClassName = rejectionPolicy;
}
String policyClassName = switch (rejectionPolicy) {
case "ABORT" -> prefix + "AbortPolicy";
case "CALLER_RUNS" -> prefix + "CallerRunsPolicy";
case "DISCARD" -> prefix + "DiscardPolicy";
case "DISCARD_OLDEST" -> prefix + "DiscardOldestPolicy";
default -> rejectionPolicy;
};
builder.addPropertyValue("rejectedExecutionHandler", new RootBeanDefinition(policyClassName));
}

View File

@ -24,7 +24,6 @@ import java.rmi.MarshalException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@ -1224,8 +1223,7 @@ public abstract class AbstractAopProxyTests {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
ReflectiveMethodInvocation rmi = (ReflectiveMethodInvocation) invocation;
for (Iterator<String> it = rmi.getUserAttributes().keySet().iterator(); it.hasNext(); ){
Object key = it.next();
for (Object key : rmi.getUserAttributes().keySet()) {
assertThat(rmi.getUserAttributes().get(key)).isEqualTo(expectedValues.get(key));
}
rmi.getUserAttributes().putAll(valuesToAdd);
@ -1233,7 +1231,7 @@ public abstract class AbstractAopProxyTests {
}
}
AdvisedSupport pc = new AdvisedSupport(ITestBean.class);
MapAwareMethodInterceptor mami1 = new MapAwareMethodInterceptor(new HashMap<>(), new HashMap<String, String>());
MapAwareMethodInterceptor mami1 = new MapAwareMethodInterceptor(new HashMap<>(), new HashMap<>());
Map<String, String> firstValuesToAdd = new HashMap<>();
firstValuesToAdd.put("test", "");
MapAwareMethodInterceptor mami2 = new MapAwareMethodInterceptor(new HashMap<>(), firstValuesToAdd);

View File

@ -186,8 +186,8 @@ class CommonsPool2TargetSourceTests {
pooledInstances[9] = targetSource.getTarget();
// release all objects
for (int i = 0; i < pooledInstances.length; i++) {
targetSource.releaseTarget(pooledInstances[i]);
for (Object pooledInstance : pooledInstances) {
targetSource.releaseTarget(pooledInstance);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -88,7 +88,7 @@ class ConfigurationClassAndBFPPTests {
@Autowired TestBean autowiredTestBean;
@Bean
public static final BeanFactoryPostProcessor bfpp() {
public static BeanFactoryPostProcessor bfpp() {
return beanFactory -> {
// no-op
};

View File

@ -37,7 +37,7 @@ public class AsyncResultTests {
String value = "val";
final Set<String> values = new HashSet<>(1);
org.springframework.util.concurrent.ListenableFuture<String> future = AsyncResult.forValue(value);
future.addCallback(new org.springframework.util.concurrent.ListenableFutureCallback<String>() {
future.addCallback(new org.springframework.util.concurrent.ListenableFutureCallback<>() {
@Override
public void onSuccess(String result) {
values.add(result);
@ -59,7 +59,7 @@ public class AsyncResultTests {
IOException ex = new IOException();
final Set<Throwable> values = new HashSet<>(1);
org.springframework.util.concurrent.ListenableFuture<String> future = AsyncResult.forExecutionException(ex);
future.addCallback(new org.springframework.util.concurrent.ListenableFutureCallback<String>() {
future.addCallback(new org.springframework.util.concurrent.ListenableFutureCallback<>() {
@Override
public void onSuccess(String result) {
throw new AssertionError("Success callback not expected: " + result);

View File

@ -276,7 +276,7 @@ class ScheduledAnnotationBeanPostProcessorObservabilityTests {
@Scheduled(fixedDelay = 10_000, initialDelay = 5_000)
Mono<String> hasCurrentObservation() {
return Mono.just("test")
.tap(() -> new DefaultSignalListener<String>() {
.tap(() -> new DefaultSignalListener<>() {
@Override
public void doFirst() throws Throwable {
Observation observation = observationRegistry.getCurrentObservation();

View File

@ -2043,7 +2043,7 @@ class DataBinderTests {
binder.bind(pvs);
assertThat(tb.getIntegerList()).hasSize(257);
assertThat(tb.getIntegerList()).element(256).isEqualTo(Integer.valueOf(1));
assertThat(tb.getIntegerList()).element(256).isEqualTo(1);
assertThat(binder.getBindingResult().getFieldValue("integerList[256]")).isEqualTo(1);
}

View File

@ -1,13 +1,13 @@
/*
* Copyright 2003,2004 The Apache Software Foundation
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
@ -24,6 +24,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import org.springframework.asm.ClassVisitor;
@ -288,7 +289,7 @@ abstract public class BeanMap implements Map {
}
Object v1 = get(key);
Object v2 = other.get(key);
if (!((v1 == null) ? v2 == null : v1.equals(v2))) {
if (!(Objects.equals(v1, v2))) {
return false;
}
}

View File

@ -607,8 +607,8 @@ public class ConcurrentReferenceHashMap<K, V> extends AbstractMap<K, V> implemen
// Restructure the resized reference array
if (resizing) {
Reference<K, V>[] restructured = createReferenceArray(restructureSize);
for (int i = 0; i < this.references.length; i++) {
ref = this.references[i];
for (Reference<K, V> reference : this.references) {
ref = reference;
while (ref != null) {
if (!toPurge.contains(ref)) {
Entry<K, V> entry = ref.get();

View File

@ -263,7 +263,7 @@ public abstract class AbstractMethodMetadataTests {
public static class WithPrivateMethod {
@Tag
private final String test() {
private String test() {
return "";
}

View File

@ -453,7 +453,7 @@ class ClassUtilsTests {
void isNotLambda() {
assertIsNotLambda(new EnigmaSupplier());
assertIsNotLambda(new Supplier<String>() {
assertIsNotLambda(new Supplier<>() {
@Override
public String get() {
return "anonymous inner class";

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -59,7 +59,7 @@ public class SpelExceptionTests {
ExpressionParser parser = new SpelExpressionParser();
Expression spelExpression = parser.parseExpression("#aMap['one'] eq 1");
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariables(new HashMap<String, Object>() {
ctx.setVariables(new HashMap<>() {
{
put("aMap", new HashMap<String, Integer>() {
{
@ -98,7 +98,7 @@ public class SpelExceptionTests {
ExpressionParser parser = new SpelExpressionParser();
Expression spelExpression = parser.parseExpression("#aList.contains('one')");
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariables(new HashMap<String, Object>() {
ctx.setVariables(new HashMap<>() {
{
put("aList", new ArrayList<String>() {
{
@ -120,7 +120,7 @@ public class SpelExceptionTests {
ExpressionParser parser = new SpelExpressionParser();
Expression spelExpression = parser.parseExpression("#aList[0] eq 'one'");
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariables(new HashMap<String, Object>() {
ctx.setVariables(new HashMap<>() {
{
put("aList", new ArrayList<String>() {
{
@ -150,7 +150,7 @@ public class SpelExceptionTests {
ExpressionParser parser = new SpelExpressionParser();
Expression spelExpression = parser.parseExpression("#anArray[0] eq 1");
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariables(new HashMap<String, Object>() {
ctx.setVariables(new HashMap<>() {
{
put("anArray", new int[] {1,2,3});
}

View File

@ -1778,19 +1778,13 @@ class SpelReproTests extends AbstractExpressionTests {
@Override
public Object resolve(EvaluationContext context, String beanName) throws AccessException {
if (beanName.equals("foo")) {
return "custard";
}
else if (beanName.equals("foo.bar")) {
return "trouble";
}
else if (beanName.equals("&foo")) {
return "foo factory";
}
else if (beanName.equals("goo")) {
throw new AccessException("DONT ASK ME ABOUT GOO");
}
return null;
return switch (beanName) {
case "foo" -> "custard";
case "foo.bar" -> "trouble";
case "&foo" -> "foo factory";
case "goo" -> throw new AccessException("DONT ASK ME ABOUT GOO");
default -> null;
};
}
}

View File

@ -242,19 +242,14 @@ public abstract class JdbcUtils {
// Corresponding SQL types for JSR-310 / Joda-Time types, left up
// to the caller to convert them (e.g. through a ConversionService).
String typeName = requiredType.getSimpleName();
if ("LocalDate".equals(typeName)) {
return rs.getDate(index);
}
else if ("LocalTime".equals(typeName)) {
return rs.getTime(index);
}
else if ("LocalDateTime".equals(typeName)) {
return rs.getTimestamp(index);
}
// Fall back to getObject without type specification, again
// left up to the caller to convert the value if necessary.
return getResultSetValue(rs, index);
return switch (typeName) {
case "LocalDate" -> rs.getDate(index);
case "LocalTime" -> rs.getTime(index);
case "LocalDateTime" -> rs.getTimestamp(index);
// Fall back to getObject without type specification, again
// left up to the caller to convert the value if necessary.
default -> getResultSetValue(rs, index);
};
}
// Perform was-null check if necessary (for results that the JDBC driver returns as primitives).

View File

@ -248,7 +248,7 @@ class DefaultMessageListenerContainerTests {
private static ConnectionFactory createRecoverableContainerFactory(final int failingAttempts) {
try {
ConnectionFactory connectionFactory = mock();
given(connectionFactory.createConnection()).will(new Answer<Object>() {
given(connectionFactory.createConnection()).will(new Answer<>() {
int currentAttempts = 0;
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {

View File

@ -22,6 +22,7 @@ import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonView;
import jakarta.jms.BytesMessage;
@ -285,10 +286,7 @@ class MappingJackson2MessageConverterTests {
return false;
}
MyBean bean = (MyBean) o;
if (foo != null ? !foo.equals(bean.foo) : bean.foo != null) {
return false;
}
return true;
return Objects.equals(this.foo, bean.foo);
}
@Override

View File

@ -1,3 +1,19 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: sample.proto

View File

@ -72,7 +72,14 @@ public class BufferingStompDecoderTests {
@Test
public void twoMessagesInOneChunk() throws InterruptedException {
BufferingStompDecoder stompDecoder = new BufferingStompDecoder(STOMP_DECODER, 128);
String chunk = "SEND\na:alpha\n\nPayload1\0" + "SEND\na:alpha\n\nPayload2\0";
String chunk = """
SEND
a:alpha
Payload1\0SEND
a:alpha
Payload2\0""";
List<Message<byte[]>> messages = stompDecoder.decode(toByteBuffer(chunk));
assertThat(messages).hasSize(2);

View File

@ -239,13 +239,10 @@ public class StompHeaderAccessorTests {
String actual = accessor.getShortLogMessage("payload".getBytes(StandardCharsets.UTF_8));
assertThat(actual).isEqualTo("SEND /foo session=123 application/json payload=payload");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 80; i++) {
sb.append('a');
}
final String payload = sb.toString() + " > 80";
String string = "a".repeat(80);
final String payload = string + " > 80";
actual = accessor.getShortLogMessage(payload.getBytes(StandardCharsets.UTF_8));
assertThat(actual).isEqualTo(("SEND /foo session=123 application/json payload=" + sb + "...(truncated)"));
assertThat(actual).isEqualTo(("SEND /foo session=123 application/json payload=" + string + "...(truncated)"));
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -34,7 +34,7 @@ public final class SystemProfileValueSource implements ProfileValueSource {
/**
* Obtain the canonical instance of this ProfileValueSource.
*/
public static final SystemProfileValueSource getInstance() {
public static SystemProfileValueSource getInstance() {
return INSTANCE;
}

View File

@ -32,7 +32,7 @@ public class ContextCacheTestUtils {
/**
* Reset the state of the static context cache in {@link DefaultCacheAwareContextLoaderDelegate}.
*/
public static final void resetContextCache() {
public static void resetContextCache() {
DefaultCacheAwareContextLoaderDelegate.defaultContextCache.reset();
}
@ -43,7 +43,7 @@ public class ContextCacheTestUtils {
* @param expectedHitCount the expected hit count
* @param expectedMissCount the expected miss count
*/
public static final void assertContextCacheStatistics(int expectedSize, int expectedHitCount, int expectedMissCount) {
public static void assertContextCacheStatistics(int expectedSize, int expectedHitCount, int expectedMissCount) {
assertContextCacheStatistics(null, expectedSize, expectedHitCount, expectedMissCount);
}
@ -55,7 +55,7 @@ public class ContextCacheTestUtils {
* @param expectedHitCount the expected hit count
* @param expectedMissCount the expected miss count
*/
public static final void assertContextCacheStatistics(String usageScenario, int expectedSize, int expectedHitCount,
public static void assertContextCacheStatistics(String usageScenario, int expectedSize, int expectedHitCount,
int expectedMissCount) {
assertContextCacheStatistics(DefaultCacheAwareContextLoaderDelegate.defaultContextCache, usageScenario,
expectedSize, expectedHitCount, expectedMissCount);
@ -70,7 +70,7 @@ public class ContextCacheTestUtils {
* @param expectedHitCount the expected hit count
* @param expectedMissCount the expected miss count
*/
public static final void assertContextCacheStatistics(ContextCache contextCache, String usageScenario,
public static void assertContextCacheStatistics(ContextCache contextCache, String usageScenario,
int expectedSize, int expectedHitCount, int expectedMissCount) {
String context = (StringUtils.hasText(usageScenario) ? " (" + usageScenario + ")" : "");

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -131,60 +131,26 @@ public class FacesRequestAttributes implements RequestAttributes {
@Override
public Object resolveReference(String key) {
if (REFERENCE_REQUEST.equals(key)) {
return getExternalContext().getRequest();
}
else if (REFERENCE_SESSION.equals(key)) {
return getExternalContext().getSession(true);
}
else if ("application".equals(key)) {
return getExternalContext().getContext();
}
else if ("requestScope".equals(key)) {
return getExternalContext().getRequestMap();
}
else if ("sessionScope".equals(key)) {
return getExternalContext().getSessionMap();
}
else if ("applicationScope".equals(key)) {
return getExternalContext().getApplicationMap();
}
else if ("facesContext".equals(key)) {
return getFacesContext();
}
else if ("cookie".equals(key)) {
return getExternalContext().getRequestCookieMap();
}
else if ("header".equals(key)) {
return getExternalContext().getRequestHeaderMap();
}
else if ("headerValues".equals(key)) {
return getExternalContext().getRequestHeaderValuesMap();
}
else if ("param".equals(key)) {
return getExternalContext().getRequestParameterMap();
}
else if ("paramValues".equals(key)) {
return getExternalContext().getRequestParameterValuesMap();
}
else if ("initParam".equals(key)) {
return getExternalContext().getInitParameterMap();
}
else if ("view".equals(key)) {
return getFacesContext().getViewRoot();
}
else if ("viewScope".equals(key)) {
return getFacesContext().getViewRoot().getViewMap();
}
else if ("flash".equals(key)) {
return getExternalContext().getFlash();
}
else if ("resource".equals(key)) {
return getFacesContext().getApplication().getResourceHandler();
}
else {
return null;
}
return switch (key) {
case REFERENCE_REQUEST -> getExternalContext().getRequest();
case REFERENCE_SESSION -> getExternalContext().getSession(true);
case "application" -> getExternalContext().getContext();
case "requestScope" -> getExternalContext().getRequestMap();
case "sessionScope" -> getExternalContext().getSessionMap();
case "applicationScope" -> getExternalContext().getApplicationMap();
case "facesContext" -> getFacesContext();
case "cookie" -> getExternalContext().getRequestCookieMap();
case "header" -> getExternalContext().getRequestHeaderMap();
case "headerValues" -> getExternalContext().getRequestHeaderValuesMap();
case "param" -> getExternalContext().getRequestParameterMap();
case "paramValues" -> getExternalContext().getRequestParameterValuesMap();
case "initParam" -> getExternalContext().getInitParameterMap();
case "view" -> getFacesContext().getViewRoot();
case "viewScope" -> getFacesContext().getViewRoot().getViewMap();
case "flash" -> getExternalContext().getFlash();
case "resource" -> getFacesContext().getApplication().getResourceHandler();
default -> null;
};
}
@Override

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -67,18 +67,12 @@ public abstract class TagUtils {
*/
public static int getScope(String scope) {
Assert.notNull(scope, "Scope to search for cannot be null");
if (scope.equals(SCOPE_REQUEST)) {
return PageContext.REQUEST_SCOPE;
}
else if (scope.equals(SCOPE_SESSION)) {
return PageContext.SESSION_SCOPE;
}
else if (scope.equals(SCOPE_APPLICATION)) {
return PageContext.APPLICATION_SCOPE;
}
else {
return PageContext.PAGE_SCOPE;
}
return switch (scope) {
case SCOPE_REQUEST -> PageContext.REQUEST_SCOPE;
case SCOPE_SESSION -> PageContext.SESSION_SCOPE;
case SCOPE_APPLICATION -> PageContext.APPLICATION_SCOPE;
default -> PageContext.PAGE_SCOPE;
};
}
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -56,7 +56,7 @@ public class MultipartBodyBuilderTests {
Publisher<String> publisher = Flux.just("foo", "bar", "baz");
builder.asyncPart("publisherClass", publisher, String.class).header("baz", "qux");
builder.asyncPart("publisherPtr", publisher, new ParameterizedTypeReference<String>() {}).header("baz", "qux");
builder.asyncPart("publisherPtr", publisher, new ParameterizedTypeReference<>() {}).header("baz", "qux");
MultiValueMap<String, HttpEntity<?>> result = builder.build();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -162,11 +162,8 @@ public class ProtobufDecoderTests extends AbstractDecoderTests<ProtobufDecoder>
@SuppressWarnings("deprecation")
public void decodeSplitMessageSize() {
this.decoder.setMaxMessageSize(100009);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 10000; i++) {
builder.append("azertyuiop");
}
Msg bigMessage = Msg.newBuilder().setFoo(builder.toString()).setBlah(secondMsg2).build();
Msg bigMessage = Msg.newBuilder().setFoo("azertyuiop".repeat(10000))
.setBlah(secondMsg2).build();
Flux<DataBuffer> input = Flux.just(bigMessage, bigMessage)
.flatMap(msg -> Mono.defer(() -> {

View File

@ -169,7 +169,7 @@ class ChannelSendOperatorTests {
return Mono.never();
});
operator.subscribe(new BaseSubscriber<Void>() {});
operator.subscribe(new BaseSubscriber<>() {});
try {
writeSubscriber.signalDemand(1); // Let cached signals ("foo" and error) be published..
}

View File

@ -1,3 +1,19 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: sample.proto

View File

@ -166,7 +166,7 @@ class RestClientIntegrationTests {
ValueContainer<Pojo> result = this.restClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.body(new ParameterizedTypeReference<ValueContainer<Pojo>>() {});
.body(new ParameterizedTypeReference<>() {});
assertThat(result.getContainerValue()).isNotNull();
Pojo pojo = result.getContainerValue();
@ -191,7 +191,7 @@ class RestClientIntegrationTests {
ValueContainer<List<Pojo>> result = this.restClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.body(new ParameterizedTypeReference<ValueContainer<List<Pojo>>>() {});
.body(new ParameterizedTypeReference<>() {});
assertThat(result.containerValue).isNotNull();
assertThat(result.containerValue).containsExactly(new Pojo("foofoo", "barbar"));

View File

@ -474,7 +474,7 @@ public class PathPatternParserTests {
}
@SafeVarargs
private final void assertPathElements(PathPattern p, Class<? extends PathElement>... sectionClasses) {
private void assertPathElements(PathPattern p, Class<? extends PathElement>... sectionClasses) {
PathElement head = p.getHeadSection();
for (Class<? extends PathElement> sectionClass : sectionClasses) {
if (head == null) {

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -164,7 +164,7 @@ public class RequestContext {
* no explicit default given.
*/
public boolean isDefaultHtmlEscape() {
return (this.defaultHtmlEscape != null && this.defaultHtmlEscape.booleanValue());
return (this.defaultHtmlEscape != null && this.defaultHtmlEscape);
}
/**

View File

@ -138,7 +138,7 @@ class BodyExtractorsTests {
@Test
void toMonoParameterizedTypeReference() {
BodyExtractor<Mono<Map<String, String>>, ReactiveHttpInputMessage> extractor =
BodyExtractors.toMono(new ParameterizedTypeReference<Map<String, String>>() {});
BodyExtractors.toMono(new ParameterizedTypeReference<>() {});
byte[] bytes = "{\"username\":\"foo\",\"password\":\"bar\"}".getBytes(StandardCharsets.UTF_8);
DefaultDataBuffer dataBuffer = DefaultDataBufferFactory.sharedInstance.wrap(ByteBuffer.wrap(bytes));
@ -183,7 +183,7 @@ class BodyExtractorsTests {
@Test // SPR-15758
void toMonoWithEmptyBodyAndNoContentType() {
BodyExtractor<Mono<Map<String, String>>, ReactiveHttpInputMessage> extractor =
BodyExtractors.toMono(new ParameterizedTypeReference<Map<String, String>>() {});
BodyExtractors.toMono(new ParameterizedTypeReference<>() {});
MockServerHttpRequest request = MockServerHttpRequest.post("/").body(Flux.empty());
Mono<Map<String, String>> result = extractor.extract(request, this.context);

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -404,16 +404,18 @@ public class BodyInsertersTests {
dataBuffer.read(resultBytes);
DataBufferUtils.release(dataBuffer);
String content = new String(resultBytes, StandardCharsets.UTF_8);
assertThat(content).contains("Content-Disposition: form-data; name=\"name\"\r\n" +
"Content-Type: text/plain;charset=UTF-8\r\n" +
"Content-Length: 6\r\n" +
"\r\n" +
"value1");
assertThat(content).contains("Content-Disposition: form-data; name=\"name\"\r\n" +
"Content-Type: text/plain;charset=UTF-8\r\n" +
"Content-Length: 6\r\n" +
"\r\n" +
"value2");
assertThat(content).contains("""
Content-Disposition: form-data; name="name"\r
Content-Type: text/plain;charset=UTF-8\r
Content-Length: 6\r
\r
value1""");
assertThat(content).contains("""
Content-Disposition: form-data; name="name"\r
Content-Type: text/plain;charset=UTF-8\r
Content-Length: 6\r
\r
value2""");
})
.expectComplete()
.verify();

View File

@ -124,7 +124,7 @@ class WebClientDataBufferAllocatingTests extends AbstractDataBufferAllocatingTes
Mono<Map<String, String>> mono = this.webClient.get()
.uri("/sample").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<Map<String, String>>() {});
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(mono).expectError(WebClientResponseException.class).verify(Duration.ofSeconds(3));
assertThat(this.server.getRequestCount()).isEqualTo(1);

View File

@ -197,7 +197,7 @@ class WebClientIntegrationTests {
Mono<ValueContainer<Pojo>> result = this.webClient.get()
.uri("/json").accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<ValueContainer<Pojo>>() {});
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(result)
.assertNext(c -> assertThat(c.getContainerValue()).isEqualTo(new Pojo("foofoo", "barbar")))
@ -804,7 +804,7 @@ class WebClientIntegrationTests {
.uri("/greeting")
.retrieve()
.onStatus(HttpStatusCode::is5xxServerError, response -> Mono.just(new MyException("500 error!")))
.bodyToMono(new ParameterizedTypeReference<String>() {});
.bodyToMono(new ParameterizedTypeReference<>() {});
StepVerifier.create(result)
.expectError(MyException.class)

View File

@ -318,8 +318,7 @@ public class DefaultServerRequestTests {
DefaultServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), messageReaders);
Mono<Map<String, String>> resultMono = request.bodyToMono(
new ParameterizedTypeReference<Map<String, String>>() {
});
new ParameterizedTypeReference<>() {});
StepVerifier.create(resultMono)
.expectError(ServerWebInputException.class)
.verify();

View File

@ -18,6 +18,7 @@ package org.springframework.web.reactive.function.server;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@ -275,7 +276,7 @@ class DispatcherHandlerIntegrationTests extends AbstractHttpHandlerIntegrationTe
return false;
}
Person person = (Person) o;
return !(this.name != null ? !this.name.equals(person.name) : person.name != null);
return Objects.equals(this.name, person.name);
}
@Override

View File

@ -18,6 +18,7 @@ package org.springframework.web.reactive.function.server;
import java.net.URI;
import java.util.List;
import java.util.Objects;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@ -146,7 +147,7 @@ class PublisherHandlerFunctionIntegrationTests extends AbstractRouterFunctionInt
return false;
}
Person person = (Person) o;
return !(this.name != null ? !this.name.equals(person.name) : person.name != null);
return Objects.equals(this.name, person.name);
}
@Override

View File

@ -17,6 +17,7 @@
package org.springframework.web.reactive.function.server;
import java.time.Duration;
import java.util.Objects;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@ -100,7 +101,7 @@ class SseHandlerFunctionIntegrationTests extends AbstractRouterFunctionIntegrati
.uri("/event")
.accept(TEXT_EVENT_STREAM)
.retrieve()
.bodyToFlux(new ParameterizedTypeReference<ServerSentEvent<String>>() {});
.bodyToFlux(new ParameterizedTypeReference<>() {});
StepVerifier.create(result)
.consumeNextWith( event -> {
@ -175,7 +176,7 @@ class SseHandlerFunctionIntegrationTests extends AbstractRouterFunctionIntegrati
return false;
}
Person person = (Person) o;
return !(this.name != null ? !this.name.equals(person.name) : person.name != null);
return Objects.equals(this.name, person.name);
}
@Override

View File

@ -1,3 +1,19 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: sample.proto

View File

@ -17,6 +17,7 @@
package org.springframework.web.reactive.result.method.annotation;
import java.time.Duration;
import java.util.Objects;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
@ -153,7 +154,7 @@ class JacksonStreamingIntegrationTests extends AbstractHttpHandlerIntegrationTes
return false;
}
Person person = (Person) o;
return !(this.name != null ? !this.name.equals(person.name) : person.name != null);
return Objects.equals(this.name, person.name);
}
@Override

View File

@ -21,6 +21,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import io.reactivex.rxjava3.core.Completable;
@ -712,7 +713,7 @@ class RequestMappingMessageConversionIntegrationTests extends AbstractRequestMap
return false;
}
Person person = (Person) o;
return !(this.name != null ? !this.name.equals(person.name) : person.name != null);
return Objects.equals(this.name, person.name);
}
@Override

View File

@ -21,6 +21,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.time.Duration;
import java.util.Objects;
import java.util.stream.Stream;
import org.junit.jupiter.api.Disabled;
@ -134,7 +135,7 @@ class SseIntegrationTests extends AbstractHttpHandlerIntegrationTests {
.uri("/event")
.accept(TEXT_EVENT_STREAM)
.retrieve()
.bodyToFlux(new ParameterizedTypeReference<ServerSentEvent<Person>>() {});
.bodyToFlux(new ParameterizedTypeReference<>() {});
verifyPersonEvents(result);
}
@ -147,7 +148,7 @@ class SseIntegrationTests extends AbstractHttpHandlerIntegrationTests {
.uri("/event")
.accept(TEXT_EVENT_STREAM)
.retrieve()
.bodyToFlux(new ParameterizedTypeReference<ServerSentEvent<Person>>() {});
.bodyToFlux(new ParameterizedTypeReference<>() {});
verifyPersonEvents(result);
}
@ -277,7 +278,7 @@ class SseIntegrationTests extends AbstractHttpHandlerIntegrationTests {
return false;
}
Person person = (Person) o;
return !(this.name != null ? !this.name.equals(person.name) : person.name != null);
return Objects.equals(this.name, person.name);
}
@Override

View File

@ -474,7 +474,7 @@ public class RequestContext {
* Is default HTML escaping active? Falls back to {@code false} in case of no explicit default given.
*/
public boolean isDefaultHtmlEscape() {
return (this.defaultHtmlEscape != null && this.defaultHtmlEscape.booleanValue());
return (this.defaultHtmlEscape != null && this.defaultHtmlEscape);
}
/**
@ -493,7 +493,7 @@ public class RequestContext {
* @since 4.1.2
*/
public boolean isResponseEncodedHtmlEscape() {
return (this.responseEncodedHtmlEscape == null || this.responseEncodedHtmlEscape.booleanValue());
return (this.responseEncodedHtmlEscape == null || this.responseEncodedHtmlEscape);
}
/**

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -61,7 +61,7 @@ public abstract class HtmlEscapingAwareTag extends RequestContextAwareTag {
*/
protected boolean isHtmlEscape() {
if (this.htmlEscape != null) {
return this.htmlEscape.booleanValue();
return this.htmlEscape;
}
else {
return isDefaultHtmlEscape();

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -111,7 +111,7 @@ public abstract class AbstractFormTag extends HtmlEscapingAwareTag {
@Override
protected boolean isDefaultHtmlEscape() {
Boolean defaultHtmlEscape = getRequestContext().getDefaultHtmlEscape();
return (defaultHtmlEscape == null || defaultHtmlEscape.booleanValue());
return (defaultHtmlEscape == null || defaultHtmlEscape);
}

View File

@ -114,8 +114,11 @@ public class ComplexWebApplicationContext extends StaticWebApplicationContext {
pvs = new MutablePropertyValues();
pvs.add(
"mappings", "/head.do=headController\n" +
"body.do=bodyController\n/noview*=noviewController\n/noview/simple*=noviewController");
"mappings", """
/head.do=headController
body.do=bodyController
/noview*=noviewController
/noview/simple*=noviewController""");
pvs.add("order", "1");
registerSingleton("handlerMapping", SimpleUrlHandlerMapping.class, pvs);

View File

@ -60,7 +60,7 @@ class DefaultEntityResponseBuilderTests {
void fromObjectTypeReference() {
String body = "foo";
EntityResponse<String> response = EntityResponse.fromObject(body,
new ParameterizedTypeReference<String>() {})
new ParameterizedTypeReference<>() {})
.build();
assertThat(response.entity()).isSameAs(body);

View File

@ -265,7 +265,7 @@ class DefaultServerRequestTests {
DefaultServerRequest request = new DefaultServerRequest(servletRequest,
List.of(new MappingJackson2HttpMessageConverter()));
List<String> result = request.body(new ParameterizedTypeReference<List<String>>() {});
List<String> result = request.body(new ParameterizedTypeReference<>() {});
assertThat(result).hasSize(2);
assertThat(result).element(0).isEqualTo("foo");
assertThat(result).element(1).isEqualTo("bar");

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -293,7 +293,7 @@ class DefaultServerResponseBuilderTests {
List<String> body = new ArrayList<>();
body.add("foo");
body.add("bar");
ServerResponse response = ServerResponse.ok().body(body, new ParameterizedTypeReference<List<String>>() {});
ServerResponse response = ServerResponse.ok().body(body, new ParameterizedTypeReference<>() {});
MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", "https://example.com");
MockHttpServletResponse mockResponse = new MockHttpServletResponse();

View File

@ -109,11 +109,13 @@ class SseServerResponseTests {
ModelAndView mav = response.writeTo(this.mockRequest, this.mockResponse, context);
assertThat(mav).isNull();
String expected = "data:{\n" +
"data: \"name\" : \"John Doe\",\n" +
"data: \"age\" : 42\n" +
"data:}\n" +
"\n";
String expected = """
data:{
data: "name" : "John Doe",
data: "age" : 42
data:}
""";
assertThat(this.mockResponse.getContentAsString()).isEqualTo(expected);
}

View File

@ -291,7 +291,7 @@ class ViewResolverTests {
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.wac);
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver());
View view = vr.resolveViewName("example1", Locale.getDefault());
view.render(new HashMap<String, Object>(), request, this.response);
view.render(new HashMap<>(), request, this.response);
}
@Test
@ -327,7 +327,7 @@ class ViewResolverTests {
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.wac);
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver());
View view = vr.resolveViewName("example1", Locale.getDefault());
view.render(new HashMap<String, Object>(), request, this.response);
view.render(new HashMap<>(), request, this.response);
}
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -102,11 +102,7 @@ public class SpringConfigurator extends Configurator {
private String getBeanNameByType(WebApplicationContext wac, Class<?> endpointClass) {
String wacId = wac.getId();
Map<Class<?>, String> beanNamesByType = cache.get(wacId);
if (beanNamesByType == null) {
beanNamesByType = new ConcurrentHashMap<>();
cache.put(wacId, beanNamesByType);
}
Map<Class<?>, String> beanNamesByType = cache.computeIfAbsent(wacId, k -> new ConcurrentHashMap<>());
if (!beanNamesByType.containsKey(endpointClass)) {
String[] names = wac.getBeanNamesForType(endpointClass);

View File

@ -20,7 +20,6 @@ import java.io.ByteArrayOutputStream;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.concurrent.CompletableFuture;
import org.eclipse.jetty.client.ContentResponse;
@ -172,9 +171,7 @@ public class JettyXhrTransport extends AbstractXhrTransport implements Lifecycle
private static HttpHeaders toHttpHeaders(HttpFields httpFields) {
HttpHeaders responseHeaders = new HttpHeaders();
Iterator<String> names = httpFields.getFieldNamesCollection().iterator();
while (names.hasNext()) {
String name = names.next();
for (String name : httpFields.getFieldNamesCollection()) {
Enumeration<String> values = httpFields.getValues(name);
while (values.hasMoreElements()) {
String value = values.nextElement();

View File

@ -216,7 +216,7 @@ abstract class AbstractSockJsIntegrationTests {
CountDownLatch latch = new CountDownLatch(1);
initSockJsClient(createWebSocketTransport());
this.sockJsClient.doHandshake(handler, this.baseUrl + "/echo").addCallback(
new org.springframework.util.concurrent.ListenableFutureCallback<WebSocketSession>() {
new org.springframework.util.concurrent.ListenableFutureCallback<>() {
@Override
public void onSuccess(WebSocketSession result) {
}

View File

@ -137,7 +137,7 @@ class RestTemplateXhrTransportTests {
final CountDownLatch latch = new CountDownLatch(1);
connect(restTemplate).addCallback(
new org.springframework.util.concurrent.ListenableFutureCallback<WebSocketSession>() {
new org.springframework.util.concurrent.ListenableFutureCallback<>() {
@Override
public void onSuccess(WebSocketSession result) {
}