Browse Source

Use enhanced switch expressions where feasible

Closes gh-28014
pull/28094/head
a.yazychyan 4 years ago committed by Sam Brannen
parent
commit
c5c926726d
  1. 18
      spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectMetadata.java
  2. 15
      spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/InstantiationModelAwarePointcutAdvisorImpl.java
  3. 34
      spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/ReflectiveAspectJAdvisorFactory.java
  4. 20
      spring-beans/src/jmh/java/org/springframework/beans/AbstractPropertyAccessorBenchmark.java
  5. 20
      spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMessageHelper.java
  6. 12
      spring-context/src/main/java/org/springframework/cache/annotation/CachingConfigurationSelector.java
  7. 28
      spring-context/src/main/java/org/springframework/context/annotation/TypeFilterUtils.java
  8. 10
      spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeFormatterRegistrar.java
  9. 16
      spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncConfigurationSelector.java
  10. 23
      spring-core/src/main/java/org/springframework/asm/TypePath.java
  11. 41
      spring-core/src/main/java/org/springframework/core/annotation/AnnotationsScanner.java
  12. 23
      spring-core/src/main/java/org/springframework/core/env/ProfilesParser.java
  13. 13
      spring-core/src/main/java/org/springframework/core/io/buffer/DataBufferUtils.java
  14. 28
      spring-core/src/main/java/org/springframework/util/concurrent/ListenableFutureCallbackRegistry.java
  15. 6
      spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java
  16. 21
      spring-expression/src/main/java/org/springframework/expression/spel/ast/OpDivide.java
  17. 42
      spring-expression/src/main/java/org/springframework/expression/spel/ast/OpMinus.java
  18. 21
      spring-expression/src/main/java/org/springframework/expression/spel/ast/OpModulus.java
  19. 21
      spring-expression/src/main/java/org/springframework/expression/spel/ast/OpMultiply.java
  20. 21
      spring-expression/src/main/java/org/springframework/expression/spel/ast/OpPlus.java
  21. 12
      spring-expression/src/main/java/org/springframework/expression/spel/ast/Selection.java
  22. 29
      spring-jcl/src/main/java/org/apache/commons/logging/LogAdapter.java
  23. 13
      spring-jms/src/main/java/org/springframework/jms/support/converter/MarshallingMessageConverter.java
  24. 15
      spring-messaging/src/jmh/java/org/springframework/messaging/simp/broker/DefaultSubscriptionRegistryBenchmark.java
  25. 24
      spring-messaging/src/main/java/org/springframework/messaging/rsocket/annotation/support/RSocketFrameTypeMessageCondition.java
  26. 9
      spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java
  27. 26
      spring-orm/src/main/java/org/springframework/orm/jpa/vendor/EclipseLinkJpaVendorAdapter.java
  28. 28
      spring-orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaVendorAdapter.java
  29. 18
      spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/R2dbcTransactionManager.java
  30. 38
      spring-test/src/main/java/org/springframework/mock/web/MockPageContext.java
  31. 16
      spring-tx/src/main/java/org/springframework/transaction/HeuristicCompletionException.java
  32. 11
      spring-tx/src/main/java/org/springframework/transaction/jta/SpringJtaSynchronizationAdapter.java
  33. 16
      spring-web/src/main/java/org/springframework/http/codec/json/Jackson2Tokenizer.java
  34. 9
      spring-web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java
  35. 38
      spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockPageContext.java
  36. 19
      spring-webmvc/src/main/java/org/springframework/web/servlet/config/ViewControllerBeanDefinitionParser.java
  37. 11
      spring-websocket/src/main/java/org/springframework/web/socket/handler/ConcurrentWebSocketSessionDecorator.java
  38. 19
      spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractSockJsSession.java

18
spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/AspectMetadata.java

@ -101,24 +101,22 @@ public class AspectMetadata implements Serializable {
this.ajType = ajType; this.ajType = ajType;
switch (this.ajType.getPerClause().getKind()) { switch (this.ajType.getPerClause().getKind()) {
case SINGLETON: case SINGLETON -> {
this.perClausePointcut = Pointcut.TRUE; this.perClausePointcut = Pointcut.TRUE;
return; }
case PERTARGET: case PERTARGET, PERTHIS -> {
case PERTHIS:
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut(); AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setLocation(aspectClass.getName()); ajexp.setLocation(aspectClass.getName());
ajexp.setExpression(findPerClause(aspectClass)); ajexp.setExpression(findPerClause(aspectClass));
ajexp.setPointcutDeclarationScope(aspectClass); ajexp.setPointcutDeclarationScope(aspectClass);
this.perClausePointcut = ajexp; this.perClausePointcut = ajexp;
return; }
case PERTYPEWITHIN: case PERTYPEWITHIN -> {
// Works with a type pattern // Works with a type pattern
this.perClausePointcut = new ComposablePointcut(new TypePatternClassFilter(findPerClause(aspectClass))); this.perClausePointcut = new ComposablePointcut(new TypePatternClassFilter(findPerClause(aspectClass)));
return; }
default: default -> throw new AopConfigException(
throw new AopConfigException( "PerClause " + ajType.getPerClause().getKind() + " not supported by Spring AOP for " + aspectClass);
"PerClause " + ajType.getPerClause().getKind() + " not supported by Spring AOP for " + aspectClass);
} }
} }

15
spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/InstantiationModelAwarePointcutAdvisorImpl.java

@ -220,21 +220,18 @@ final class InstantiationModelAwarePointcutAdvisorImpl
} }
else { else {
switch (aspectJAnnotation.getAnnotationType()) { switch (aspectJAnnotation.getAnnotationType()) {
case AtPointcut: case AtPointcut, AtAround -> {
case AtAround:
this.isBeforeAdvice = false; this.isBeforeAdvice = false;
this.isAfterAdvice = false; this.isAfterAdvice = false;
break; }
case AtBefore: case AtBefore -> {
this.isBeforeAdvice = true; this.isBeforeAdvice = true;
this.isAfterAdvice = false; this.isAfterAdvice = false;
break; }
case AtAfter: case AtAfter, AtAfterReturning, AtAfterThrowing -> {
case AtAfterReturning:
case AtAfterThrowing:
this.isBeforeAdvice = false; this.isBeforeAdvice = false;
this.isAfterAdvice = true; this.isAfterAdvice = true;
break; }
} }
} }
} }

34
spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/ReflectiveAspectJAdvisorFactory.java

@ -261,42 +261,36 @@ public class ReflectiveAspectJAdvisorFactory extends AbstractAspectJAdvisorFacto
AbstractAspectJAdvice springAdvice; AbstractAspectJAdvice springAdvice;
switch (aspectJAnnotation.getAnnotationType()) { switch (aspectJAnnotation.getAnnotationType()) {
case AtPointcut: case AtPointcut -> {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Processing pointcut '" + candidateAdviceMethod.getName() + "'"); logger.debug("Processing pointcut '" + candidateAdviceMethod.getName() + "'");
} }
return null; return null;
case AtAround: }
springAdvice = new AspectJAroundAdvice( case AtAround -> springAdvice = new AspectJAroundAdvice(
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory); candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
break; case AtBefore -> springAdvice = new AspectJMethodBeforeAdvice(
case AtBefore: candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
springAdvice = new AspectJMethodBeforeAdvice( case AtAfter -> springAdvice = new AspectJAfterAdvice(
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory); candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
break; case AtAfterReturning -> {
case AtAfter:
springAdvice = new AspectJAfterAdvice(
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
break;
case AtAfterReturning:
springAdvice = new AspectJAfterReturningAdvice( springAdvice = new AspectJAfterReturningAdvice(
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory); candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
AfterReturning afterReturningAnnotation = (AfterReturning) aspectJAnnotation.getAnnotation(); AfterReturning afterReturningAnnotation = (AfterReturning) aspectJAnnotation.getAnnotation();
if (StringUtils.hasText(afterReturningAnnotation.returning())) { if (StringUtils.hasText(afterReturningAnnotation.returning())) {
springAdvice.setReturningName(afterReturningAnnotation.returning()); springAdvice.setReturningName(afterReturningAnnotation.returning());
} }
break; }
case AtAfterThrowing: case AtAfterThrowing -> {
springAdvice = new AspectJAfterThrowingAdvice( springAdvice = new AspectJAfterThrowingAdvice(
candidateAdviceMethod, expressionPointcut, aspectInstanceFactory); candidateAdviceMethod, expressionPointcut, aspectInstanceFactory);
AfterThrowing afterThrowingAnnotation = (AfterThrowing) aspectJAnnotation.getAnnotation(); AfterThrowing afterThrowingAnnotation = (AfterThrowing) aspectJAnnotation.getAnnotation();
if (StringUtils.hasText(afterThrowingAnnotation.throwing())) { if (StringUtils.hasText(afterThrowingAnnotation.throwing())) {
springAdvice.setThrowingName(afterThrowingAnnotation.throwing()); springAdvice.setThrowingName(afterThrowingAnnotation.throwing());
} }
break; }
default: default -> throw new UnsupportedOperationException(
throw new UnsupportedOperationException( "Unsupported advice type on method: " + candidateAdviceMethod);
"Unsupported advice type on method: " + candidateAdviceMethod);
} }
// Now to configure the advice... // Now to configure the advice...

20
spring-beans/src/jmh/java/org/springframework/beans/AbstractPropertyAccessorBenchmark.java

@ -61,18 +61,14 @@ public class AbstractPropertyAccessorBenchmark {
this.propertyAccessor = new BeanWrapperImpl(this.target); this.propertyAccessor = new BeanWrapperImpl(this.target);
} }
switch (this.customEditor) { switch (this.customEditor) {
case "stringTrimmer": case "stringTrimmer" -> this.propertyAccessor.registerCustomEditor(String.class,
this.propertyAccessor.registerCustomEditor(String.class, new StringTrimmerEditor(false)); new StringTrimmerEditor(false));
break; case "numberOnPath" -> this.propertyAccessor.registerCustomEditor(int.class, "array.somePath",
case "numberOnPath": new CustomNumberEditor(Integer.class, false));
this.propertyAccessor.registerCustomEditor(int.class, "array.somePath", new CustomNumberEditor(Integer.class, false)); case "numberOnNestedPath" -> this.propertyAccessor.registerCustomEditor(int.class, "array[0].somePath",
break; new CustomNumberEditor(Integer.class, false));
case "numberOnNestedPath": case "numberOnType" -> this.propertyAccessor.registerCustomEditor(int.class,
this.propertyAccessor.registerCustomEditor(int.class, "array[0].somePath", new CustomNumberEditor(Integer.class, false)); new CustomNumberEditor(Integer.class, false));
break;
case "numberOnType":
this.propertyAccessor.registerCustomEditor(int.class, new CustomNumberEditor(Integer.class, false));
break;
} }
} }

20
spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMessageHelper.java

@ -333,20 +333,18 @@ public class MimeMessageHelper {
*/ */
protected void createMimeMultiparts(MimeMessage mimeMessage, int multipartMode) throws MessagingException { protected void createMimeMultiparts(MimeMessage mimeMessage, int multipartMode) throws MessagingException {
switch (multipartMode) { switch (multipartMode) {
case MULTIPART_MODE_NO: case MULTIPART_MODE_NO -> setMimeMultiparts(null, null);
setMimeMultiparts(null, null); case MULTIPART_MODE_MIXED -> {
break;
case MULTIPART_MODE_MIXED:
MimeMultipart mixedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_MIXED); MimeMultipart mixedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_MIXED);
mimeMessage.setContent(mixedMultipart); mimeMessage.setContent(mixedMultipart);
setMimeMultiparts(mixedMultipart, mixedMultipart); setMimeMultiparts(mixedMultipart, mixedMultipart);
break; }
case MULTIPART_MODE_RELATED: case MULTIPART_MODE_RELATED -> {
MimeMultipart relatedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_RELATED); MimeMultipart relatedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_RELATED);
mimeMessage.setContent(relatedMultipart); mimeMessage.setContent(relatedMultipart);
setMimeMultiparts(relatedMultipart, relatedMultipart); setMimeMultiparts(relatedMultipart, relatedMultipart);
break; }
case MULTIPART_MODE_MIXED_RELATED: case MULTIPART_MODE_MIXED_RELATED -> {
MimeMultipart rootMixedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_MIXED); MimeMultipart rootMixedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_MIXED);
mimeMessage.setContent(rootMixedMultipart); mimeMessage.setContent(rootMixedMultipart);
MimeMultipart nestedRelatedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_RELATED); MimeMultipart nestedRelatedMultipart = new MimeMultipart(MULTIPART_SUBTYPE_RELATED);
@ -354,9 +352,9 @@ public class MimeMessageHelper {
relatedBodyPart.setContent(nestedRelatedMultipart); relatedBodyPart.setContent(nestedRelatedMultipart);
rootMixedMultipart.addBodyPart(relatedBodyPart); rootMixedMultipart.addBodyPart(relatedBodyPart);
setMimeMultiparts(rootMixedMultipart, nestedRelatedMultipart); setMimeMultiparts(rootMixedMultipart, nestedRelatedMultipart);
break; }
default: default -> throw new IllegalArgumentException(
throw new IllegalArgumentException("Only multipart modes MIXED_RELATED, RELATED and NO supported"); "Only multipart modes MIXED_RELATED, RELATED and NO supported");
} }
} }

12
spring-context/src/main/java/org/springframework/cache/annotation/CachingConfigurationSelector.java vendored

@ -68,14 +68,10 @@ public class CachingConfigurationSelector extends AdviceModeImportSelector<Enabl
*/ */
@Override @Override
public String[] selectImports(AdviceMode adviceMode) { public String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) { return switch (adviceMode) {
case PROXY: case PROXY -> getProxyImports();
return getProxyImports(); case ASPECTJ -> getAspectJImports();
case ASPECTJ: };
return getAspectJImports();
default:
return null;
}
} }
/** /**

28
spring-context/src/main/java/org/springframework/context/annotation/TypeFilterUtils.java

@ -78,38 +78,32 @@ public abstract class TypeFilterUtils {
for (Class<?> filterClass : filterAttributes.getClassArray("classes")) { for (Class<?> filterClass : filterAttributes.getClassArray("classes")) {
switch (filterType) { switch (filterType) {
case ANNOTATION: case ANNOTATION -> {
Assert.isAssignable(Annotation.class, filterClass, Assert.isAssignable(Annotation.class, filterClass,
"@ComponentScan ANNOTATION type filter requires an annotation type"); "@ComponentScan ANNOTATION type filter requires an annotation type");
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Class<Annotation> annotationType = (Class<Annotation>) filterClass; Class<Annotation> annotationType = (Class<Annotation>) filterClass;
typeFilters.add(new AnnotationTypeFilter(annotationType)); typeFilters.add(new AnnotationTypeFilter(annotationType));
break; }
case ASSIGNABLE_TYPE: case ASSIGNABLE_TYPE -> typeFilters.add(new AssignableTypeFilter(filterClass));
typeFilters.add(new AssignableTypeFilter(filterClass)); case CUSTOM -> {
break;
case CUSTOM:
Assert.isAssignable(TypeFilter.class, filterClass, Assert.isAssignable(TypeFilter.class, filterClass,
"@ComponentScan CUSTOM type filter requires a TypeFilter implementation"); "@ComponentScan CUSTOM type filter requires a TypeFilter implementation");
TypeFilter filter = ParserStrategyUtils.instantiateClass(filterClass, TypeFilter.class, TypeFilter filter = ParserStrategyUtils.instantiateClass(filterClass, TypeFilter.class,
environment, resourceLoader, registry); environment, resourceLoader, registry);
typeFilters.add(filter); typeFilters.add(filter);
break; }
default: default -> throw new IllegalArgumentException(
throw new IllegalArgumentException("Filter type not supported with Class value: " + filterType); "Filter type not supported with Class value: " + filterType);
} }
} }
for (String expression : filterAttributes.getStringArray("pattern")) { for (String expression : filterAttributes.getStringArray("pattern")) {
switch (filterType) { switch (filterType) {
case ASPECTJ: case ASPECTJ -> typeFilters.add(new AspectJTypeFilter(expression, resourceLoader.getClassLoader()));
typeFilters.add(new AspectJTypeFilter(expression, resourceLoader.getClassLoader())); case REGEX -> typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression)));
break; default -> throw new IllegalArgumentException(
case REGEX: "Filter type not supported with String pattern: " + filterType);
typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression)));
break;
default:
throw new IllegalArgumentException("Filter type not supported with String pattern: " + filterType);
} }
} }

10
spring-context/src/main/java/org/springframework/format/datetime/standard/DateTimeFormatterRegistrar.java

@ -209,11 +209,11 @@ public class DateTimeFormatterRegistrar implements FormatterRegistrar {
} }
private DateTimeFormatter getFallbackFormatter(Type type) { private DateTimeFormatter getFallbackFormatter(Type type) {
switch (type) { return switch (type) {
case DATE: return DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT); case DATE -> DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
case TIME: return DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT); case TIME -> DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
default: return DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT); case DATE_TIME -> DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
} };
} }
} }

16
spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncConfigurationSelector.java

@ -18,7 +18,7 @@ package org.springframework.scheduling.annotation;
import org.springframework.context.annotation.AdviceMode; import org.springframework.context.annotation.AdviceMode;
import org.springframework.context.annotation.AdviceModeImportSelector; import org.springframework.context.annotation.AdviceModeImportSelector;
import org.springframework.lang.Nullable; import org.springframework.lang.NonNull;
/** /**
* Selects which implementation of {@link AbstractAsyncConfiguration} should * Selects which implementation of {@link AbstractAsyncConfiguration} should
@ -43,16 +43,12 @@ public class AsyncConfigurationSelector extends AdviceModeImportSelector<EnableA
* respectively. * respectively.
*/ */
@Override @Override
@Nullable @NonNull
public String[] selectImports(AdviceMode adviceMode) { public String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) { return switch (adviceMode) {
case PROXY: case PROXY -> new String[]{ProxyAsyncConfiguration.class.getName()};
return new String[] {ProxyAsyncConfiguration.class.getName()}; case ASPECTJ -> new String[]{ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME};
case ASPECTJ: };
return new String[] {ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME};
default:
return null;
}
} }
} }

23
spring-core/src/main/java/org/springframework/asm/TypePath.java

@ -163,22 +163,13 @@ public final class TypePath {
int length = getLength(); int length = getLength();
StringBuilder result = new StringBuilder(length * 2); StringBuilder result = new StringBuilder(length * 2);
for (int i = 0; i < length; ++i) { for (int i = 0; i < length; ++i) {
switch (getStep(i)) { switch (getStep(i)) {
case ARRAY_ELEMENT: case ARRAY_ELEMENT -> result.append('[');
result.append('['); case INNER_TYPE -> result.append('.');
break; case WILDCARD_BOUND -> result.append('*');
case INNER_TYPE: case TYPE_ARGUMENT -> result.append(getStepArgument(i)).append(';');
result.append('.'); default -> throw new AssertionError();
break; }
case WILDCARD_BOUND:
result.append('*');
break;
case TYPE_ARGUMENT:
result.append(getStepArgument(i)).append(';');
break;
default:
throw new AssertionError();
}
} }
return result.toString(); return result.toString();
} }

41
spring-core/src/main/java/org/springframework/core/annotation/AnnotationsScanner.java

@ -95,19 +95,13 @@ abstract class AnnotationsScanner {
private static <C, R> R processClass(C context, Class<?> source, private static <C, R> R processClass(C context, Class<?> source,
SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) { SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {
switch (searchStrategy) { return switch (searchStrategy) {
case DIRECT: case DIRECT -> processElement(context, source, processor);
return processElement(context, source, processor); case INHERITED_ANNOTATIONS -> processClassInheritedAnnotations(context, source, searchStrategy, processor);
case INHERITED_ANNOTATIONS: case SUPERCLASS -> processClassHierarchy(context, source, processor, false, false);
return processClassInheritedAnnotations(context, source, searchStrategy, processor); case TYPE_HIERARCHY -> processClassHierarchy(context, source, processor, true, false);
case SUPERCLASS: case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES -> processClassHierarchy(context, source, processor, true, true);
return processClassHierarchy(context, source, processor, false, false); };
case TYPE_HIERARCHY:
return processClassHierarchy(context, source, processor, true, false);
case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES:
return processClassHierarchy(context, source, processor, true, true);
}
throw new IllegalStateException("Unsupported search strategy " + searchStrategy);
} }
@Nullable @Nullable
@ -238,19 +232,14 @@ abstract class AnnotationsScanner {
private static <C, R> R processMethod(C context, Method source, private static <C, R> R processMethod(C context, Method source,
SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) { SearchStrategy searchStrategy, AnnotationsProcessor<C, R> processor) {
switch (searchStrategy) { return switch (searchStrategy) {
case DIRECT: case DIRECT, INHERITED_ANNOTATIONS -> processMethodInheritedAnnotations(context, source, processor);
case INHERITED_ANNOTATIONS: case SUPERCLASS -> processMethodHierarchy(context, new int[]{0}, source.getDeclaringClass(),
return processMethodInheritedAnnotations(context, source, processor); processor, source, false);
case SUPERCLASS: case TYPE_HIERARCHY, TYPE_HIERARCHY_AND_ENCLOSING_CLASSES -> processMethodHierarchy(context, new int[]{0},
return processMethodHierarchy(context, new int[] {0}, source.getDeclaringClass(), source.getDeclaringClass(),
processor, source, false); processor, source, true);
case TYPE_HIERARCHY: };
case TYPE_HIERARCHY_AND_ENCLOSING_CLASSES:
return processMethodHierarchy(context, new int[] {0}, source.getDeclaringClass(),
processor, source, true);
}
throw new IllegalStateException("Unsupported search strategy " + searchStrategy);
} }
@Nullable @Nullable

23
spring-core/src/main/java/org/springframework/core/env/ProfilesParser.java vendored

@ -70,25 +70,23 @@ final class ProfilesParser {
continue; continue;
} }
switch (token) { switch (token) {
case "(": case "(" -> {
Profiles contents = parseTokens(expression, tokens, Context.BRACKET); Profiles contents = parseTokens(expression, tokens, Context.BRACKET);
if (context == Context.INVERT) { if (context == Context.INVERT) {
return contents; return contents;
} }
elements.add(contents); elements.add(contents);
break; }
case "&": case "&" -> {
assertWellFormed(expression, operator == null || operator == Operator.AND); assertWellFormed(expression, operator == null || operator == Operator.AND);
operator = Operator.AND; operator = Operator.AND;
break; }
case "|": case "|" -> {
assertWellFormed(expression, operator == null || operator == Operator.OR); assertWellFormed(expression, operator == null || operator == Operator.OR);
operator = Operator.OR; operator = Operator.OR;
break; }
case "!": case "!" -> elements.add(not(parseTokens(expression, tokens, Context.INVERT)));
elements.add(not(parseTokens(expression, tokens, Context.INVERT))); case ")" -> {
break;
case ")":
Profiles merged = merge(expression, elements, operator); Profiles merged = merge(expression, elements, operator);
if (context == Context.BRACKET) { if (context == Context.BRACKET) {
return merged; return merged;
@ -96,13 +94,14 @@ final class ProfilesParser {
elements.clear(); elements.clear();
elements.add(merged); elements.add(merged);
operator = null; operator = null;
break; }
default: default -> {
Profiles value = equals(token); Profiles value = equals(token);
if (context == Context.INVERT) { if (context == Context.INVERT) {
return value; return value;
} }
elements.add(value); elements.add(value);
}
} }
} }
return merge(expression, elements, operator); return merge(expression, elements, operator);

13
spring-core/src/main/java/org/springframework/core/io/buffer/DataBufferUtils.java

@ -608,14 +608,11 @@ public abstract class DataBufferUtils {
private static NestedMatcher createMatcher(byte[] delimiter) { private static NestedMatcher createMatcher(byte[] delimiter) {
Assert.isTrue(delimiter.length > 0, "Delimiter must not be empty"); Assert.isTrue(delimiter.length > 0, "Delimiter must not be empty");
switch (delimiter.length) { return switch (delimiter.length) {
case 1: case 1 -> (delimiter[0] == 10 ? SingleByteMatcher.NEWLINE_MATCHER : new SingleByteMatcher(delimiter));
return (delimiter[0] == 10 ? SingleByteMatcher.NEWLINE_MATCHER : new SingleByteMatcher(delimiter)); case 2 -> new TwoByteMatcher(delimiter);
case 2: default -> new KnuthMorrisPrattMatcher(delimiter);
return new TwoByteMatcher(delimiter); };
default:
return new KnuthMorrisPrattMatcher(delimiter);
}
} }

28
spring-core/src/main/java/org/springframework/util/concurrent/ListenableFutureCallbackRegistry.java

@ -56,16 +56,12 @@ public class ListenableFutureCallbackRegistry<T> {
Assert.notNull(callback, "'callback' must not be null"); Assert.notNull(callback, "'callback' must not be null");
synchronized (this.mutex) { synchronized (this.mutex) {
switch (this.state) { switch (this.state) {
case NEW: case NEW -> {
this.successCallbacks.add(callback); this.successCallbacks.add(callback);
this.failureCallbacks.add(callback); this.failureCallbacks.add(callback);
break; }
case SUCCESS: case SUCCESS -> notifySuccess(callback);
notifySuccess(callback); case FAILURE -> notifyFailure(callback);
break;
case FAILURE:
notifyFailure(callback);
break;
} }
} }
} }
@ -99,12 +95,8 @@ public class ListenableFutureCallbackRegistry<T> {
Assert.notNull(callback, "'callback' must not be null"); Assert.notNull(callback, "'callback' must not be null");
synchronized (this.mutex) { synchronized (this.mutex) {
switch (this.state) { switch (this.state) {
case NEW: case NEW -> this.successCallbacks.add(callback);
this.successCallbacks.add(callback); case SUCCESS -> notifySuccess(callback);
break;
case SUCCESS:
notifySuccess(callback);
break;
} }
} }
} }
@ -118,12 +110,8 @@ public class ListenableFutureCallbackRegistry<T> {
Assert.notNull(callback, "'callback' must not be null"); Assert.notNull(callback, "'callback' must not be null");
synchronized (this.mutex) { synchronized (this.mutex) {
switch (this.state) { switch (this.state) {
case NEW: case NEW -> this.failureCallbacks.add(callback);
this.failureCallbacks.add(callback); case FAILURE -> notifyFailure(callback);
break;
case FAILURE:
notifyFailure(callback);
break;
} }
} }
} }

6
spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java

@ -287,10 +287,8 @@ public enum SpelMessage {
public String formatMessage(Object... inserts) { public String formatMessage(Object... inserts) {
StringBuilder formattedMessage = new StringBuilder(); StringBuilder formattedMessage = new StringBuilder();
formattedMessage.append("EL").append(this.code); formattedMessage.append("EL").append(this.code);
switch (this.kind) { if (this.kind == Kind.ERROR) {
case ERROR: formattedMessage.append('E');
formattedMessage.append('E');
break;
} }
formattedMessage.append(": "); formattedMessage.append(": ");
formattedMessage.append(MessageFormat.format(this.message, inserts)); formattedMessage.append(MessageFormat.format(this.message, inserts));

21
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpDivide.java

@ -115,21 +115,12 @@ public class OpDivide extends Operator {
cf.exitCompilationScope(); cf.exitCompilationScope();
CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc); CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc);
switch (targetDesc) { switch (targetDesc) {
case 'I': case 'I' -> mv.visitInsn(IDIV);
mv.visitInsn(IDIV); case 'J' -> mv.visitInsn(LDIV);
break; case 'F' -> mv.visitInsn(FDIV);
case 'J': case 'D' -> mv.visitInsn(DDIV);
mv.visitInsn(LDIV); default -> throw new IllegalStateException(
break; "Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
case 'F':
mv.visitInsn(FDIV);
break;
case 'D':
mv.visitInsn(DDIV);
break;
default:
throw new IllegalStateException(
"Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
} }
} }
cf.pushDescriptor(this.exitTypeDescriptor); cf.pushDescriptor(this.exitTypeDescriptor);

42
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpMinus.java

@ -184,40 +184,22 @@ public class OpMinus extends Operator {
cf.exitCompilationScope(); cf.exitCompilationScope();
CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc); CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc);
switch (targetDesc) { switch (targetDesc) {
case 'I': case 'I' -> mv.visitInsn(ISUB);
mv.visitInsn(ISUB); case 'J' -> mv.visitInsn(LSUB);
break; case 'F' -> mv.visitInsn(FSUB);
case 'J': case 'D' -> mv.visitInsn(DSUB);
mv.visitInsn(LSUB); default -> throw new IllegalStateException(
break; "Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
case 'F':
mv.visitInsn(FSUB);
break;
case 'D':
mv.visitInsn(DSUB);
break;
default:
throw new IllegalStateException(
"Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
} }
} }
else { else {
switch (targetDesc) { switch (targetDesc) {
case 'I': case 'I' -> mv.visitInsn(INEG);
mv.visitInsn(INEG); case 'J' -> mv.visitInsn(LNEG);
break; case 'F' -> mv.visitInsn(FNEG);
case 'J': case 'D' -> mv.visitInsn(DNEG);
mv.visitInsn(LNEG); default -> throw new IllegalStateException(
break; "Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
case 'F':
mv.visitInsn(FNEG);
break;
case 'D':
mv.visitInsn(DNEG);
break;
default:
throw new IllegalStateException(
"Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
} }
} }
cf.pushDescriptor(this.exitTypeDescriptor); cf.pushDescriptor(this.exitTypeDescriptor);

21
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpModulus.java

@ -112,21 +112,12 @@ public class OpModulus extends Operator {
cf.exitCompilationScope(); cf.exitCompilationScope();
CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc); CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc);
switch (targetDesc) { switch (targetDesc) {
case 'I': case 'I' -> mv.visitInsn(IREM);
mv.visitInsn(IREM); case 'J' -> mv.visitInsn(LREM);
break; case 'F' -> mv.visitInsn(FREM);
case 'J': case 'D' -> mv.visitInsn(DREM);
mv.visitInsn(LREM); default -> throw new IllegalStateException(
break; "Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
case 'F':
mv.visitInsn(FREM);
break;
case 'D':
mv.visitInsn(DREM);
break;
default:
throw new IllegalStateException(
"Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
} }
} }
cf.pushDescriptor(this.exitTypeDescriptor); cf.pushDescriptor(this.exitTypeDescriptor);

21
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpMultiply.java

@ -140,21 +140,12 @@ public class OpMultiply extends Operator {
cf.exitCompilationScope(); cf.exitCompilationScope();
CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc); CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc);
switch (targetDesc) { switch (targetDesc) {
case 'I': case 'I' -> mv.visitInsn(IMUL);
mv.visitInsn(IMUL); case 'J' -> mv.visitInsn(LMUL);
break; case 'F' -> mv.visitInsn(FMUL);
case 'J': case 'D' -> mv.visitInsn(DMUL);
mv.visitInsn(LMUL); default -> throw new IllegalStateException(
break; "Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
case 'F':
mv.visitInsn(FMUL);
break;
case 'D':
mv.visitInsn(DMUL);
break;
default:
throw new IllegalStateException(
"Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
} }
} }
cf.pushDescriptor(this.exitTypeDescriptor); cf.pushDescriptor(this.exitTypeDescriptor);

21
spring-expression/src/main/java/org/springframework/expression/spel/ast/OpPlus.java

@ -226,21 +226,12 @@ public class OpPlus extends Operator {
cf.exitCompilationScope(); cf.exitCompilationScope();
CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc); CodeFlow.insertNumericUnboxOrPrimitiveTypeCoercion(mv, rightDesc, targetDesc);
switch (targetDesc) { switch (targetDesc) {
case 'I': case 'I' -> mv.visitInsn(IADD);
mv.visitInsn(IADD); case 'J' -> mv.visitInsn(LADD);
break; case 'F' -> mv.visitInsn(FADD);
case 'J': case 'D' -> mv.visitInsn(DADD);
mv.visitInsn(LADD); default -> throw new IllegalStateException(
break; "Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
case 'F':
mv.visitInsn(FADD);
break;
case 'D':
mv.visitInsn(DADD);
break;
default:
throw new IllegalStateException(
"Unrecognized exit type descriptor: '" + this.exitTypeDescriptor + "'");
} }
} }
} }

12
spring-expression/src/main/java/org/springframework/expression/spel/ast/Selection.java

@ -209,12 +209,12 @@ public class Selection extends SpelNodeImpl {
} }
private String prefix() { private String prefix() {
switch (this.variant) { return switch (this.variant) {
case ALL: return "?["; case ALL -> "?[";
case FIRST: return "^["; case FIRST -> "^[";
case LAST: return "$["; case LAST -> "$[";
} default -> "";
return ""; };
} }
} }

29
spring-jcl/src/main/java/org/apache/commons/logging/LogAdapter.java

@ -84,22 +84,19 @@ final class LogAdapter {
* @param name the logger name * @param name the logger name
*/ */
public static Log createLog(String name) { public static Log createLog(String name) {
switch (logApi) { return switch (logApi) {
case LOG4J: case LOG4J -> Log4jAdapter.createLog(name);
return Log4jAdapter.createLog(name); case SLF4J_LAL -> Slf4jAdapter.createLocationAwareLog(name);
case SLF4J_LAL: case SLF4J -> Slf4jAdapter.createLog(name);
return Slf4jAdapter.createLocationAwareLog(name); default ->
case SLF4J: // Defensively use lazy-initializing adapter class here as well since the
return Slf4jAdapter.createLog(name); // java.logging module is not present by default on JDK 9. We are requiring
default: // its presence if neither Log4j nor SLF4J is available; however, in the
// Defensively use lazy-initializing adapter class here as well since the // case of Log4j or SLF4J, we are trying to prevent early initialization
// java.logging module is not present by default on JDK 9. We are requiring // of the JavaUtilLog adapter - e.g. by a JVM in debug mode - when eagerly
// its presence if neither Log4j nor SLF4J is available; however, in the // trying to parse the bytecode for all the cases of this switch clause.
// case of Log4j or SLF4J, we are trying to prevent early initialization JavaUtilAdapter.createLog(name);
// of the JavaUtilLog adapter - e.g. by a JVM in debug mode - when eagerly };
// trying to parse the bytecode for all the cases of this switch clause.
return JavaUtilAdapter.createLog(name);
}
} }
private static boolean isPresent(String className) { private static boolean isPresent(String className) {

13
spring-jms/src/main/java/org/springframework/jms/support/converter/MarshallingMessageConverter.java

@ -155,14 +155,11 @@ public class MarshallingMessageConverter implements MessageConverter, Initializi
public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException { public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
Assert.state(this.marshaller != null, "No Marshaller set"); Assert.state(this.marshaller != null, "No Marshaller set");
try { try {
switch (this.targetType) { return switch (this.targetType) {
case TEXT: case TEXT -> marshalToTextMessage(object, session, this.marshaller);
return marshalToTextMessage(object, session, this.marshaller); case BYTES -> marshalToBytesMessage(object, session, this.marshaller);
case BYTES: default -> marshalToMessage(object, session, this.marshaller, this.targetType);
return marshalToBytesMessage(object, session, this.marshaller); };
default:
return marshalToMessage(object, session, this.marshaller, this.targetType);
}
} }
catch (XmlMappingException | IOException ex) { catch (XmlMappingException | IOException ex) {
throw new MessageConversionException("Could not marshal [" + object + "]", ex); throw new MessageConversionException("Could not marshal [" + object + "]", ex);

15
spring-messaging/src/jmh/java/org/springframework/messaging/simp/broker/DefaultSubscriptionRegistryBenchmark.java

@ -145,18 +145,15 @@ public class DefaultSubscriptionRegistryBenchmark {
@Setup(Level.Trial) @Setup(Level.Trial)
public void doSetup(ServerState serverState) { public void doSetup(ServerState serverState) {
switch (this.contention) { switch (this.contention) {
case "noSubscribers": case "noSubscribers" -> {
this.destination = "someDestination_withNoSubscribers_" + serverState.uniqueIdGenerator.incrementAndGet(); this.destination = "someDestination_withNoSubscribers_" + serverState.uniqueIdGenerator.incrementAndGet();
break; }
case "sameDestination": case "sameDestination" -> this.destination = serverState.destinationIds[0];
this.destination = serverState.destinationIds[0]; case "none" -> {
break;
case "none":
int uniqueNumber = serverState.uniqueIdGenerator.getAndIncrement(); int uniqueNumber = serverState.uniqueIdGenerator.getAndIncrement();
this.destination = serverState.destinationIds[uniqueNumber % serverState.destinationIds.length]; this.destination = serverState.destinationIds[uniqueNumber % serverState.destinationIds.length];
break; }
default: default -> throw new IllegalStateException();
throw new IllegalStateException();
} }
} }
} }

24
spring-messaging/src/main/java/org/springframework/messaging/rsocket/annotation/support/RSocketFrameTypeMessageCondition.java

@ -192,20 +192,16 @@ public class RSocketFrameTypeMessageCondition extends AbstractMessageCondition<R
* @since 5.2.2 * @since 5.2.2
*/ */
public static RSocketFrameTypeMessageCondition getCondition(int cardinalityIn, int cardinalityOut) { public static RSocketFrameTypeMessageCondition getCondition(int cardinalityIn, int cardinalityOut) {
switch (cardinalityIn) { return switch (cardinalityIn) {
case 0: case 0, 1 -> switch (cardinalityOut) {
case 1: case 0 -> REQUEST_FNF_OR_RESPONSE_CONDITION;
switch (cardinalityOut) { case 1 -> REQUEST_RESPONSE_CONDITION;
case 0: return REQUEST_FNF_OR_RESPONSE_CONDITION; case 2 -> REQUEST_STREAM_CONDITION;
case 1: return REQUEST_RESPONSE_CONDITION; default -> throw new IllegalStateException("Invalid cardinality: " + cardinalityOut);
case 2: return REQUEST_STREAM_CONDITION; };
default: throw new IllegalStateException("Invalid cardinality: " + cardinalityOut); case 2 -> REQUEST_CHANNEL_CONDITION;
} default -> throw new IllegalStateException("Invalid cardinality: " + cardinalityIn);
case 2: };
return REQUEST_CHANNEL_CONDITION;
default:
throw new IllegalStateException("Invalid cardinality: " + cardinalityIn);
}
} }
} }

9
spring-orm/src/main/java/org/springframework/orm/jpa/SharedEntityManagerCreator.java

@ -266,13 +266,14 @@ public abstract class SharedEntityManagerCreator {
this.targetFactory, this.properties, this.synchronizedWithTransaction); this.targetFactory, this.properties, this.synchronizedWithTransaction);
switch (method.getName()) { switch (method.getName()) {
case "getTargetEntityManager": case "getTargetEntityManager" -> {
// Handle EntityManagerProxy interface. // Handle EntityManagerProxy interface.
if (target == null) { if (target == null) {
throw new IllegalStateException("No transactional EntityManager available"); throw new IllegalStateException("No transactional EntityManager available");
} }
return target; return target;
case "unwrap": }
case "unwrap" -> {
Class<?> targetClass = (Class<?>) args[0]; Class<?> targetClass = (Class<?>) args[0];
if (targetClass == null) { if (targetClass == null) {
return (target != null ? target : proxy); return (target != null ? target : proxy);
@ -281,8 +282,8 @@ public abstract class SharedEntityManagerCreator {
if (target == null) { if (target == null) {
throw new IllegalStateException("No transactional EntityManager available"); throw new IllegalStateException("No transactional EntityManager available");
} }
// Still perform unwrap call on target EntityManager. }
break; // Still perform unwrap call on target EntityManager.
} }
if (transactionRequiringMethods.contains(method.getName())) { if (transactionRequiringMethods.contains(method.getName())) {

26
spring-orm/src/main/java/org/springframework/orm/jpa/vendor/EclipseLinkJpaVendorAdapter.java vendored

@ -94,19 +94,19 @@ public class EclipseLinkJpaVendorAdapter extends AbstractJpaVendorAdapter {
*/ */
@Nullable @Nullable
protected String determineTargetDatabaseName(Database database) { protected String determineTargetDatabaseName(Database database) {
switch (database) { return switch (database) {
case DB2: return TargetDatabase.DB2; case DB2 -> TargetDatabase.DB2;
case DERBY: return TargetDatabase.Derby; case DERBY -> TargetDatabase.Derby;
case HANA: return TargetDatabase.HANA; case HANA -> TargetDatabase.HANA;
case HSQL: return TargetDatabase.HSQL; case HSQL -> TargetDatabase.HSQL;
case INFORMIX: return TargetDatabase.Informix; case INFORMIX -> TargetDatabase.Informix;
case MYSQL: return TargetDatabase.MySQL; case MYSQL -> TargetDatabase.MySQL;
case ORACLE: return TargetDatabase.Oracle; case ORACLE -> TargetDatabase.Oracle;
case POSTGRESQL: return TargetDatabase.PostgreSQL; case POSTGRESQL -> TargetDatabase.PostgreSQL;
case SQL_SERVER: return TargetDatabase.SQLServer; case SQL_SERVER -> TargetDatabase.SQLServer;
case SYBASE: return TargetDatabase.Sybase; case SYBASE -> TargetDatabase.Sybase;
default: return null; default -> null;
} };
} }
@Override @Override

28
spring-orm/src/main/java/org/springframework/orm/jpa/vendor/HibernateJpaVendorAdapter.java vendored

@ -169,20 +169,20 @@ public class HibernateJpaVendorAdapter extends AbstractJpaVendorAdapter {
*/ */
@Nullable @Nullable
protected Class<?> determineDatabaseDialectClass(Database database) { protected Class<?> determineDatabaseDialectClass(Database database) {
switch (database) { return switch (database) {
case DB2: return DB2Dialect.class; case DB2 -> DB2Dialect.class;
case DERBY: return DerbyTenSevenDialect.class; case DERBY -> DerbyTenSevenDialect.class;
case H2: return H2Dialect.class; case H2 -> H2Dialect.class;
case HANA: return HANAColumnStoreDialect.class; case HANA -> HANAColumnStoreDialect.class;
case HSQL: return HSQLDialect.class; case HSQL -> HSQLDialect.class;
case INFORMIX: return Informix10Dialect.class; case INFORMIX -> Informix10Dialect.class;
case MYSQL: return MySQL57Dialect.class; case MYSQL -> MySQL57Dialect.class;
case ORACLE: return Oracle12cDialect.class; case ORACLE -> Oracle12cDialect.class;
case POSTGRESQL: return PostgreSQL95Dialect.class; case POSTGRESQL -> PostgreSQL95Dialect.class;
case SQL_SERVER: return SQLServer2012Dialect.class; case SQL_SERVER -> SQLServer2012Dialect.class;
case SYBASE: return SybaseDialect.class; case SYBASE -> SybaseDialect.class;
default: return null; default -> null;
} };
} }
@Override @Override

18
spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/R2dbcTransactionManager.java

@ -415,17 +415,13 @@ public class R2dbcTransactionManager extends AbstractReactiveTransactionManager
*/ */
@Nullable @Nullable
protected IsolationLevel resolveIsolationLevel(int isolationLevel) { protected IsolationLevel resolveIsolationLevel(int isolationLevel) {
switch (isolationLevel) { return switch (isolationLevel) {
case TransactionDefinition.ISOLATION_READ_COMMITTED: case TransactionDefinition.ISOLATION_READ_COMMITTED -> IsolationLevel.READ_COMMITTED;
return IsolationLevel.READ_COMMITTED; case TransactionDefinition.ISOLATION_READ_UNCOMMITTED -> IsolationLevel.READ_UNCOMMITTED;
case TransactionDefinition.ISOLATION_READ_UNCOMMITTED: case TransactionDefinition.ISOLATION_REPEATABLE_READ -> IsolationLevel.REPEATABLE_READ;
return IsolationLevel.READ_UNCOMMITTED; case TransactionDefinition.ISOLATION_SERIALIZABLE -> IsolationLevel.SERIALIZABLE;
case TransactionDefinition.ISOLATION_REPEATABLE_READ: default -> null;
return IsolationLevel.REPEATABLE_READ; };
case TransactionDefinition.ISOLATION_SERIALIZABLE:
return IsolationLevel.SERIALIZABLE;
}
return null;
} }
/** /**

38
spring-test/src/main/java/org/springframework/mock/web/MockPageContext.java

@ -154,20 +154,11 @@ public class MockPageContext extends PageContext {
public void setAttribute(String name, @Nullable Object value, int scope) { public void setAttribute(String name, @Nullable Object value, int scope) {
Assert.notNull(name, "Attribute name must not be null"); Assert.notNull(name, "Attribute name must not be null");
switch (scope) { switch (scope) {
case PAGE_SCOPE: case PAGE_SCOPE -> setAttribute(name, value);
setAttribute(name, value); case REQUEST_SCOPE -> this.request.setAttribute(name, value);
break; case SESSION_SCOPE -> this.request.getSession().setAttribute(name, value);
case REQUEST_SCOPE: case APPLICATION_SCOPE -> this.servletContext.setAttribute(name, value);
this.request.setAttribute(name, value); default -> throw new IllegalArgumentException("Invalid scope: " + scope);
break;
case SESSION_SCOPE:
this.request.getSession().setAttribute(name, value);
break;
case APPLICATION_SCOPE:
this.servletContext.setAttribute(name, value);
break;
default:
throw new IllegalArgumentException("Invalid scope: " + scope);
} }
} }
@ -226,20 +217,11 @@ public class MockPageContext extends PageContext {
public void removeAttribute(String name, int scope) { public void removeAttribute(String name, int scope) {
Assert.notNull(name, "Attribute name must not be null"); Assert.notNull(name, "Attribute name must not be null");
switch (scope) { switch (scope) {
case PAGE_SCOPE: case PAGE_SCOPE -> this.attributes.remove(name);
this.attributes.remove(name); case REQUEST_SCOPE -> this.request.removeAttribute(name);
break; case SESSION_SCOPE -> this.request.getSession().removeAttribute(name);
case REQUEST_SCOPE: case APPLICATION_SCOPE -> this.servletContext.removeAttribute(name);
this.request.removeAttribute(name); default -> throw new IllegalArgumentException("Invalid scope: " + scope);
break;
case SESSION_SCOPE:
this.request.getSession().removeAttribute(name);
break;
case APPLICATION_SCOPE:
this.servletContext.removeAttribute(name);
break;
default:
throw new IllegalArgumentException("Invalid scope: " + scope);
} }
} }

16
spring-tx/src/main/java/org/springframework/transaction/HeuristicCompletionException.java

@ -49,16 +49,12 @@ public class HeuristicCompletionException extends TransactionException {
public static String getStateString(int state) { public static String getStateString(int state) {
switch (state) { return switch (state) {
case STATE_COMMITTED: case STATE_COMMITTED -> "committed";
return "committed"; case STATE_ROLLED_BACK -> "rolled back";
case STATE_ROLLED_BACK: case STATE_MIXED -> "mixed";
return "rolled back"; default -> "unknown";
case STATE_MIXED: };
return "mixed";
default:
return "unknown";
}
} }

11
spring-tx/src/main/java/org/springframework/transaction/jta/SpringJtaSynchronizationAdapter.java

@ -171,14 +171,9 @@ public class SpringJtaSynchronizationAdapter implements Synchronization {
} }
// Call afterCompletion with the appropriate status indication. // Call afterCompletion with the appropriate status indication.
switch (status) { switch (status) {
case Status.STATUS_COMMITTED: case Status.STATUS_COMMITTED -> this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_COMMITTED);
this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_COMMITTED); case Status.STATUS_ROLLEDBACK -> this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
break; default -> this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
case Status.STATUS_ROLLEDBACK:
this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
break;
default:
this.springSynchronization.afterCompletion(TransactionSynchronization.STATUS_UNKNOWN);
} }
} }

16
spring-web/src/main/java/org/springframework/http/codec/json/Jackson2Tokenizer.java

@ -154,18 +154,10 @@ final class Jackson2Tokenizer {
private void updateDepth(JsonToken token) { private void updateDepth(JsonToken token) {
switch (token) { switch (token) {
case START_OBJECT: case START_OBJECT -> this.objectDepth++;
this.objectDepth++; case END_OBJECT -> this.objectDepth--;
break; case START_ARRAY -> this.arrayDepth++;
case END_OBJECT: case END_ARRAY -> this.arrayDepth--;
this.objectDepth--;
break;
case START_ARRAY:
this.arrayDepth++;
break;
case END_ARRAY:
this.arrayDepth--;
break;
} }
} }

9
spring-web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java

@ -164,12 +164,9 @@ public class DefaultResponseErrorHandler implements ResponseErrorHandler {
String message = getErrorMessage(statusCode.value(), statusText, body, charset); String message = getErrorMessage(statusCode.value(), statusText, body, charset);
switch (statusCode.series()) { switch (statusCode.series()) {
case CLIENT_ERROR: case CLIENT_ERROR -> throw HttpClientErrorException.create(message, statusCode, statusText, headers, body, charset);
throw HttpClientErrorException.create(message, statusCode, statusText, headers, body, charset); case SERVER_ERROR -> throw HttpServerErrorException.create(message, statusCode, statusText, headers, body, charset);
case SERVER_ERROR: default -> throw new UnknownHttpStatusCodeException(message, statusCode.value(), statusText, headers, body, charset);
throw HttpServerErrorException.create(message, statusCode, statusText, headers, body, charset);
default:
throw new UnknownHttpStatusCodeException(message, statusCode.value(), statusText, headers, body, charset);
} }
} }

38
spring-web/src/testFixtures/java/org/springframework/web/testfixture/servlet/MockPageContext.java

@ -154,20 +154,11 @@ public class MockPageContext extends PageContext {
public void setAttribute(String name, @Nullable Object value, int scope) { public void setAttribute(String name, @Nullable Object value, int scope) {
Assert.notNull(name, "Attribute name must not be null"); Assert.notNull(name, "Attribute name must not be null");
switch (scope) { switch (scope) {
case PAGE_SCOPE: case PAGE_SCOPE -> setAttribute(name, value);
setAttribute(name, value); case REQUEST_SCOPE -> this.request.setAttribute(name, value);
break; case SESSION_SCOPE -> this.request.getSession().setAttribute(name, value);
case REQUEST_SCOPE: case APPLICATION_SCOPE -> this.servletContext.setAttribute(name, value);
this.request.setAttribute(name, value); default -> throw new IllegalArgumentException("Invalid scope: " + scope);
break;
case SESSION_SCOPE:
this.request.getSession().setAttribute(name, value);
break;
case APPLICATION_SCOPE:
this.servletContext.setAttribute(name, value);
break;
default:
throw new IllegalArgumentException("Invalid scope: " + scope);
} }
} }
@ -226,20 +217,11 @@ public class MockPageContext extends PageContext {
public void removeAttribute(String name, int scope) { public void removeAttribute(String name, int scope) {
Assert.notNull(name, "Attribute name must not be null"); Assert.notNull(name, "Attribute name must not be null");
switch (scope) { switch (scope) {
case PAGE_SCOPE: case PAGE_SCOPE -> this.attributes.remove(name);
this.attributes.remove(name); case REQUEST_SCOPE -> this.request.removeAttribute(name);
break; case SESSION_SCOPE -> this.request.getSession().removeAttribute(name);
case REQUEST_SCOPE: case APPLICATION_SCOPE -> this.servletContext.removeAttribute(name);
this.request.removeAttribute(name); default -> throw new IllegalArgumentException("Invalid scope: " + scope);
break;
case SESSION_SCOPE:
this.request.getSession().removeAttribute(name);
break;
case APPLICATION_SCOPE:
this.servletContext.removeAttribute(name);
break;
default:
throw new IllegalArgumentException("Invalid scope: " + scope);
} }
} }

19
spring-webmvc/src/main/java/org/springframework/web/servlet/config/ViewControllerBeanDefinitionParser.java

@ -82,24 +82,23 @@ class ViewControllerBeanDefinitionParser implements BeanDefinitionParser {
String name = element.getLocalName(); String name = element.getLocalName();
switch (name) { switch (name) {
case "view-controller": case "view-controller" -> {
if (element.hasAttribute("view-name")) { if (element.hasAttribute("view-name")) {
controller.getPropertyValues().add("viewName", element.getAttribute("view-name")); controller.getPropertyValues().add("viewName", element.getAttribute("view-name"));
} }
if (statusCode != null) { if (statusCode != null) {
controller.getPropertyValues().add("statusCode", statusCode); controller.getPropertyValues().add("statusCode", statusCode);
} }
break; }
case "redirect-view-controller": case "redirect-view-controller" -> controller.getPropertyValues()
controller.getPropertyValues().add("view", getRedirectView(element, statusCode, source)); .add("view", getRedirectView(element, statusCode, source));
break; case "status-controller" -> {
case "status-controller":
controller.getPropertyValues().add("statusCode", statusCode); controller.getPropertyValues().add("statusCode", statusCode);
controller.getPropertyValues().add("statusOnly", true); controller.getPropertyValues().add("statusOnly", true);
break; }
default: default ->
// Should never happen... // Should never happen...
throw new IllegalStateException("Unexpected tag name: " + name); throw new IllegalStateException("Unexpected tag name: " + name);
} }
Map<String, BeanDefinition> urlMap = (Map<String, BeanDefinition>) hm.getPropertyValues().get("urlMap"); Map<String, BeanDefinition> urlMap = (Map<String, BeanDefinition>) hm.getPropertyValues().get("urlMap");

11
spring-websocket/src/main/java/org/springframework/web/socket/handler/ConcurrentWebSocketSessionDecorator.java

@ -210,12 +210,12 @@ public class ConcurrentWebSocketSessionDecorator extends WebSocketSessionDecorat
} }
else if (getBufferSize() > getBufferSizeLimit()) { else if (getBufferSize() > getBufferSizeLimit()) {
switch (this.overflowStrategy) { switch (this.overflowStrategy) {
case TERMINATE: case TERMINATE -> {
String format = "Buffer size %d bytes for session '%s' exceeds the allowed limit %d"; String format = "Buffer size %d bytes for session '%s' exceeds the allowed limit %d";
String reason = String.format(format, getBufferSize(), getId(), getBufferSizeLimit()); String reason = String.format(format, getBufferSize(), getId(), getBufferSizeLimit());
limitExceeded(reason); limitExceeded(reason);
break; }
case DROP: case DROP -> {
int i = 0; int i = 0;
while (getBufferSize() > getBufferSizeLimit()) { while (getBufferSize() > getBufferSizeLimit()) {
WebSocketMessage<?> message = this.buffer.poll(); WebSocketMessage<?> message = this.buffer.poll();
@ -228,10 +228,7 @@ public class ConcurrentWebSocketSessionDecorator extends WebSocketSessionDecorat
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Dropped " + i + " messages, buffer size: " + getBufferSize()); logger.debug("Dropped " + i + " messages, buffer size: " + getBufferSize());
} }
break; }
default:
// Should never happen..
throw new IllegalStateException("Unexpected OverflowStrategy: " + this.overflowStrategy);
} }
} }
} }

19
spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractSockJsSession.java

@ -407,17 +407,14 @@ public abstract class AbstractSockJsSession implements SockJsSession {
} }
private static List<String> getUndelivered(String[] messages, int i) { private static List<String> getUndelivered(String[] messages, int i) {
switch (messages.length - i) { return switch (messages.length - i) {
case 0: case 0 -> Collections.emptyList();
return Collections.emptyList(); case 1 -> (messages[i].trim().isEmpty() ?
case 1: Collections.<String>emptyList() : Collections.singletonList(messages[i]));
return (messages[i].trim().isEmpty() ? default -> Arrays.stream(Arrays.copyOfRange(messages, i, messages.length))
Collections.emptyList() : Collections.singletonList(messages[i])); .filter(message -> !message.trim().isEmpty())
default: .collect(Collectors.toList());
return Arrays.stream(Arrays.copyOfRange(messages, i, messages.length)) };
.filter(message -> !message.trim().isEmpty())
.collect(Collectors.toList());
}
} }
/** /**

Loading…
Cancel
Save