Polishing

This commit is contained in:
Juergen Hoeller
2015-07-24 18:24:19 +02:00
parent e1cce309ae
commit efd7f9bf72
5 changed files with 47 additions and 55 deletions

View File

@@ -545,7 +545,7 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
* Return the primary Validator to apply after each binding step, if any. * Return the primary Validator to apply after each binding step, if any.
*/ */
public Validator getValidator() { public Validator getValidator() {
return this.validators.size() > 0 ? this.validators.get(0) : null; return (this.validators.size() > 0 ? this.validators.get(0) : null);
} }
/** /**

View File

@@ -21,7 +21,6 @@ import java.lang.reflect.Method;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.junit.internal.runners.model.ReflectiveCallable; import org.junit.internal.runners.model.ReflectiveCallable;
@@ -92,8 +91,8 @@ public class SpringJUnit4ClassRunner extends BlockJUnit4ClassRunner {
private static final Method withRulesMethod; private static final Method withRulesMethod;
static { static {
withRulesMethod = ReflectionUtils.findMethod(SpringJUnit4ClassRunner.class, "withRules", FrameworkMethod.class, withRulesMethod = ReflectionUtils.findMethod(SpringJUnit4ClassRunner.class, "withRules",
Object.class, Statement.class); FrameworkMethod.class, Object.class, Statement.class);
if (withRulesMethod == null) { if (withRulesMethod == null) {
throw new IllegalStateException( throw new IllegalStateException(
"Failed to find withRules() method: SpringJUnit4ClassRunner requires JUnit 4.9 or higher."); "Failed to find withRules() method: SpringJUnit4ClassRunner requires JUnit 4.9 or higher.");
@@ -107,12 +106,12 @@ public class SpringJUnit4ClassRunner extends BlockJUnit4ClassRunner {
private static void ensureSpringRulesAreNotPresent(Class<?> testClass) { private static void ensureSpringRulesAreNotPresent(Class<?> testClass) {
for (Field field : testClass.getFields()) { for (Field field : testClass.getFields()) {
if (SpringClassRule.class.isAssignableFrom(field.getType())) { if (SpringClassRule.class.isAssignableFrom(field.getType())) {
throw new IllegalStateException(String.format("Detected SpringClassRule field in test class [%s], but " throw new IllegalStateException(String.format("Detected SpringClassRule field in test class [%s], " +
+ "SpringClassRule cannot be used with the SpringJUnit4ClassRunner.", testClass.getName())); "but SpringClassRule cannot be used with the SpringJUnit4ClassRunner.", testClass.getName()));
} }
if (SpringMethodRule.class.isAssignableFrom(field.getType())) { if (SpringMethodRule.class.isAssignableFrom(field.getType())) {
throw new IllegalStateException(String.format("Detected SpringMethodRule field in test class [%s], " throw new IllegalStateException(String.format("Detected SpringMethodRule field in test class [%s], " +
+ "but SpringMethodRule cannot be used with the SpringJUnit4ClassRunner.", testClass.getName())); "but SpringMethodRule cannot be used with the SpringJUnit4ClassRunner.", testClass.getName()));
} }
} }
} }
@@ -127,7 +126,7 @@ public class SpringJUnit4ClassRunner extends BlockJUnit4ClassRunner {
public SpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError { public SpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError {
super(clazz); super(clazz);
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
logger.debug("SpringJUnit4ClassRunner constructor called with [" + clazz + "]."); logger.debug("SpringJUnit4ClassRunner constructor called with [" + clazz + "]");
} }
ensureSpringRulesAreNotPresent(clazz); ensureSpringRulesAreNotPresent(clazz);
this.testContextManager = createTestContextManager(clazz); this.testContextManager = createTestContextManager(clazz);
@@ -272,7 +271,6 @@ public class SpringJUnit4ClassRunner extends BlockJUnit4ClassRunner {
Object testInstance; Object testInstance;
try { try {
testInstance = new ReflectiveCallable() { testInstance = new ReflectiveCallable() {
@Override @Override
protected Object runReflectiveCall() throws Throwable { protected Object runReflectiveCall() throws Throwable {
return createTest(); return createTest();
@@ -290,7 +288,6 @@ public class SpringJUnit4ClassRunner extends BlockJUnit4ClassRunner {
statement = withRulesReflectively(frameworkMethod, testInstance, statement); statement = withRulesReflectively(frameworkMethod, testInstance, statement);
statement = withPotentialRepeat(frameworkMethod, testInstance, statement); statement = withPotentialRepeat(frameworkMethod, testInstance, statement);
statement = withPotentialTimeout(frameworkMethod, testInstance, statement); statement = withPotentialTimeout(frameworkMethod, testInstance, statement);
return statement; return statement;
} }
@@ -309,8 +306,8 @@ public class SpringJUnit4ClassRunner extends BlockJUnit4ClassRunner {
*/ */
protected boolean isTestMethodIgnored(FrameworkMethod frameworkMethod) { protected boolean isTestMethodIgnored(FrameworkMethod frameworkMethod) {
Method method = frameworkMethod.getMethod(); Method method = frameworkMethod.getMethod();
return (method.isAnnotationPresent(Ignore.class) || !ProfileValueUtils.isTestEnabledInThisEnvironment(method, return (method.isAnnotationPresent(Ignore.class) ||
getTestClass().getJavaClass())); !ProfileValueUtils.isTestEnabledInThisEnvironment(method, getTestClass().getJavaClass()));
} }
/** /**
@@ -334,7 +331,7 @@ public class SpringJUnit4ClassRunner extends BlockJUnit4ClassRunner {
*/ */
protected Class<? extends Throwable> getExpectedException(FrameworkMethod frameworkMethod) { protected Class<? extends Throwable> getExpectedException(FrameworkMethod frameworkMethod) {
Test test = frameworkMethod.getAnnotation(Test.class); Test test = frameworkMethod.getAnnotation(Test.class);
return ((test != null) && (test.expected() != Test.None.class) ? test.expected() : null); return (test != null && test.expected() != Test.None.class ? test.expected() : null);
} }
/** /**
@@ -356,11 +353,9 @@ public class SpringJUnit4ClassRunner extends BlockJUnit4ClassRunner {
long springTimeout = getSpringTimeout(frameworkMethod); long springTimeout = getSpringTimeout(frameworkMethod);
long junitTimeout = getJUnitTimeout(frameworkMethod); long junitTimeout = getJUnitTimeout(frameworkMethod);
if (springTimeout > 0 && junitTimeout > 0) { if (springTimeout > 0 && junitTimeout > 0) {
String msg = String.format( String msg = String.format("Test method [%s] has been configured with Spring's @Timed(millis=%s) and " +
"Test method [%s] has been configured with Spring's @Timed(millis=%s) and " "JUnit's @Test(timeout=%s) annotations, but only one declaration of a 'timeout' is " +
+ "JUnit's @Test(timeout=%s) annotations, but only one declaration of " "permitted per test method.", frameworkMethod.getMethod(), springTimeout, junitTimeout);
+ "a 'timeout' is permitted per test method.",
frameworkMethod.getMethod(), springTimeout, junitTimeout);
logger.error(msg); logger.error(msg);
throw new IllegalStateException(msg); throw new IllegalStateException(msg);
} }
@@ -385,7 +380,7 @@ public class SpringJUnit4ClassRunner extends BlockJUnit4ClassRunner {
*/ */
protected long getJUnitTimeout(FrameworkMethod frameworkMethod) { protected long getJUnitTimeout(FrameworkMethod frameworkMethod) {
Test test = frameworkMethod.getAnnotation(Test.class); Test test = frameworkMethod.getAnnotation(Test.class);
return ((test != null) && (test.timeout() > 0) ? test.timeout() : 0); return (test != null && test.timeout() > 0 ? test.timeout() : 0);
} }
/** /**
@@ -410,7 +405,7 @@ public class SpringJUnit4ClassRunner extends BlockJUnit4ClassRunner {
protected Statement withBefores(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) { protected Statement withBefores(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) {
Statement junitBefores = super.withBefores(frameworkMethod, testInstance, statement); Statement junitBefores = super.withBefores(frameworkMethod, testInstance, statement);
return new RunBeforeTestMethodCallbacks(junitBefores, testInstance, frameworkMethod.getMethod(), return new RunBeforeTestMethodCallbacks(junitBefores, testInstance, frameworkMethod.getMethod(),
getTestContextManager()); getTestContextManager());
} }
/** /**
@@ -424,7 +419,7 @@ public class SpringJUnit4ClassRunner extends BlockJUnit4ClassRunner {
protected Statement withAfters(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) { protected Statement withAfters(FrameworkMethod frameworkMethod, Object testInstance, Statement statement) {
Statement junitAfters = super.withAfters(frameworkMethod, testInstance, statement); Statement junitAfters = super.withAfters(frameworkMethod, testInstance, statement);
return new RunAfterTestMethodCallbacks(junitAfters, testInstance, frameworkMethod.getMethod(), return new RunAfterTestMethodCallbacks(junitAfters, testInstance, frameworkMethod.getMethod(),
getTestContextManager()); getTestContextManager());
} }
/** /**

View File

@@ -214,8 +214,8 @@ public abstract class AbstractJackson2HttpMessageConverter extends AbstractGener
if (inputMessage instanceof MappingJacksonInputMessage) { if (inputMessage instanceof MappingJacksonInputMessage) {
Class<?> deserializationView = ((MappingJacksonInputMessage) inputMessage).getDeserializationView(); Class<?> deserializationView = ((MappingJacksonInputMessage) inputMessage).getDeserializationView();
if (deserializationView != null) { if (deserializationView != null) {
return this.objectMapper.readerWithView(deserializationView) return this.objectMapper.readerWithView(deserializationView).withType(javaType).
.withType(javaType).readValue(inputMessage.getBody()); readValue(inputMessage.getBody());
} }
} }
return this.objectMapper.readValue(inputMessage.getBody(), javaType); return this.objectMapper.readValue(inputMessage.getBody(), javaType);
@@ -245,8 +245,7 @@ public abstract class AbstractJackson2HttpMessageConverter extends AbstractGener
serializationView = container.getSerializationView(); serializationView = container.getSerializationView();
filters = container.getFilters(); filters = container.getFilters();
} }
if (jackson26Available && type != null && value != null if (jackson26Available && type != null && value != null && TypeUtils.isAssignable(type, value.getClass())) {
&& TypeUtils.isAssignable(type, value.getClass())) {
javaType = getJavaType(type, null); javaType = getJavaType(type, null);
} }
ObjectWriter objectWriter; ObjectWriter objectWriter;

View File

@@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2014 the original author or authors. * Copyright 2002-2015 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.
@@ -73,6 +73,7 @@ public class HttpComponentsHttpInvokerRequestExecutor extends AbstractHttpInvoke
private RequestConfig requestConfig; private RequestConfig requestConfig;
/** /**
* Create a new instance of the HttpComponentsHttpInvokerRequestExecutor with a default * Create a new instance of the HttpComponentsHttpInvokerRequestExecutor with a default
* {@link HttpClient} that uses a default {@code org.apache.http.impl.conn.PoolingClientConnectionManager}. * {@link HttpClient} that uses a default {@code org.apache.http.impl.conn.PoolingClientConnectionManager}.
@@ -82,20 +83,6 @@ public class HttpComponentsHttpInvokerRequestExecutor extends AbstractHttpInvoke
.setSocketTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS).build()); .setSocketTimeout(DEFAULT_READ_TIMEOUT_MILLISECONDS).build());
} }
private static HttpClient createDefaultHttpClient() {
Registry<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager
= new PoolingHttpClientConnectionManager(schemeRegistry);
connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
return HttpClientBuilder.create().setConnectionManager(connectionManager).build();
}
/** /**
* Create a new instance of the HttpComponentsClientHttpRequestFactory * Create a new instance of the HttpComponentsClientHttpRequestFactory
* with the given {@link HttpClient} instance. * with the given {@link HttpClient} instance.
@@ -110,6 +97,21 @@ public class HttpComponentsHttpInvokerRequestExecutor extends AbstractHttpInvoke
this.requestConfig = requestConfig; this.requestConfig = requestConfig;
} }
private static HttpClient createDefaultHttpClient() {
Registry<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(schemeRegistry);
connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
return HttpClientBuilder.create().setConnectionManager(connectionManager).build();
}
/** /**
* Set the {@link HttpClient} instance to use for this request executor. * Set the {@link HttpClient} instance to use for this request executor.
*/ */
@@ -134,8 +136,7 @@ public class HttpComponentsHttpInvokerRequestExecutor extends AbstractHttpInvoke
*/ */
public void setConnectTimeout(int timeout) { public void setConnectTimeout(int timeout) {
Assert.isTrue(timeout >= 0, "Timeout must be a non-negative value"); Assert.isTrue(timeout >= 0, "Timeout must be a non-negative value");
this.requestConfig = cloneRequestConfig() this.requestConfig = cloneRequestConfig().setConnectTimeout(timeout).build();
.setConnectTimeout(timeout).build();
setLegacyConnectionTimeout(getHttpClient(), timeout); setLegacyConnectionTimeout(getHttpClient(), timeout);
} }
@@ -156,8 +157,7 @@ public class HttpComponentsHttpInvokerRequestExecutor extends AbstractHttpInvoke
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
private void setLegacyConnectionTimeout(HttpClient client, int timeout) { private void setLegacyConnectionTimeout(HttpClient client, int timeout) {
if (org.apache.http.impl.client.AbstractHttpClient.class.isInstance(client)) { if (org.apache.http.impl.client.AbstractHttpClient.class.isInstance(client)) {
client.getParams().setIntParameter( client.getParams().setIntParameter(org.apache.http.params.CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
org.apache.http.params.CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
} }
} }
@@ -171,8 +171,7 @@ public class HttpComponentsHttpInvokerRequestExecutor extends AbstractHttpInvoke
* @see RequestConfig#getConnectionRequestTimeout() * @see RequestConfig#getConnectionRequestTimeout()
*/ */
public void setConnectionRequestTimeout(int connectionRequestTimeout) { public void setConnectionRequestTimeout(int connectionRequestTimeout) {
this.requestConfig = cloneRequestConfig() this.requestConfig = cloneRequestConfig().setConnectionRequestTimeout(connectionRequestTimeout).build();
.setConnectionRequestTimeout(connectionRequestTimeout).build();
} }
/** /**
@@ -186,8 +185,7 @@ public class HttpComponentsHttpInvokerRequestExecutor extends AbstractHttpInvoke
*/ */
public void setReadTimeout(int timeout) { public void setReadTimeout(int timeout) {
Assert.isTrue(timeout >= 0, "Timeout must be a non-negative value"); Assert.isTrue(timeout >= 0, "Timeout must be a non-negative value");
this.requestConfig = cloneRequestConfig() this.requestConfig = cloneRequestConfig().setSocketTimeout(timeout).build();
.setSocketTimeout(timeout).build();
setLegacySocketTimeout(getHttpClient(), timeout); setLegacySocketTimeout(getHttpClient(), timeout);
} }
@@ -201,15 +199,15 @@ public class HttpComponentsHttpInvokerRequestExecutor extends AbstractHttpInvoke
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
private void setLegacySocketTimeout(HttpClient client, int timeout) { private void setLegacySocketTimeout(HttpClient client, int timeout) {
if (org.apache.http.impl.client.AbstractHttpClient.class.isInstance(client)) { if (org.apache.http.impl.client.AbstractHttpClient.class.isInstance(client)) {
client.getParams().setIntParameter( client.getParams().setIntParameter(org.apache.http.params.CoreConnectionPNames.SO_TIMEOUT, timeout);
org.apache.http.params.CoreConnectionPNames.SO_TIMEOUT, timeout);
} }
} }
private RequestConfig.Builder cloneRequestConfig() { private RequestConfig.Builder cloneRequestConfig() {
return this.requestConfig != null ? RequestConfig.copy(this.requestConfig) : RequestConfig.custom(); return (this.requestConfig != null ? RequestConfig.copy(this.requestConfig) : RequestConfig.custom());
} }
/** /**
* Execute the given request through the HttpClient. * Execute the given request through the HttpClient.
* <p>This method implements the basic processing workflow: * <p>This method implements the basic processing workflow:

View File

@@ -177,7 +177,7 @@ public class ServletWebRequest extends ServletRequestAttributes implements Nativ
HttpServletResponse response = getResponse(); HttpServletResponse response = getResponse();
if (lastModifiedTimestamp >= 0 && !this.notModified) { if (lastModifiedTimestamp >= 0 && !this.notModified) {
if (response == null || HttpStatus.valueOf(response.getStatus()).is2xxSuccessful()) { if (response == null || HttpStatus.valueOf(response.getStatus()).is2xxSuccessful()) {
this.notModified = isTimeStampNotModified(lastModifiedTimestamp); this.notModified = isTimestampNotModified(lastModifiedTimestamp);
if (response != null) { if (response != null) {
if (this.notModified && supportsNotModifiedStatus()) { if (this.notModified && supportsNotModifiedStatus()) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
@@ -192,7 +192,7 @@ public class ServletWebRequest extends ServletRequestAttributes implements Nativ
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
private boolean isTimeStampNotModified(long lastModifiedTimestamp) { private boolean isTimestampNotModified(long lastModifiedTimestamp) {
long ifModifiedSince = -1; long ifModifiedSince = -1;
try { try {
ifModifiedSince = getRequest().getDateHeader(HEADER_IF_MODIFIED_SINCE); ifModifiedSince = getRequest().getDateHeader(HEADER_IF_MODIFIED_SINCE);
@@ -270,7 +270,7 @@ public class ServletWebRequest extends ServletRequestAttributes implements Nativ
if (StringUtils.hasLength(etag) && !this.notModified) { if (StringUtils.hasLength(etag) && !this.notModified) {
if (response == null || HttpStatus.valueOf(response.getStatus()).is2xxSuccessful()) { if (response == null || HttpStatus.valueOf(response.getStatus()).is2xxSuccessful()) {
etag = addEtagPadding(etag); etag = addEtagPadding(etag);
this.notModified = isETagNotModified(etag) && isTimeStampNotModified(lastModifiedTimestamp); this.notModified = isETagNotModified(etag) && isTimestampNotModified(lastModifiedTimestamp);
if (response != null) { if (response != null) {
if (this.notModified && supportsNotModifiedStatus()) { if (this.notModified && supportsNotModifiedStatus()) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);