Use Assert.state() where appropriate

This commit is contained in:
Sam Brannen 2022-11-14 17:36:11 +01:00
parent 2aa78889d2
commit abf3400c07
30 changed files with 80 additions and 82 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2017 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -69,7 +69,7 @@ public abstract class AbstractServiceLoaderBasedFactoryBean extends AbstractFact
*/ */
@Override @Override
protected Object createInstance() { protected Object createInstance() {
Assert.notNull(getServiceType(), "Property 'serviceType' is required"); Assert.state(getServiceType() != null, "Property 'serviceType' is required");
return getObjectToExpose(ServiceLoader.load(getServiceType(), this.beanClassLoader)); return getObjectToExpose(ServiceLoader.load(getServiceType(), this.beanClassLoader));
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -166,7 +166,7 @@ public class DefaultJCacheOperationSource extends AnnotationJCacheOperationSourc
public void afterSingletonsInstantiated() { public void afterSingletonsInstantiated() {
// Make sure that the cache resolver is initialized. An exception cache resolver is only // Make sure that the cache resolver is initialized. An exception cache resolver is only
// required if the exceptionCacheName attribute is set on an operation. // required if the exceptionCacheName attribute is set on an operation.
Assert.notNull(getDefaultCacheResolver(), "Cache resolver should have been initialized"); Assert.state(getDefaultCacheResolver() != null, "Cache resolver should have been initialized");
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -44,7 +44,7 @@ public class ProxyAsyncConfiguration extends AbstractAsyncConfiguration {
@Bean(name = TaskManagementConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME) @Bean(name = TaskManagementConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE) @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public AsyncAnnotationBeanPostProcessor asyncAdvisor() { public AsyncAnnotationBeanPostProcessor asyncAdvisor() {
Assert.notNull(this.enableAsync, "@EnableAsync annotation metadata was not injected"); Assert.state(this.enableAsync != null, "@EnableAsync annotation metadata was not injected");
AsyncAnnotationBeanPostProcessor bpp = new AsyncAnnotationBeanPostProcessor(); AsyncAnnotationBeanPostProcessor bpp = new AsyncAnnotationBeanPostProcessor();
bpp.configure(this.executor, this.exceptionHandler); bpp.configure(this.executor, this.exceptionHandler);
Class<? extends Annotation> customAsyncAnnotation = this.enableAsync.getClass("annotation"); Class<? extends Annotation> customAsyncAnnotation = this.enableAsync.getClass("annotation");

View File

@ -378,43 +378,43 @@ public class LocalValidatorFactoryBean extends SpringValidatorAdapter
@Override @Override
public Validator getValidator() { public Validator getValidator() {
Assert.notNull(this.validatorFactory, "No target ValidatorFactory set"); Assert.state(this.validatorFactory != null, "No target ValidatorFactory set");
return this.validatorFactory.getValidator(); return this.validatorFactory.getValidator();
} }
@Override @Override
public ValidatorContext usingContext() { public ValidatorContext usingContext() {
Assert.notNull(this.validatorFactory, "No target ValidatorFactory set"); Assert.state(this.validatorFactory != null, "No target ValidatorFactory set");
return this.validatorFactory.usingContext(); return this.validatorFactory.usingContext();
} }
@Override @Override
public MessageInterpolator getMessageInterpolator() { public MessageInterpolator getMessageInterpolator() {
Assert.notNull(this.validatorFactory, "No target ValidatorFactory set"); Assert.state(this.validatorFactory != null, "No target ValidatorFactory set");
return this.validatorFactory.getMessageInterpolator(); return this.validatorFactory.getMessageInterpolator();
} }
@Override @Override
public TraversableResolver getTraversableResolver() { public TraversableResolver getTraversableResolver() {
Assert.notNull(this.validatorFactory, "No target ValidatorFactory set"); Assert.state(this.validatorFactory != null, "No target ValidatorFactory set");
return this.validatorFactory.getTraversableResolver(); return this.validatorFactory.getTraversableResolver();
} }
@Override @Override
public ConstraintValidatorFactory getConstraintValidatorFactory() { public ConstraintValidatorFactory getConstraintValidatorFactory() {
Assert.notNull(this.validatorFactory, "No target ValidatorFactory set"); Assert.state(this.validatorFactory != null, "No target ValidatorFactory set");
return this.validatorFactory.getConstraintValidatorFactory(); return this.validatorFactory.getConstraintValidatorFactory();
} }
@Override @Override
public ParameterNameProvider getParameterNameProvider() { public ParameterNameProvider getParameterNameProvider() {
Assert.notNull(this.validatorFactory, "No target ValidatorFactory set"); Assert.state(this.validatorFactory != null, "No target ValidatorFactory set");
return this.validatorFactory.getParameterNameProvider(); return this.validatorFactory.getParameterNameProvider();
} }
@Override @Override
public ClockProvider getClockProvider() { public ClockProvider getClockProvider() {
Assert.notNull(this.validatorFactory, "No target ValidatorFactory set"); Assert.state(this.validatorFactory != null, "No target ValidatorFactory set");
return this.validatorFactory.getClockProvider(); return this.validatorFactory.getClockProvider();
} }

View File

@ -98,7 +98,7 @@ public final class RecordedInvocation {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public <T> T getInstance() { public <T> T getInstance() {
Assert.notNull(this.instance, "Cannot resolve 'this' for static invocations"); Assert.state(this.instance != null, "Cannot resolve 'this' for static invocations");
return (T) this.instance; return (T) this.instance;
} }
@ -108,7 +108,7 @@ public final class RecordedInvocation {
* @throws IllegalStateException in case of static invocations (there is no {@code this}) * @throws IllegalStateException in case of static invocations (there is no {@code this})
*/ */
public TypeReference getInstanceTypeReference() { public TypeReference getInstanceTypeReference() {
Assert.notNull(this.instance, "Cannot resolve 'this' for static invocations"); Assert.state(this.instance != null, "Cannot resolve 'this' for static invocations");
return TypeReference.of(this.instance.getClass()); return TypeReference.of(this.instance.getClass());
} }

View File

@ -49,7 +49,7 @@ public final class RuntimeHintsRecorder {
*/ */
public synchronized static RuntimeHintsInvocations record(Runnable action) { public synchronized static RuntimeHintsInvocations record(Runnable action) {
Assert.notNull(action, "Runnable action must not be null"); Assert.notNull(action, "Runnable action must not be null");
Assert.isTrue(RuntimeHintsAgent.isLoaded(), "RuntimeHintsAgent should be loaded in the current JVM"); Assert.state(RuntimeHintsAgent.isLoaded(), "RuntimeHintsAgent must be loaded in the current JVM");
RuntimeHintsRecorder recorder = new RuntimeHintsRecorder(); RuntimeHintsRecorder recorder = new RuntimeHintsRecorder();
RecordedInvocationsPublisher.addListener(recorder.listener); RecordedInvocationsPublisher.addListener(recorder.listener);
try { try {

View File

@ -63,8 +63,8 @@ class RecordedInvocationTests {
@Test @Test
void staticInvocationShouldThrowWhenGetInstance() { void staticInvocationShouldThrowWhenGetInstance() {
assertThatThrownBy(staticInvocation::getInstance).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(staticInvocation::getInstance).isInstanceOf(IllegalStateException.class);
assertThatThrownBy(staticInvocation::getInstanceTypeReference).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(staticInvocation::getInstanceTypeReference).isInstanceOf(IllegalStateException.class);
} }
@Test @Test

View File

@ -42,16 +42,18 @@ public class DefaultMethodReference implements MethodReference {
@Nullable @Nullable
private final ClassName declaringClass; private final ClassName declaringClass;
public DefaultMethodReference(MethodSpec method, @Nullable ClassName declaringClass) { public DefaultMethodReference(MethodSpec method, @Nullable ClassName declaringClass) {
this.method = method; this.method = method;
this.declaringClass = declaringClass; this.declaringClass = declaringClass;
} }
@Override @Override
public CodeBlock toCodeBlock() { public CodeBlock toCodeBlock() {
String methodName = this.method.name; String methodName = this.method.name;
if (isStatic()) { if (isStatic()) {
Assert.notNull(this.declaringClass, "static method reference must define a declaring class"); Assert.state(this.declaringClass != null, "static method reference must define a declaring class");
return CodeBlock.of("$T::$L", this.declaringClass, methodName); return CodeBlock.of("$T::$L", this.declaringClass, methodName);
} }
else { else {
@ -59,12 +61,13 @@ public class DefaultMethodReference implements MethodReference {
} }
} }
@Override
public CodeBlock toInvokeCodeBlock(ArgumentCodeGenerator argumentCodeGenerator, public CodeBlock toInvokeCodeBlock(ArgumentCodeGenerator argumentCodeGenerator,
@Nullable ClassName targetClassName) { @Nullable ClassName targetClassName) {
String methodName = this.method.name; String methodName = this.method.name;
CodeBlock.Builder code = CodeBlock.builder(); CodeBlock.Builder code = CodeBlock.builder();
if (isStatic()) { if (isStatic()) {
Assert.notNull(this.declaringClass, "static method reference must define a declaring class"); Assert.state(this.declaringClass != null, "static method reference must define a declaring class");
if (isSameDeclaringClass(targetClassName)) { if (isSameDeclaringClass(targetClassName)) {
code.add("$L", methodName); code.add("$L", methodName);
} }

View File

@ -30,6 +30,7 @@ import org.springframework.lang.Nullable;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
/** /**
* Tests for {@link DefaultMethodReference}. * Tests for {@link DefaultMethodReference}.
@ -86,7 +87,7 @@ class DefaultMethodReferenceTests {
void toCodeBlockWithStaticMethodRequiresDeclaringClass() { void toCodeBlockWithStaticMethodRequiresDeclaringClass() {
MethodSpec method = createTestMethod("methodName", new TypeName[0], Modifier.STATIC); MethodSpec method = createTestMethod("methodName", new TypeName[0], Modifier.STATIC);
MethodReference methodReference = new DefaultMethodReference(method, null); MethodReference methodReference = new DefaultMethodReference(method, null);
assertThatIllegalArgumentException().isThrownBy(methodReference::toCodeBlock) assertThatIllegalStateException().isThrownBy(methodReference::toCodeBlock)
.withMessage("static method reference must define a declaring class"); .withMessage("static method reference must define a declaring class");
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -157,7 +157,7 @@ public class ConnectionHolder extends ResourceHolderSupport {
* @see #released() * @see #released()
*/ */
public Connection getConnection() { public Connection getConnection() {
Assert.notNull(this.connectionHandle, "Active Connection is required"); Assert.state(this.connectionHandle != null, "Active Connection is required");
if (this.currentConnection == null) { if (this.currentConnection == null) {
this.currentConnection = this.connectionHandle.getConnection(); this.currentConnection = this.connectionHandle.getConnection();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -136,8 +136,8 @@ public class SimpleDriverDataSource extends AbstractDriverBasedDataSource {
@Override @Override
protected Connection getConnectionFromDriver(Properties props) throws SQLException { protected Connection getConnectionFromDriver(Properties props) throws SQLException {
Driver driver = getDriver(); Driver driver = getDriver();
Assert.state(driver != null, "Driver has not been set");
String url = getUrl(); String url = getUrl();
Assert.notNull(driver, "Driver must not be null");
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("Creating new JDBC Driver Connection to [" + url + "]"); logger.debug("Creating new JDBC Driver Connection to [" + url + "]");
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -144,7 +144,7 @@ public class MarshallingMessageConverter extends AbstractMessageConverter {
@Override @Override
@Nullable @Nullable
protected Object convertFromInternal(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) { protected Object convertFromInternal(Message<?> message, Class<?> targetClass, @Nullable Object conversionHint) {
Assert.notNull(this.unmarshaller, "Property 'unmarshaller' is required"); Assert.state(this.unmarshaller != null, "Property 'unmarshaller' is required");
try { try {
Source source = getSource(message.getPayload()); Source source = getSource(message.getPayload());
Object result = this.unmarshaller.unmarshal(source); Object result = this.unmarshaller.unmarshal(source);
@ -172,7 +172,7 @@ public class MarshallingMessageConverter extends AbstractMessageConverter {
protected Object convertToInternal(Object payload, @Nullable MessageHeaders headers, protected Object convertToInternal(Object payload, @Nullable MessageHeaders headers,
@Nullable Object conversionHint) { @Nullable Object conversionHint) {
Assert.notNull(this.marshaller, "Property 'marshaller' is required"); Assert.state(this.marshaller != null, "Property 'marshaller' is required");
try { try {
if (byte[].class == getSerializedPayloadClass()) { if (byte[].class == getSerializedPayloadClass()) {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024); ByteArrayOutputStream out = new ByteArrayOutputStream(1024);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -23,7 +23,6 @@ import org.springframework.lang.Nullable;
import org.springframework.transaction.support.ResourceHolderSupport; import org.springframework.transaction.support.ResourceHolderSupport;
import org.springframework.util.Assert; import org.springframework.util.Assert;
/** /**
* Resource holder wrapping a R2DBC {@link Connection}. * Resource holder wrapping a R2DBC {@link Connection}.
* {@link R2dbcTransactionManager} binds instances of this class to the subscription, * {@link R2dbcTransactionManager} binds instances of this class to the subscription,
@ -109,7 +108,7 @@ public class ConnectionHolder extends ResourceHolderSupport {
* @see #released() * @see #released()
*/ */
public Connection getConnection() { public Connection getConnection() {
Assert.notNull(this.currentConnection, "Active Connection is required"); Assert.state(this.currentConnection != null, "Active Connection is required");
return this.currentConnection; return this.currentConnection;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -121,7 +121,7 @@ public class MarshallingHttpMessageConverter extends AbstractXmlHttpMessageConve
@Override @Override
protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) throws Exception { protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) throws Exception {
Assert.notNull(this.unmarshaller, "Property 'unmarshaller' is required"); Assert.state(this.unmarshaller != null, "Property 'unmarshaller' is required");
Object result = this.unmarshaller.unmarshal(source); Object result = this.unmarshaller.unmarshal(source);
if (!clazz.isInstance(result)) { if (!clazz.isInstance(result)) {
throw new TypeMismatchException(result, clazz); throw new TypeMismatchException(result, clazz);
@ -131,7 +131,7 @@ public class MarshallingHttpMessageConverter extends AbstractXmlHttpMessageConve
@Override @Override
protected void writeToResult(Object o, HttpHeaders headers, Result result) throws Exception { protected void writeToResult(Object o, HttpHeaders headers, Result result) throws Exception {
Assert.notNull(this.marshaller, "Property 'marshaller' is required"); Assert.state(this.marshaller != null, "Property 'marshaller' is required");
this.marshaller.marshal(o, result); this.marshaller.marshal(o, result);
} }

View File

@ -59,7 +59,7 @@ public class JettyHttpHandlerAdapter extends ServletHttpHandlerAdapter {
protected ServletServerHttpRequest createRequest(HttpServletRequest request, AsyncContext context) protected ServletServerHttpRequest createRequest(HttpServletRequest request, AsyncContext context)
throws IOException, URISyntaxException { throws IOException, URISyntaxException {
Assert.notNull(getServletPath(), "Servlet path is not initialized"); Assert.state(getServletPath() != null, "Servlet path is not initialized");
return new JettyServerHttpRequest( return new JettyServerHttpRequest(
request, context, getServletPath(), getDataBufferFactory(), getBufferSize()); request, context, getServletPath(), getDataBufferFactory(), getBufferSize());
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -200,7 +200,7 @@ public class ServletHttpHandlerAdapter implements Servlet {
protected ServletServerHttpRequest createRequest(HttpServletRequest request, AsyncContext context) protected ServletServerHttpRequest createRequest(HttpServletRequest request, AsyncContext context)
throws IOException, URISyntaxException { throws IOException, URISyntaxException {
Assert.notNull(this.servletPath, "Servlet path is not initialized"); Assert.state(this.servletPath != null, "Servlet path is not initialized");
return new ServletServerHttpRequest( return new ServletServerHttpRequest(
request, context, this.servletPath, getDataBufferFactory(), getBufferSize()); request, context, this.servletPath, getDataBufferFactory(), getBufferSize());
} }

View File

@ -67,7 +67,7 @@ public class TomcatHttpHandlerAdapter extends ServletHttpHandlerAdapter {
protected ServletServerHttpRequest createRequest(HttpServletRequest request, AsyncContext asyncContext) protected ServletServerHttpRequest createRequest(HttpServletRequest request, AsyncContext asyncContext)
throws IOException, URISyntaxException { throws IOException, URISyntaxException {
Assert.notNull(getServletPath(), "Servlet path is not initialized"); Assert.state(getServletPath() != null, "Servlet path is not initialized");
return new TomcatServerHttpRequest( return new TomcatServerHttpRequest(
request, asyncContext, getServletPath(), getDataBufferFactory(), getBufferSize()); request, asyncContext, getServletPath(), getDataBufferFactory(), getBufferSize());
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -128,7 +128,7 @@ public class StandardServletAsyncWebRequest extends ServletWebRequest implements
@Override @Override
public void dispatch() { public void dispatch() {
Assert.notNull(this.asyncContext, "Cannot dispatch without an AsyncContext"); Assert.state(this.asyncContext != null, "Cannot dispatch without an AsyncContext");
this.asyncContext.dispatch(); this.asyncContext.dispatch();
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -28,6 +28,8 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.http.server.reactive.HttpHandler; import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ServletHttpHandlerAdapter; import org.springframework.http.server.reactive.ServletHttpHandlerAdapter;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.WebApplicationInitializer; import org.springframework.web.WebApplicationInitializer;
/** /**
@ -55,10 +57,10 @@ public abstract class AbstractReactiveWebInitializer implements WebApplicationIn
@Override @Override
public void onStartup(ServletContext servletContext) throws ServletException { public void onStartup(ServletContext servletContext) throws ServletException {
String servletName = getServletName(); String servletName = getServletName();
Assert.hasLength(servletName, "getServletName() must not return null or empty"); Assert.state(StringUtils.hasLength(servletName), "getServletName() must not return null or empty");
ApplicationContext applicationContext = createApplicationContext(); ApplicationContext applicationContext = createApplicationContext();
Assert.notNull(applicationContext, "createApplicationContext() must not return null"); Assert.state(applicationContext != null, "createApplicationContext() must not return null");
refreshApplicationContext(applicationContext); refreshApplicationContext(applicationContext);
registerCloseListener(servletContext, applicationContext); registerCloseListener(servletContext, applicationContext);
@ -92,7 +94,7 @@ public abstract class AbstractReactiveWebInitializer implements WebApplicationIn
protected ApplicationContext createApplicationContext() { protected ApplicationContext createApplicationContext() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
Class<?>[] configClasses = getConfigClasses(); Class<?>[] configClasses = getConfigClasses();
Assert.notEmpty(configClasses, "No Spring configuration provided through getConfigClasses()"); Assert.state(!ObjectUtils.isEmpty(configClasses), "No Spring configuration provided through getConfigClasses()");
context.register(configClasses); context.register(configClasses);
return context; return context;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -19,7 +19,6 @@ package org.springframework.http.client.support;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.Proxy; import java.net.Proxy;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
@ -28,38 +27,31 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
/** /**
* @author Arjen Poutsma * @author Arjen Poutsma
*/ */
public class ProxyFactoryBeanTests { class ProxyFactoryBeanTests {
ProxyFactoryBean factoryBean; private final ProxyFactoryBean factoryBean = new ProxyFactoryBean();
@BeforeEach
public void setUp() {
factoryBean = new ProxyFactoryBean();
}
@Test @Test
public void noType() { void noType() {
factoryBean.setType(null); factoryBean.setType(null);
assertThatIllegalArgumentException().isThrownBy( assertThatIllegalArgumentException().isThrownBy(factoryBean::afterPropertiesSet);
factoryBean::afterPropertiesSet);
} }
@Test @Test
public void noHostname() { void noHostname() {
factoryBean.setHostname(""); factoryBean.setHostname("");
assertThatIllegalArgumentException().isThrownBy( assertThatIllegalArgumentException().isThrownBy(factoryBean::afterPropertiesSet);
factoryBean::afterPropertiesSet);
} }
@Test @Test
public void noPort() { void noPort() {
factoryBean.setHostname("example.com"); factoryBean.setHostname("example.com");
assertThatIllegalArgumentException().isThrownBy( assertThatIllegalArgumentException().isThrownBy(factoryBean::afterPropertiesSet);
factoryBean::afterPropertiesSet);
} }
@Test @Test
public void normal() { void normal() {
Proxy.Type type = Proxy.Type.HTTP; Proxy.Type type = Proxy.Type.HTTP;
factoryBean.setType(type); factoryBean.setType(type);
String hostname = "example.com"; String hostname = "example.com";

View File

@ -374,7 +374,7 @@ public abstract class AbstractUrlHandlerMapping extends AbstractHandlerMapping i
@Override @Override
@Nullable @Nullable
public RequestMatchResult match(HttpServletRequest request, String pattern) { public RequestMatchResult match(HttpServletRequest request, String pattern) {
Assert.isNull(getPatternParser(), "This HandlerMapping uses PathPatterns."); Assert.state(getPatternParser() == null, "This HandlerMapping uses PathPatterns.");
String lookupPath = UrlPathHelper.getResolvedLookupPath(request); String lookupPath = UrlPathHelper.getResolvedLookupPath(request);
if (getPathMatcher().match(pattern, lookupPath)) { if (getPathMatcher().match(pattern, lookupPath)) {
return new RequestMatchResult(pattern, lookupPath, getPathMatcher()); return new RequestMatchResult(pattern, lookupPath, getPathMatcher());

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -158,7 +158,7 @@ public class HandlerMappingIntrospector
HttpServletRequest request, boolean ignoreException, HttpServletRequest request, boolean ignoreException,
BiFunction<HandlerMapping, HandlerExecutionChain, T> matchHandler) throws Exception { BiFunction<HandlerMapping, HandlerExecutionChain, T> matchHandler) throws Exception {
Assert.notNull(this.handlerMappings, "Handler mappings not initialized"); Assert.state(this.handlerMappings != null, "Handler mappings not initialized");
boolean parseRequestPath = !this.pathPatternHandlerMappings.isEmpty(); boolean parseRequestPath = !this.pathPatternHandlerMappings.isEmpty();
RequestPath previousPath = null; RequestPath previousPath = null;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -59,7 +59,7 @@ class PathPatternMatchableHandlerMapping implements MatchableHandlerMapping {
@Override @Override
public RequestMatchResult match(HttpServletRequest request, String pattern) { public RequestMatchResult match(HttpServletRequest request, String pattern) {
PathPattern pathPattern = this.pathPatternCache.computeIfAbsent(pattern, value -> { PathPattern pathPattern = this.pathPatternCache.computeIfAbsent(pattern, value -> {
Assert.isTrue(this.pathPatternCache.size() < MAX_PATTERNS, "Max size for pattern cache exceeded."); Assert.state(this.pathPatternCache.size() < MAX_PATTERNS, "Max size for pattern cache exceeded.");
return this.parser.parse(pattern); return this.parser.parse(pattern);
}); });
PathContainer path = ServletRequestPathUtils.getParsedRequestPath(request).pathWithinApplication(); PathContainer path = ServletRequestPathUtils.getParsedRequestPath(request).pathWithinApplication();

View File

@ -448,7 +448,7 @@ public class MvcUriComponentsBuilder {
*/ */
public static MethodArgumentBuilder fromMappingName(@Nullable UriComponentsBuilder builder, String name) { public static MethodArgumentBuilder fromMappingName(@Nullable UriComponentsBuilder builder, String name) {
WebApplicationContext wac = getWebApplicationContext(); WebApplicationContext wac = getWebApplicationContext();
Assert.notNull(wac, "No WebApplicationContext"); Assert.state(wac != null, "No WebApplicationContext");
Map<String, RequestMappingInfoHandlerMapping> map = wac.getBeansOfType(RequestMappingInfoHandlerMapping.class); Map<String, RequestMappingInfoHandlerMapping> map = wac.getBeansOfType(RequestMappingInfoHandlerMapping.class);
List<HandlerMethod> handlerMethods = null; List<HandlerMethod> handlerMethods = null;
for (RequestMappingInfoHandlerMapping mapping : map.values()) { for (RequestMappingInfoHandlerMapping mapping : map.values()) {

View File

@ -454,7 +454,7 @@ public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi
@Override @Override
public RequestMatchResult match(HttpServletRequest request, String pattern) { public RequestMatchResult match(HttpServletRequest request, String pattern) {
Assert.isNull(getPatternParser(), "This HandlerMapping requires a PathPattern"); Assert.state(getPatternParser() == null, "This HandlerMapping uses PathPatterns.");
RequestMappingInfo info = RequestMappingInfo.paths(pattern).options(this.config).build(); RequestMappingInfo info = RequestMappingInfo.paths(pattern).options(this.config).build();
RequestMappingInfo match = info.getMatchingCondition(request); RequestMappingInfo match = info.getMatchingCondition(request);
return (match != null && match.getPatternsCondition() != null ? return (match != null && match.getPatternsCondition() != null ?

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -625,8 +625,8 @@ public class ResourceHttpRequestHandler extends WebContentGenerator
return null; return null;
} }
Assert.notNull(this.resolverChain, "ResourceResolverChain not initialized."); Assert.state(this.resolverChain != null, "ResourceResolverChain not initialized.");
Assert.notNull(this.transformerChain, "ResourceTransformerChain not initialized."); Assert.state(this.transformerChain != null, "ResourceTransformerChain not initialized.");
Resource resource = this.resolverChain.resolveResource(request, path, getLocations()); Resource resource = this.resolverChain.resolveResource(request, path, getLocations());
if (resource != null) { if (resource != null) {

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -31,6 +31,7 @@ import org.springframework.core.Conventions;
import org.springframework.lang.Nullable; import org.springframework.lang.Nullable;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils; import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.AbstractContextLoaderInitializer; import org.springframework.web.context.AbstractContextLoaderInitializer;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet; import org.springframework.web.servlet.DispatcherServlet;
@ -77,13 +78,13 @@ public abstract class AbstractDispatcherServletInitializer extends AbstractConte
*/ */
protected void registerDispatcherServlet(ServletContext servletContext) { protected void registerDispatcherServlet(ServletContext servletContext) {
String servletName = getServletName(); String servletName = getServletName();
Assert.hasLength(servletName, "getServletName() must not return null or empty"); Assert.state(StringUtils.hasLength(servletName), "getServletName() must not return null or empty");
WebApplicationContext servletAppContext = createServletApplicationContext(); WebApplicationContext servletAppContext = createServletApplicationContext();
Assert.notNull(servletAppContext, "createServletApplicationContext() must not return null"); Assert.state(servletAppContext != null, "createServletApplicationContext() must not return null");
FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext); FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);
Assert.notNull(dispatcherServlet, "createDispatcherServlet(WebApplicationContext) must not return null"); Assert.state(dispatcherServlet != null, "createDispatcherServlet(WebApplicationContext) must not return null");
dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers()); dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());
ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet); ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2018 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -97,7 +97,7 @@ public class MarshallingView extends AbstractView {
@Override @Override
protected void initApplicationContext() { protected void initApplicationContext() {
Assert.notNull(this.marshaller, "Property 'marshaller' is required"); Assert.state(this.marshaller != null, "Property 'marshaller' is required");
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -267,7 +267,7 @@ public class SubProtocolWebSocketHandler
@Override @Override
public final void start() { public final void start() {
Assert.isTrue(this.defaultProtocolHandler != null || !this.protocolHandlers.isEmpty(), "No handlers"); Assert.state(this.defaultProtocolHandler != null || !this.protocolHandlers.isEmpty(), "No handlers");
synchronized (this.lifecycleMonitor) { synchronized (this.lifecycleMonitor) {
this.clientOutboundChannel.subscribe(this); this.clientOutboundChannel.subscribe(this);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 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 not use this file except in compliance with the License.
@ -84,7 +84,7 @@ public class SockJsWebSocketHandler extends TextWebSocketHandler implements SubP
@Override @Override
public void afterConnectionEstablished(WebSocketSession wsSession) throws Exception { public void afterConnectionEstablished(WebSocketSession wsSession) throws Exception {
Assert.isTrue(this.sessionCount.compareAndSet(0, 1), "Unexpected connection"); Assert.state(this.sessionCount.compareAndSet(0, 1), "Unexpected connection");
this.sockJsSession.initializeDelegateSession(wsSession); this.sockJsSession.initializeDelegateSession(wsSession);
} }