language stringclasses 1
value | owner stringlengths 2 15 | repo stringlengths 2 21 | sha stringlengths 45 45 | message stringlengths 7 36.3k | path stringlengths 1 199 | patch stringlengths 15 102k | is_multipart bool 2
classes |
|---|---|---|---|---|---|---|---|
Other | spring-projects | spring-framework | 38cf91922c0423fa8ffd541e9cc7f1d2cae87529.json | Fix intermittent test failure in AsyncTests | spring-test-mvc/src/main/java/org/springframework/test/web/servlet/TestDispatcherServlet.java | @@ -66,19 +66,21 @@ protected void service(HttpServletRequest request, HttpServletResponse response)
super.service(request, response);
}
- private CountDownLatch registerAsyncInterceptors(HttpServletRequest request) {
+ private CountDownLatch registerAsyncInterceptors(final HttpServletRequest servletRequest) {
final CountDownLatch asyncResultLatch = new CountDownLatch(1);
- WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
+ WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(servletRequest);
asyncManager.registerCallableInterceptor(KEY, new CallableProcessingInterceptorAdapter() {
public <T> void postProcess(NativeWebRequest request, Callable<T> task, Object value) throws Exception {
+ getMvcResult(servletRequest).setAsyncResult(value);
asyncResultLatch.countDown();
}
});
asyncManager.registerDeferredResultInterceptor(KEY, new DeferredResultProcessingInterceptorAdapter() {
public <T> void postProcess(NativeWebRequest request, DeferredResult<T> result, Object value) throws Exception {
+ getMvcResult(servletRequest).setAsyncResult(value);
asyncResultLatch.countDown();
}
}); | true |
Other | spring-projects | spring-framework | 93c01e071098bb2e07e127c3b091d89ce73de983.json | Fix timezone issue in DateTimeFormatterFactory
The DateTimeFormatterFactory introduced in SPR-7121 supports a timeZone
property; however, this property is currently not properly supported.
This commit addresses this issue by ensuring that the timeZone properly
is honored.
Issue: SPR-9953 | spring-context/src/main/java/org/springframework/format/datetime/joda/DateTimeFormatterFactory.java | @@ -33,6 +33,7 @@
* or {@link #setStyle(String) style} (considered in that order).
*
* @author Phillip Webb
+ * @author Sam Brannen
* @see #getDateTimeFormatter()
* @see #getDateTimeFormatter(DateTimeFormatter)
* @since 3.2
@@ -100,7 +101,7 @@ public DateTimeFormatter getDateTimeFormatter() {
public DateTimeFormatter getDateTimeFormatter(DateTimeFormatter fallbackFormatter) {
DateTimeFormatter dateTimeFormatter = createDateTimeFormatter();
if(dateTimeFormatter != null && this.timeZone != null) {
- dateTimeFormatter.withZone(DateTimeZone.forTimeZone(this.timeZone));
+ dateTimeFormatter = dateTimeFormatter.withZone(DateTimeZone.forTimeZone(this.timeZone));
}
return (dateTimeFormatter != null ? dateTimeFormatter : fallbackFormatter);
} | true |
Other | spring-projects | spring-framework | 93c01e071098bb2e07e127c3b091d89ce73de983.json | Fix timezone issue in DateTimeFormatterFactory
The DateTimeFormatterFactory introduced in SPR-7121 supports a timeZone
property; however, this property is currently not properly supported.
This commit addresses this issue by ensuring that the timeZone properly
is honored.
Issue: SPR-9953 | spring-context/src/test/java/org/springframework/format/datetime/joda/DateTimeFormatterFactoryTests.java | @@ -16,16 +16,14 @@
package org.springframework.format.datetime.joda;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.nullValue;
-import static org.hamcrest.Matchers.sameInstance;
+import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.util.Locale;
import java.util.TimeZone;
import org.joda.time.DateTime;
+import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.junit.Test;
@@ -35,13 +33,15 @@
* Tests for {@link DateTimeFormatterFactory}.
*
* @author Phillip Webb
+ * @author Sam Brannen
*/
public class DateTimeFormatterFactoryTests {
private DateTimeFormatterFactory factory = new DateTimeFormatterFactory();
private DateTime dateTime = new DateTime(2009, 10, 21, 12, 10, 00, 00);
+
@Test
public void shouldDefaultToMediumFormat() throws Exception {
assertThat(factory.getObject(), is(equalTo(DateTimeFormat.mediumDateTime())));
@@ -63,7 +63,7 @@ public void shouldBeSingleton() throws Exception {
@Test
@SuppressWarnings("rawtypes")
public void shouldCreateDateTimeFormatter() throws Exception {
- assertThat(factory.getObjectType(), is(equalTo((Class)DateTimeFormatter.class)));
+ assertThat(factory.getObjectType(), is(equalTo((Class) DateTimeFormatter.class)));
}
@Test
@@ -93,12 +93,34 @@ public void shouldGetDateTimeFormatter() throws Exception {
@Test
public void shouldGetWithTimeZone() throws Exception {
+
+ TimeZone zurich = TimeZone.getTimeZone("Europe/Zurich");
+ TimeZone newYork = TimeZone.getTimeZone("America/New_York");
+
+ // Ensure that we are testing against a timezone other than the default.
+ TimeZone testTimeZone;
+ String offset;
+
+ if (zurich.equals(TimeZone.getDefault())) {
+ testTimeZone = newYork;
+ offset = "-0400"; // Daylight savings on October 21st
+ }
+ else {
+ testTimeZone = zurich;
+ offset = "+0200"; // Daylight savings on October 21st
+ }
+
factory.setPattern("yyyyMMddHHmmss Z");
- factory.setTimeZone(TimeZone.getTimeZone("-0700"));
- assertThat(factory.getDateTimeFormatter().print(dateTime), is("20091021121000 -0700"));
+ factory.setTimeZone(testTimeZone);
+
+ DateTimeZone dateTimeZone = DateTimeZone.forTimeZone(testTimeZone);
+ DateTime dateTime = new DateTime(2009, 10, 21, 12, 10, 00, 00, dateTimeZone);
+
+ assertThat(factory.getDateTimeFormatter().print(dateTime), is("20091021121000 " + offset));
}
private DateTimeFormatter applyLocale(DateTimeFormatter dateTimeFormatter) {
return dateTimeFormatter.withLocale(Locale.US);
}
+
} | true |
Other | spring-projects | spring-framework | b3e3a37441473dab2121694afd38d2fb7fe9b681.json | Release version 3.2.0.RC1 | gradle.properties | @@ -1 +1 @@
-version=3.2.0.BUILD-SNAPSHOT
+version=3.2.0.RC1 | false |
Other | spring-projects | spring-framework | 856fb2ccacf6a1c98526671eb75cf697aa205e81.json | Move JRuby dependency below Joda
JRuby includes a copy of joda classes with the same package names.
This commit changes the order of the loaded jars to load the original
joda classes first. | build.gradle | @@ -262,12 +262,12 @@ project('spring-context') {
}
compile("org.beanshell:bsh:2.0b4", optional)
compile("org.codehaus.groovy:groovy-all:1.6.3", optional)
- compile("org.jruby:jruby:1.4.0", optional)
compile("org.hibernate:hibernate-validator:4.2.0.Final") { dep ->
optional dep
exclude group: 'org.slf4j', module: 'slf4j-api'
}
compile("joda-time:joda-time:1.6", optional)
+ compile("org.jruby:jruby:1.4.0", optional)
compile("javax.cache:cache-api:0.5", optional)
compile("net.sf.ehcache:ehcache-core:2.0.0", optional)
compile("org.slf4j:slf4j-api:1.6.1", optional) | false |
Other | spring-projects | spring-framework | 3aa9ac15a1e0a36ff15b94e18bf75e4034a643f4.json | Update cache to support concurrent reads
Change the cache implementation from a synchronized weak hash map to
a concurrent implementation.
Issue: SPR-8701 | spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java | @@ -16,25 +16,22 @@
package org.springframework.core;
-import java.lang.ref.Reference;
-import java.lang.ref.WeakReference;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import java.util.WeakHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
+import org.springframework.util.ConcurrentReferenceHashMap;
/**
* Helper class for resolving generic types against type variables.
@@ -53,9 +50,8 @@ public abstract class GenericTypeResolver {
private static final Log logger = LogFactory.getLog(GenericTypeResolver.class);
/** Cache from Class to TypeVariable Map */
- private static final Map<Class, Reference<Map<TypeVariable, Type>>> typeVariableCache =
- Collections.synchronizedMap(new WeakHashMap<Class, Reference<Map<TypeVariable, Type>>>());
-
+ private static final Map<Class, Map<TypeVariable, Type>> typeVariableCache =
+ new ConcurrentReferenceHashMap<Class, Map<TypeVariable,Type>>();
/**
* Determine the target type for the given parameter specification.
@@ -408,8 +404,8 @@ static Type getRawType(Type genericType, Map<TypeVariable, Type> typeVariableMap
* all super types, enclosing types and interfaces.
*/
public static Map<TypeVariable, Type> getTypeVariableMap(Class clazz) {
- Reference<Map<TypeVariable, Type>> ref = typeVariableCache.get(clazz);
- Map<TypeVariable, Type> typeVariableMap = (ref != null ? ref.get() : null);
+ Map<TypeVariable, Type> ref = typeVariableCache.get(clazz);
+ Map<TypeVariable, Type> typeVariableMap = (ref != null ? ref : null);
if (typeVariableMap == null) {
typeVariableMap = new HashMap<TypeVariable, Type>();
@@ -441,7 +437,7 @@ public static Map<TypeVariable, Type> getTypeVariableMap(Class clazz) {
type = type.getEnclosingClass();
}
- typeVariableCache.put(clazz, new WeakReference<Map<TypeVariable, Type>>(typeVariableMap));
+ typeVariableCache.put(clazz, typeVariableMap);
}
return typeVariableMap; | false |
Other | spring-projects | spring-framework | de38c033e4f2196a481f88329703e32730bf1ab7.json | Make hamcrest dependency optional in spring-test
Users of Spring MVC Test will need to list a hamcrest dependency --
either hamcrest-library or hamcrest-all.
Issue: SPR-9940 | build.gradle | @@ -557,7 +557,8 @@ project('spring-test-mvc') {
compile project(":spring-webmvc")
compile project(":spring-test").sourceSets.main.output
compile("org.apache.tomcat:tomcat-servlet-api:7.0.8", provided)
- compile "org.hamcrest:hamcrest-library:1.3"
+ compile("org.hamcrest:hamcrest-core:1.3", optional)
+ compile("org.hamcrest:hamcrest-library:1.3", optional)
compile("com.jayway.jsonpath:json-path:0.8.1", optional)
compile("xmlunit:xmlunit:1.2", optional)
testCompile("org.slf4j:jcl-over-slf4j:1.6.1") | false |
Other | spring-projects | spring-framework | c0baea58c0a14ea34d53f3823704892154b7803e.json | Fix issue with generic @RequestBody arguments
The original commit c9b7b1 ensured the ability to read parameterized
type @RequestBody arguments via GenericHttpMessageConverter (e.g.
application/json and List<String>). However, it also affected the
ability to read @RequestBody arguments that happen are parameterized
but aren't treated as such (e.g. application/x-www-form-urlencoded and
MultiValueMap<String, String>). This commit corrects the issue.
Issue: SPR-9570 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodArgumentResolver.java | @@ -17,6 +17,9 @@
package org.springframework.web.servlet.mvc.method.annotation;
import java.io.IOException;
+import java.lang.reflect.Array;
+import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
@@ -107,15 +110,15 @@ protected <T> Object readWithMessageConverters(NativeWebRequest webRequest,
* @throws HttpMediaTypeNotSupportedException if no suitable message converter is found
*/
@SuppressWarnings("unchecked")
- protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter methodParam,
- Type paramType) throws IOException, HttpMediaTypeNotSupportedException {
+ protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage,
+ MethodParameter methodParam, Type paramType) throws IOException, HttpMediaTypeNotSupportedException {
MediaType contentType = inputMessage.getHeaders().getContentType();
if (contentType == null) {
contentType = MediaType.APPLICATION_OCTET_STREAM;
}
- Class<T> paramClass = (paramType instanceof Class) ? (Class) paramType : null;
+ Class<T> paramClass = getParamClass(paramType);
for (HttpMessageConverter<?> messageConverter : this.messageConverters) {
if (messageConverter instanceof GenericHttpMessageConverter) {
@@ -142,6 +145,26 @@ protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, Me
throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes);
}
+ private Class getParamClass(Type paramType) {
+ if (paramType instanceof Class) {
+ return (Class) paramType;
+ }
+ else if (paramType instanceof GenericArrayType) {
+ Type componentType = ((GenericArrayType) paramType).getGenericComponentType();
+ if (componentType instanceof Class) {
+ // Surely, there should be a nicer way to determine the array type
+ return Array.newInstance((Class<?>) componentType, 0).getClass();
+ }
+ }
+ else if (paramType instanceof ParameterizedType) {
+ ParameterizedType parameterizedType = (ParameterizedType) paramType;
+ if (parameterizedType.getRawType() instanceof Class) {
+ return (Class) parameterizedType.getRawType();
+ }
+ }
+ return null;
+ }
+
/**
* Creates a new {@link HttpInputMessage} from the given {@link NativeWebRequest}.
* | true |
Other | spring-projects | spring-framework | c0baea58c0a14ea34d53f3823704892154b7803e.json | Fix issue with generic @RequestBody arguments
The original commit c9b7b1 ensured the ability to read parameterized
type @RequestBody arguments via GenericHttpMessageConverter (e.g.
application/json and List<String>). However, it also affected the
ability to read @RequestBody arguments that happen are parameterized
but aren't treated as such (e.g. application/x-www-form-urlencoded and
MultiValueMap<String, String>). This commit corrects the issue.
Issue: SPR-9570 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java | @@ -17,8 +17,6 @@
package org.springframework.web.servlet.mvc.method.annotation;
import java.io.IOException;
-import java.lang.reflect.Array;
-import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
@@ -89,23 +87,11 @@ private Type getHttpEntityType(MethodParameter parameter) {
Assert.isAssignable(HttpEntity.class, parameter.getParameterType());
ParameterizedType type = (ParameterizedType) parameter.getGenericParameterType();
if (type.getActualTypeArguments().length == 1) {
- Type typeArgument = type.getActualTypeArguments()[0];
- if (typeArgument instanceof Class) {
- return (Class<?>) typeArgument;
- }
- else if (typeArgument instanceof GenericArrayType) {
- Type componentType = ((GenericArrayType) typeArgument).getGenericComponentType();
- if (componentType instanceof Class) {
- // Surely, there should be a nicer way to determine the array type
- return Array.newInstance((Class<?>) componentType, 0).getClass();
- }
- }
- else if (typeArgument instanceof ParameterizedType) {
- return typeArgument;
- }
+ return type.getActualTypeArguments()[0];
}
- throw new IllegalArgumentException("HttpEntity parameter (" + parameter.getParameterName() + ") "
- + "in method " + parameter.getMethod() + "is not parameterized");
+ throw new IllegalArgumentException("HttpEntity parameter ("
+ + parameter.getParameterName() + ") in method " + parameter.getMethod()
+ + " is not parameterized or has more than one parameter");
}
public void handleReturnValue( | true |
Other | spring-projects | spring-framework | c0baea58c0a14ea34d53f3823704892154b7803e.json | Fix issue with generic @RequestBody arguments
The original commit c9b7b1 ensured the ability to read parameterized
type @RequestBody arguments via GenericHttpMessageConverter (e.g.
application/json and List<String>). However, it also affected the
ability to read @RequestBody arguments that happen are parameterized
but aren't treated as such (e.g. application/x-www-form-urlencoded and
MultiValueMap<String, String>). This commit corrects the issue.
Issue: SPR-9570 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java | @@ -190,30 +190,35 @@ private void testResolveArgumentWithValidation(SimpleBean simpleBean) throws IOE
}
@Test(expected = HttpMediaTypeNotSupportedException.class)
- public void resolveArgumentNotReadable() throws Exception {
+ public void resolveArgumentCannotRead() throws Exception {
MediaType contentType = MediaType.TEXT_PLAIN;
servletRequest.addHeader("Content-Type", contentType.toString());
- servletRequest.setContent(new byte[] {});
expect(messageConverter.canRead(String.class, contentType)).andReturn(false);
replay(messageConverter);
processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
}
- @Test(expected = HttpMediaTypeNotSupportedException.class)
+ @Test
public void resolveArgumentNoContentType() throws Exception {
- servletRequest.setContent(new byte[] {});
- processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
- }
-
- @Test(expected = HttpMessageNotReadableException.class)
- public void resolveArgumentRequiredNoContent() throws Exception {
- processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
+ expect(messageConverter.canRead(String.class, MediaType.APPLICATION_OCTET_STREAM)).andReturn(false);
+ replay(messageConverter);
+ try {
+ processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null);
+ fail("Expected exception");
+ }
+ catch (HttpMediaTypeNotSupportedException ex) {
+ }
+ verify(messageConverter);
}
@Test
public void resolveArgumentNotRequiredNoContent() throws Exception {
+ servletRequest.setContent(null);
+ assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, webRequest, new ValidatingBinderFactory()));
+
+ servletRequest.setContent(new byte[0]);
assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, webRequest, new ValidatingBinderFactory()));
}
| true |
Other | spring-projects | spring-framework | c0baea58c0a14ea34d53f3823704892154b7803e.json | Fix issue with generic @RequestBody arguments
The original commit c9b7b1 ensured the ability to read parameterized
type @RequestBody arguments via GenericHttpMessageConverter (e.g.
application/json and List<String>). However, it also affected the
ability to read @RequestBody arguments that happen are parameterized
but aren't treated as such (e.g. application/x-www-form-urlencoded and
MultiValueMap<String, String>). This commit corrects the issue.
Issue: SPR-9570 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java | @@ -21,17 +21,21 @@
import java.lang.reflect.Method;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.MethodParameter;
+import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
+import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.util.MultiValueMap;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.RequestBody;
@@ -52,6 +56,8 @@ public class RequestResponseBodyMethodProcessorTests {
private MethodParameter paramGenericList;
private MethodParameter paramSimpleBean;
+ private MethodParameter paramMultiValueMap;
+ private MethodParameter paramString;
private MethodParameter returnTypeString;
private ModelAndViewContainer mavContainer;
@@ -65,9 +71,13 @@ public class RequestResponseBodyMethodProcessorTests {
@Before
public void setUp() throws Exception {
- Method method = getClass().getMethod("handle", List.class, SimpleBean.class);
+ Method method = getClass().getMethod("handle",
+ List.class, SimpleBean.class, MultiValueMap.class, String.class);
+
paramGenericList = new MethodParameter(method, 0);
paramSimpleBean = new MethodParameter(method, 1);
+ paramMultiValueMap = new MethodParameter(method, 2);
+ paramString = new MethodParameter(method, 3);
returnTypeString = new MethodParameter(method, -1);
mavContainer = new ModelAndViewContainer();
@@ -79,10 +89,10 @@ public void setUp() throws Exception {
@Test
- public void resolveGenericArgument() throws Exception {
+ public void resolveArgumentParameterizedType() throws Exception {
String content = "[{\"name\" : \"Jad\"}, {\"name\" : \"Robert\"}]";
this.servletRequest.setContent(content.getBytes("UTF-8"));
- this.servletRequest.setContentType("application/json");
+ this.servletRequest.setContentType(MediaType.APPLICATION_JSON_VALUE);
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(new MappingJackson2HttpMessageConverter());
@@ -98,7 +108,26 @@ public void resolveGenericArgument() throws Exception {
}
@Test
- public void resolveArgument() throws Exception {
+ public void resolveArgumentRawTypeFromParameterizedType() throws Exception {
+ String content = "fruit=apple&vegetable=kale";
+ this.servletRequest.setContent(content.getBytes("UTF-8"));
+ this.servletRequest.setContentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
+
+ List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
+ converters.add(new XmlAwareFormHttpMessageConverter());
+ RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);
+
+ @SuppressWarnings("unchecked")
+ MultiValueMap<String, String> result = (MultiValueMap<String, String>) processor.resolveArgument(
+ paramMultiValueMap, mavContainer, webRequest, new ValidatingBinderFactory());
+
+ assertNotNull(result);
+ assertEquals("apple", result.getFirst("fruit"));
+ assertEquals("kale", result.getFirst("vegetable"));
+ }
+
+ @Test
+ public void resolveArgumentClassJson() throws Exception {
String content = "{\"name\" : \"Jad\"}";
this.servletRequest.setContent(content.getBytes("UTF-8"));
this.servletRequest.setContentType("application/json");
@@ -114,6 +143,23 @@ public void resolveArgument() throws Exception {
assertEquals("Jad", result.getName());
}
+ @Test
+ public void resolveArgumentClassString() throws Exception {
+ String content = "foobarbaz";
+ this.servletRequest.setContent(content.getBytes("UTF-8"));
+ this.servletRequest.setContentType("application/json");
+
+ List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
+ converters.add(new StringHttpMessageConverter());
+ RequestResponseBodyMethodProcessor processor = new RequestResponseBodyMethodProcessor(converters);
+
+ String result = (String) processor.resolveArgument(
+ paramString, mavContainer, webRequest, new ValidatingBinderFactory());
+
+ assertNotNull(result);
+ assertEquals("foobarbaz", result);
+ }
+
// SPR-9160
@Test
@@ -158,7 +204,12 @@ public void handleReturnValueStringAcceptCharset() throws Exception {
}
- public String handle(@RequestBody List<SimpleBean> list, @RequestBody SimpleBean simpleBean) {
+ public String handle(
+ @RequestBody List<SimpleBean> list,
+ @RequestBody SimpleBean simpleBean,
+ @RequestBody MultiValueMap<String, String> multiValueMap,
+ @RequestBody String string) {
+
return null;
}
| true |
Other | spring-projects | spring-framework | 742d5f6f3830f8a021ef7f1da3e6bf6e92036633.json | Restore GRADLE_OPTS from wrappers
Run the updated build script to generate gradlew and gradlew.bat files
that have correct GRADLE_OPTS. | gradle/wrapper/gradle-wrapper.properties | @@ -1,4 +1,4 @@
-#Sun Oct 28 11:46:52 PDT 2012
+#Wed Oct 31 17:27:34 PDT 2012
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME | true |
Other | spring-projects | spring-framework | 742d5f6f3830f8a021ef7f1da3e6bf6e92036633.json | Restore GRADLE_OPTS from wrappers
Run the updated build script to generate gradlew and gradlew.bat files
that have correct GRADLE_OPTS. | gradlew | @@ -7,6 +7,7 @@
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+GRADLE_OPTS="-XX:MaxPermSize=1024m -Xmx1024m -XX:MaxHeapSize=256m $GRADLE_OPTS"
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle" | true |
Other | spring-projects | spring-framework | 742d5f6f3830f8a021ef7f1da3e6bf6e92036633.json | Restore GRADLE_OPTS from wrappers
Run the updated build script to generate gradlew and gradlew.bat files
that have correct GRADLE_OPTS. | gradlew.bat | @@ -9,6 +9,7 @@
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set GRADLE_OPTS=-XX:MaxPermSize=1024m -Xmx1024m -XX:MaxHeapSize=256m %GRADLE_OPTS%
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
| true |
Other | spring-projects | spring-framework | 23b091b786f18ceb477e1113fefe503c89471737.json | Remove need to manually set wrapper GRADLE_OPTS
Replace the wrapper task with a variant that automatically adds the
appropriate GRADLE_OPTS to the shell and bat files. | build.gradle | @@ -805,3 +805,12 @@ configure(rootProject) {
}
}
+def defaultWrapper = tasks["wrapper"]
+task wrapper(overwrite: true, dependsOn: defaultWrapper) << {
+ def gradleOpts = "-XX:MaxPermSize=1024m -Xmx1024m -XX:MaxHeapSize=256m"
+ File wrapperFile = file('gradlew')
+ wrapperFile.text = wrapperFile.text.replace("DEFAULT_JVM_OPTS=", "GRADLE_OPTS=\"$gradleOpts \$GRADLE_OPTS\"\nDEFAULT_JVM_OPTS=")
+ File wrapperBatFile = file('gradlew.bat')
+ wrapperBatFile.text = wrapperBatFile.text.replace("set DEFAULT_JVM_OPTS=", "set GRADLE_OPTS=$gradleOpts %GRADLE_OPTS%\nset DEFAULT_JVM_OPTS=")
+}
+ | false |
Other | spring-projects | spring-framework | 00220ebab0593fc9a4e4f0cbbf5632947a77799a.json | Fix typo in changelog | src/dist/changelog.txt | @@ -43,7 +43,7 @@ Changes in version 3.2 RC1 (2012-11-02)
* the Jackson message converters now include "application/*+json" in supported media types (SPR-7905)
* DispatcherPortlet uses a forward for rendering a view as resource response (SPR-9876)
* prevent duplicate @Import processing and ImportBeanDefinitionRegistrar invocation (SPR-9925)
-* throw AopInvocationException on advise returning null for primitive type (SPR-4675)
+* throw AopInvocationException on advice returning null for primitive type (SPR-4675)
* resolve Collection element types during conversion (SPR-9257)
* allow SpEL reserved words in type package names (SPR-9862)
* provide alternative message code resolver styles (SPR-9707) | false |
Other | spring-projects | spring-framework | 8bb19f05ea99a12ee63e03f28412d8929ed4f581.json | Fix typos in Javadoc | spring-beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java | @@ -534,7 +534,7 @@ protected void checkNameUniqueness(String beanName, List<String> aliases, Elemen
/**
* Parse the bean definition itself, without regard to name or aliases. May return
- * <code>null</code> if problems occured during the parse of the bean definition.
+ * <code>null</code> if problems occurred during the parsing of the bean definition.
*/
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, BeanDefinition containingBean) { | true |
Other | spring-projects | spring-framework | 8bb19f05ea99a12ee63e03f28412d8929ed4f581.json | Fix typos in Javadoc | spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DefaultServletHandlerConfigurer.java | @@ -30,7 +30,7 @@
/**
* Configures a request handler for serving static resources by forwarding the request to the Servlet container's
- * "default" Servlet. This is indended to be used when the Spring MVC {@link DispatcherServlet} is mapped to "/"
+ * "default" Servlet. This is intended to be used when the Spring MVC {@link DispatcherServlet} is mapped to "/"
* thus overriding the Servlet container's default handling of static resources. Since this handler is configured
* at the lowest precedence, effectively it allows all other handler mappings to handle the request, and if none
* of them do, this handler can forward it to the "default" Servlet. | true |
Other | spring-projects | spring-framework | 6d8b37d8bbce8c6e6cb4890291469c80742132f7.json | Prevent duplicate @Import processing
Refactor ConfigurationClassParser to recursively find values from
all @Import annotations, combining them into a single unique set.
This change prevents ImportBeanDefinitionRegistrars from being
invoked twice.
Issue: SPR-9925 | spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java | @@ -17,14 +17,13 @@
package org.springframework.context.annotation;
import java.io.IOException;
-import java.lang.annotation.Annotation;
-import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
-import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
@@ -222,10 +221,9 @@ protected AnnotationMetadata doProcessConfigurationClass(
}
// process any @Import annotations
- List<AnnotationAttributes> imports =
- findAllAnnotationAttributes(Import.class, metadata.getClassName(), true);
- for (AnnotationAttributes importAnno : imports) {
- processImport(configClass, importAnno.getStringArray("value"), true);
+ Set<String> imports = getImports(metadata.getClassName(), null, new HashSet<String>());
+ if (imports != null && !imports.isEmpty()) {
+ processImport(configClass, imports.toArray(new String[imports.size()]), true);
}
// process any @ImportResource annotations
@@ -265,45 +263,36 @@ protected AnnotationMetadata doProcessConfigurationClass(
}
/**
- * Return a list of attribute maps for all declarations of the given annotation
- * on the given annotated class using the given MetadataReaderFactory to introspect
- * annotation metadata. Meta-annotations are ordered first in the list, and if the
- * target annotation is declared directly on the class, its map of attributes will be
- * ordered last in the list.
- * @param targetAnnotation the annotation to search for, both locally and as a meta-annotation
- * @param annotatedClassName the class to inspect
- * @param classValuesAsString whether class attributes should be returned as strings
+ * Recursively collect all declared {@code @Import} values. Unlike most
+ * meta-annotations it is valid to have several {@code @Import}s declared with
+ * different values, the usual process or returning values from the first
+ * meta-annotation on a class is not sufficient.
+ * <p>For example, it is common for a {@code @Configuration} class to declare direct
+ * {@code @Import}s in addition to meta-imports originating from an {@code @Enable}
+ * annotation.
+ * @param className the class name to search
+ * @param imports the imports collected so far or {@code null}
+ * @param visited used to track visited classes to prevent infinite recursion (must not be null)
+ * @return a set of all {@link Import#value() import values} or {@code null}
+ * @throws IOException if there is any problem reading metadata from the named class
*/
- private List<AnnotationAttributes> findAllAnnotationAttributes(
- Class<? extends Annotation> targetAnnotation, String annotatedClassName,
- boolean classValuesAsString) throws IOException {
-
- List<AnnotationAttributes> allAttribs = new ArrayList<AnnotationAttributes>();
-
- MetadataReader reader = this.metadataReaderFactory.getMetadataReader(annotatedClassName);
- AnnotationMetadata metadata = reader.getAnnotationMetadata();
- String targetAnnotationType = targetAnnotation.getName();
-
- for (String annotationType : metadata.getAnnotationTypes()) {
- if (annotationType.equals(targetAnnotationType)) {
- continue;
+ private Set<String> getImports(String className, Set<String> imports,
+ Set<String> visited) throws IOException {
+ if (visited.add(className)) {
+ AnnotationMetadata metadata = metadataReaderFactory.getMetadataReader(className).getAnnotationMetadata();
+ Map<String, Object> attributes = metadata.getAnnotationAttributes(Import.class.getName(), true);
+ if (attributes != null) {
+ String[] value = (String[]) attributes.get("value");
+ if (value != null && value.length > 0) {
+ imports = (imports == null ? new LinkedHashSet<String>() : imports);
+ imports.addAll(Arrays.asList(value));
+ }
}
- AnnotationMetadata metaAnnotations =
- this.metadataReaderFactory.getMetadataReader(annotationType).getAnnotationMetadata();
- AnnotationAttributes targetAttribs =
- AnnotationAttributes.fromMap(metaAnnotations.getAnnotationAttributes(targetAnnotationType, classValuesAsString));
- if (targetAttribs != null) {
- allAttribs.add(targetAttribs);
+ for (String annotationType : metadata.getAnnotationTypes()) {
+ getImports(annotationType, imports, visited);
}
}
-
- AnnotationAttributes localAttribs =
- AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(targetAnnotationType, classValuesAsString));
- if (localAttribs != null) {
- allAttribs.add(localAttribs);
- }
-
- return allAttribs;
+ return imports;
}
private void processImport(ConfigurationClass configClass, String[] classesToImport, boolean checkForCircularImports) throws IOException {
@@ -440,5 +429,4 @@ public CircularImportProblem(ConfigurationClass attemptedImport, Stack<Configura
new Location(importStack.peek().getResource(), metadata));
}
}
-
} | true |
Other | spring-projects | spring-framework | 6d8b37d8bbce8c6e6cb4890291469c80742132f7.json | Prevent duplicate @Import processing
Refactor ConfigurationClassParser to recursively find values from
all @Import annotations, combining them into a single unique set.
This change prevents ImportBeanDefinitionRegistrars from being
invoked twice.
Issue: SPR-9925 | spring-context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java | @@ -25,10 +25,14 @@
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
+import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;
+import org.springframework.beans.factory.support.BeanDefinitionRegistry;
+import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor;
+import org.springframework.util.Assert;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
@@ -77,6 +81,24 @@ public void indirectlyAnnotatedWithImport() {
assertThat(foo, is("xyz"));
}
+ @Test
+ public void importRegistrar() throws Exception {
+ ImportedRegistrar.called = false;
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
+ ctx.register(ImportingRegistrarConfig.class);
+ ctx.refresh();
+ assertNotNull(ctx.getBean("registrarImportedBean"));
+ }
+
+ @Test
+ public void importRegistrarWithImport() throws Exception {
+ ImportedRegistrar.called = false;
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
+ ctx.register(ImportingRegistrarConfigWithImport.class);
+ ctx.refresh();
+ assertNotNull(ctx.getBean("registrarImportedBean"));
+ assertNotNull(ctx.getBean(ImportedConfig.class));
+ }
@Configuration
@Import(ImportedConfig.class)
@@ -131,4 +153,35 @@ public Object postProcessAfterInitialization(Object bean, String beanName) throw
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
}
}
+
+ @Configuration
+ @EnableImportRegistrar
+ static class ImportingRegistrarConfig {
+ }
+
+ @Configuration
+ @EnableImportRegistrar
+ @Import(ImportedConfig.class)
+ static class ImportingRegistrarConfigWithImport {
+ }
+
+ @Target(ElementType.TYPE)
+ @Retention(RetentionPolicy.RUNTIME)
+ @Import(ImportedRegistrar.class)
+ public @interface EnableImportRegistrar {
+ }
+
+ static class ImportedRegistrar implements ImportBeanDefinitionRegistrar {
+
+ static boolean called;
+
+ public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
+ BeanDefinitionRegistry registry) {
+ BeanDefinition beanDefinition = new GenericBeanDefinition();
+ beanDefinition.setBeanClassName(String.class.getName());
+ registry.registerBeanDefinition("registrarImportedBean", beanDefinition );
+ Assert.state(called == false, "ImportedRegistrar called twice");
+ called = true;
+ }
+ }
} | true |
Other | spring-projects | spring-framework | 4036ffc4d4f62626208dccc63ffdefc112d4ed1c.json | Improve #toString for AnnotationAttributes
Improve the #toString method for AnnotationAttributes to print array
values as a comma-separated list. This change is primarily to provide
better variable inspection when debugging code within an IDE. | spring-core/src/main/java/org/springframework/core/annotation/AnnotationAttributes.java | @@ -18,10 +18,12 @@
import static java.lang.String.format;
+import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.util.Assert;
+import org.springframework.util.StringUtils;
/**
* {@link LinkedHashMap} subclass representing annotation attribute key/value pairs
@@ -129,4 +131,28 @@ private <T> T doGet(String attributeName, Class<T> expectedType) {
attributeName, value.getClass().getSimpleName(), expectedType.getSimpleName()));
return (T) value;
}
-}
\ No newline at end of file
+
+ public String toString() {
+ Iterator<Map.Entry<String, Object>> entries = entrySet().iterator();
+ StringBuilder sb = new StringBuilder("{");
+ while (entries.hasNext()) {
+ Map.Entry<String, Object> entry = entries.next();
+ sb.append(entry.getKey());
+ sb.append('=');
+ sb.append(valueToString(entry.getValue()));
+ sb.append(entries.hasNext() ? ", " : "");
+ }
+ sb.append("}");
+ return sb.toString();
+ }
+
+ private String valueToString(Object value) {
+ if (value == this) {
+ return "(this Map)";
+ }
+ if (value instanceof Object[]) {
+ return "[" + StringUtils.arrayToCommaDelimitedString((Object[]) value) + "]";
+ }
+ return String.valueOf(value);
+ }
+} | false |
Other | spring-projects | spring-framework | 7d177ecfd4cf7c7dd148a6ccba887b259831dd77.json | Update Servlet 3.0 dependency in webmvc pom | org.springframework.web.servlet/pom.xml | @@ -56,9 +56,9 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>3.0</version>
+ <groupId>org.apache.tomcat</groupId>
+ <artifactId>tomcat-servlet-api</artifactId>
+ <version>7.0.8</version>
<scope>provided</scope>
</dependency>
<dependency> | false |
Other | spring-projects | spring-framework | 711b84ab06372e45d5be0e2788652367e82c7985.json | Update .core pom with jopt dependency
Issue: SPR-8482 | org.springframework.core/pom.xml | @@ -39,6 +39,13 @@
<scope>compile</scope>
<optional>true</optional>
</dependency>
+ <dependency>
+ <groupId>net.sf.jopt-simple</groupId>
+ <artifactId>jopt-simple</artifactId>
+ <version>3.0</version>
+ <scope>compile</scope>
+ <optional>true</optional>
+ </dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId> | false |
Other | spring-projects | spring-framework | 4acb0fa284ce4a6f474ba22c9b215b716d260456.json | introduced ForkJoinPoolFactoryBean for Java 7 (alternative: add new jsr166.jar to Java 6) | org.springframework.context/.classpath | @@ -30,6 +30,7 @@
<classpathentry kind="var" path="IVY_CACHE/org.aspectj/com.springsource.org.aspectj.weaver/1.6.8.RELEASE/com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar"/>
<classpathentry kind="var" path="IVY_CACHE/org.beanshell/com.springsource.bsh/2.0.0.b4/com.springsource.bsh-2.0.0.b4.jar"/>
<classpathentry kind="var" path="IVY_CACHE/org.codehaus.groovy/com.springsource.org.codehaus.groovy/1.6.5/com.springsource.org.codehaus.groovy-1.6.5.jar" sourcepath="/IVY_CACHE/org.codehaus.groovy/com.springsource.org.codehaus.groovy/1.6.5/com.springsource.org.codehaus.groovy-sources-1.6.5.jar"/>
+ <classpathentry kind="var" path="IVY_CACHE/org.codehaus.jsr166-mirror/com.springsource.jsr166/1.7.0/com.springsource.jsr166-1.7.0.jar" sourcepath="/IVY_CACHE/org.codehaus.jsr166-mirror/com.springsource.jsr166/1.7.0/com.springsource.jsr166-sources-1.7.0.jar"/>
<classpathentry kind="var" path="IVY_CACHE/org.hamcrest/com.springsource.org.hamcrest/1.1.0/com.springsource.org.hamcrest-1.1.0.jar" sourcepath="/IVY_CACHE/org.hamcrest/1.1.0/com.springsource.org.hamcrest-1.1.0.jar"/>
<classpathentry kind="var" path="IVY_CACHE/org.easymock/com.springsource.org.easymock/2.5.1/com.springsource.org.easymock-2.5.1.jar" sourcepath="/IVY_CACHE/org.easymock/com.springsource.org.easymock/2.5.1/com.springsource.org.easymock-sources-2.5.1.jar"/>
<classpathentry kind="var" path="IVY_CACHE/org.joda/com.springsource.org.joda.time/1.6.0/com.springsource.org.joda.time-1.6.0.jar" sourcepath="/IVY_CACHE/org.joda/com.springsource.org.joda.time/1.6.0/com.springsource.org.joda.time-sources-1.6.0.jar"/> | true |
Other | spring-projects | spring-framework | 4acb0fa284ce4a6f474ba22c9b215b716d260456.json | introduced ForkJoinPoolFactoryBean for Java 7 (alternative: add new jsr166.jar to Java 6) | org.springframework.context/context.iml | @@ -102,6 +102,28 @@
</SOURCES>
</library>
</orderEntry>
+ <orderEntry type="module-library">
+ <library>
+ <CLASSES>
+ <root url="jar://$IVY_CACHE$/org.codehaus.jsr166-mirror/com.springsource.jsr166/1.7.0/com.springsource.jsr166-1.7.0.jar!/" />
+ </CLASSES>
+ <JAVADOC />
+ <SOURCES>
+ <root url="jar://$IVY_CACHE$/org.codehaus.jsr166-mirror/com.springsource.jsr166/1.7.0/com.springsource.jsr166-sources-1.7.0.jar!/" />
+ </SOURCES>
+ </library>
+ </orderEntry>
+ <orderEntry type="module-library">
+ <library>
+ <CLASSES>
+ <root url="jar://$IVY_CACHE$/net.sourceforge.ehcache/com.springsource.net.sf.ehcache/1.6.2/com.springsource.net.sf.ehcache-1.6.2.jar!/" />
+ </CLASSES>
+ <JAVADOC />
+ <SOURCES>
+ <root url="jar://$IVY_CACHE$/net.sourceforge.ehcache/com.springsource.net.sf.ehcache/1.6.2/com.springsource.net.sf.ehcache-sources-1.6.2.jar!/" />
+ </SOURCES>
+ </library>
+ </orderEntry>
<orderEntry type="module-library">
<library>
<CLASSES>
@@ -155,17 +177,6 @@
</SOURCES>
</library>
</orderEntry>
- <orderEntry type="module-library">
- <library>
- <CLASSES>
- <root url="jar://$IVY_CACHE$/net.sourceforge.ehcache/com.springsource.net.sf.ehcache/1.6.2/com.springsource.net.sf.ehcache-1.6.2.jar!/" />
- </CLASSES>
- <JAVADOC />
- <SOURCES>
- <root url="jar://$IVY_CACHE$/net.sourceforge.ehcache/com.springsource.net.sf.ehcache/1.6.2/com.springsource.net.sf.ehcache-sources-1.6.2.jar!/" />
- </SOURCES>
- </library>
- </orderEntry>
</component>
<component name="copyright">
<Base>
| true |
Other | spring-projects | spring-framework | 4acb0fa284ce4a6f474ba22c9b215b716d260456.json | introduced ForkJoinPoolFactoryBean for Java 7 (alternative: add new jsr166.jar to Java 6) | org.springframework.context/ivy.xml | @@ -50,6 +50,7 @@
<dependency org="org.aspectj" name="com.springsource.org.aspectj.weaver" rev="${aspectj.version}" conf="optional, aspectj->compile"/>
<dependency org="org.beanshell" name="com.springsource.bsh" rev="2.0.0.b4" conf="optional, beanshell->compile"/>
<dependency org="org.codehaus.groovy" name="com.springsource.org.codehaus.groovy" rev="1.6.5" conf="optional, groovy->compile"/>
+ <dependency org="org.codehaus.jsr166-mirror" name="com.springsource.jsr166" rev="1.7.0" conf="provided->compile"/>
<dependency org="org.hibernate" name="com.springsource.org.hibernate.validator" rev="4.1.0.GA" conf="optional->compile"/>
<dependency org="org.joda" name="com.springsource.org.joda.time" rev="1.6.0" conf="optional->compile"/>
<dependency org="org.jruby" name="com.springsource.org.jruby" rev="1.4.0" conf="optional, jruby->compile"/> | true |
Other | spring-projects | spring-framework | 4acb0fa284ce4a6f474ba22c9b215b716d260456.json | introduced ForkJoinPoolFactoryBean for Java 7 (alternative: add new jsr166.jar to Java 6) | org.springframework.context/src/main/java/org/springframework/scheduling/concurrent/ForkJoinPoolFactoryBean.java | @@ -0,0 +1,108 @@
+/*
+ * Copyright 2002-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.scheduling.concurrent;
+
+import java.util.concurrent.ForkJoinPool;
+
+import org.springframework.beans.factory.DisposableBean;
+import org.springframework.beans.factory.FactoryBean;
+import org.springframework.beans.factory.InitializingBean;
+
+/**
+ * A Spring {@link FactoryBean} that builds and exposes a preconfigured {@link ForkJoinPool}.
+ * May be used on Java 7 as well as on Java 6 with <code>jsr166.jar</code> on the classpath
+ * (ideally on the VM bootstrap classpath).
+ *
+ * <p>For details on the ForkJoinPool API and its its use with RecursiveActions, see the
+ * <a href="http://download.java.net/jdk7/docs/api/java/util/concurrent/ForkJoinPool.html">JDK 7 javadoc</a>.
+ *
+ * <p><code>jsr166.jar</code>, containing <code>java.util.concurrent</code> updates for Java 6, can be obtained
+ * from the <a href="http://gee.cs.oswego.edu/dl/concurrency-interest/">concurrency interest website</a>.
+ *
+ * @author Juergen Hoeller
+ * @since 3.1
+ */
+public class ForkJoinPoolFactoryBean implements FactoryBean<ForkJoinPool>, InitializingBean, DisposableBean {
+
+ private int parallelism = Runtime.getRuntime().availableProcessors();
+
+ private ForkJoinPool.ForkJoinWorkerThreadFactory threadFactory = ForkJoinPool.defaultForkJoinWorkerThreadFactory;
+
+ private Thread.UncaughtExceptionHandler uncaughtExceptionHandler;
+
+ private boolean asyncMode = false;
+
+ private ForkJoinPool forkJoinPool;
+
+
+ /**
+ * Specify the parallelism level. Default is {@link Runtime#availableProcessors()}.
+ */
+ public void setParallelism(int parallelism) {
+ this.parallelism = parallelism;
+ }
+
+ /**
+ * Set the factory for creating new ForkJoinWorkerThreads.
+ * Default is {@link ForkJoinPool#defaultForkJoinWorkerThreadFactory}.
+ */
+ public void setThreadFactory(ForkJoinPool.ForkJoinWorkerThreadFactory threadFactory) {
+ this.threadFactory = threadFactory;
+ }
+
+ /**
+ * Set the handler for internal worker threads that terminate due to unrecoverable errors
+ * encountered while executing tasks. Default is none.
+ */
+ public void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler uncaughtExceptionHandler) {
+ this.uncaughtExceptionHandler = uncaughtExceptionHandler;
+ }
+
+ /**
+ * Specify whether to establish a local first-in-first-out scheduling mode for forked tasks
+ * that are never joined. This mode (asyncMode = <code>true</code>) may be more appropriate
+ * than the default locally stack-based mode in applications in which worker threads only
+ * process event-style asynchronous tasks. Default is <code>false</code>.
+ */
+ public void setAsyncMode(boolean asyncMode) {
+ this.asyncMode = asyncMode;
+ }
+
+ public void afterPropertiesSet() {
+ this.forkJoinPool =
+ new ForkJoinPool(this.parallelism, this.threadFactory, this.uncaughtExceptionHandler, this.asyncMode);
+ }
+
+
+ public ForkJoinPool getObject() {
+ return this.forkJoinPool;
+ }
+
+ public Class<?> getObjectType() {
+ return ForkJoinPool.class;
+ }
+
+ public boolean isSingleton() {
+ return true;
+ }
+
+
+ public void destroy() {
+ this.forkJoinPool.shutdown();
+ }
+
+}
| true |
Other | spring-projects | spring-framework | 3ead3cf8592a6eaf84511a26cda303b250f80db7.json | Improve wording of scoped-proxy example in ref doc
Issue: SPR-8591 | spring-framework-reference/src/beans-scopes.xml | @@ -405,7 +405,7 @@
<lineannotation><!-- an HTTP <interfacename>Session</interfacename>-scoped bean exposed as a proxy --></lineannotation>
<bean id="userPreferences" class="com.foo.UserPreferences" <emphasis role="bold">scope="session"</emphasis>>
- <lineannotation><!-- this next element effects the proxying of the surrounding bean --></lineannotation>
+ <lineannotation><!-- instructs the container to proxy the surrounding bean --></lineannotation>
<emphasis role="bold"><aop:scoped-proxy/></emphasis>
</bean>
| false |
Other | spring-projects | spring-framework | 47f45ff7435cc9be7a2ad0fbfe6e65312f348599.json | SPR-8585: add generic composite filter | org.springframework.web/src/main/java/org/springframework/web/filter/CompositeFilter.java | @@ -0,0 +1,108 @@
+/*
+ * Copyright 2002-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.web.filter;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+/**
+ * A generic composite servlet {@link Filter} that just delegates its behaviour to a chain (list) of user supplied
+ * filters, achieving the functionality of a {@link FilterChain}, but conveniently using only {@link Filter} instances.
+ * This is useful for filters that require dependency injection, and can therefore be set up in a Spring application
+ * context. Typically this composite would be used in conjunction with {@link DelegatingFilterProxy}, so that it can be
+ * declared in Spring but applied to a servlet context.
+ *
+ * @since 3.1
+ *
+ * @author Dave Syer
+ *
+ */
+public class CompositeFilter implements Filter {
+
+ private List<? extends Filter> filters = new ArrayList<Filter>();
+
+ public void setFilters(List<? extends Filter> filters) {
+ this.filters = new ArrayList<Filter>(filters);
+ }
+
+ /**
+ * Clean up all the filters supplied, calling each one's destroy method in turn, but in reverse order.
+ *
+ * @see Filter#init(FilterConfig)
+ */
+ public void destroy() {
+ for (int i = filters.size(); i-- > 0;) {
+ Filter filter = filters.get(i);
+ filter.destroy();
+ }
+ }
+
+ /**
+ * Initialize all the filters, calling each one's init method in turn in the order supplied.
+ *
+ * @see Filter#init(FilterConfig)
+ */
+ public void init(FilterConfig config) throws ServletException {
+ for (Filter filter : filters) {
+ filter.init(config);
+ }
+ }
+
+ /**
+ * Forms a temporary chain from the list of delegate filters supplied ({@link #setFilters(List)}) and executes them
+ * in order. Each filter delegates to the next one in the list, achieving the normal behaviour of a
+ * {@link FilterChain}, despite the fact that this is a {@link Filter}.
+ *
+ * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
+ */
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
+ ServletException {
+ new VirtualFilterChain(chain, filters).doFilter(request, response);
+ }
+
+ private static class VirtualFilterChain implements FilterChain {
+ private final FilterChain originalChain;
+ private final List<? extends Filter> additionalFilters;
+ private int currentPosition = 0;
+
+ private VirtualFilterChain(FilterChain chain, List<? extends Filter> additionalFilters) {
+ this.originalChain = chain;
+ this.additionalFilters = additionalFilters;
+ }
+
+ public void doFilter(final ServletRequest request, final ServletResponse response) throws IOException,
+ ServletException {
+ if (currentPosition == additionalFilters.size()) {
+ originalChain.doFilter(request, response);
+ } else {
+ currentPosition++;
+ Filter nextFilter = additionalFilters.get(currentPosition - 1);
+ nextFilter.doFilter(request, response, this);
+ }
+ }
+
+ }
+
+} | true |
Other | spring-projects | spring-framework | 47f45ff7435cc9be7a2ad0fbfe6e65312f348599.json | SPR-8585: add generic composite filter | org.springframework.web/src/test/java/org/springframework/web/filter/CompositeFilterTests.java | @@ -0,0 +1,87 @@
+/*
+ * Copyright 2004, 2005 Acegi Technology Pty Limited
+ * Copyright 2006-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.web.filter;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+import org.junit.Test;
+import org.springframework.mock.web.MockFilterConfig;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+import org.springframework.mock.web.MockServletContext;
+
+/**
+ * @author Dave Syer
+ */
+public class CompositeFilterTests {
+
+ @Test
+ public void testCompositeFilter() throws ServletException, IOException {
+ ServletContext sc = new MockServletContext();
+
+ MockFilter targetFilter = new MockFilter();
+
+ MockFilterConfig proxyConfig = new MockFilterConfig(sc);
+
+ CompositeFilter filterProxy = new CompositeFilter();
+ filterProxy.setFilters(Arrays.asList(targetFilter));
+ filterProxy.init(proxyConfig);
+
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ MockHttpServletResponse response = new MockHttpServletResponse();
+ filterProxy.doFilter(request, response, null);
+
+ assertNotNull(targetFilter.filterConfig);
+ assertEquals(Boolean.TRUE, request.getAttribute("called"));
+
+ filterProxy.destroy();
+ assertNull(targetFilter.filterConfig);
+ }
+
+
+ public static class MockFilter implements Filter {
+
+ public FilterConfig filterConfig;
+
+ public void init(FilterConfig filterConfig) throws ServletException {
+ this.filterConfig = filterConfig;
+ }
+
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
+ request.setAttribute("called", Boolean.TRUE);
+ }
+
+ public void destroy() {
+ this.filterConfig = null;
+ }
+ }
+
+} | true |
Other | spring-projects | spring-framework | 0c0ab97a84b8c99a259d8f316f6a16dcbe151ead.json | Switch servlet dependency to a public one | org.springframework.web/pom.xml | @@ -1,6 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
+<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
@@ -46,9 +45,9 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>3.0</version>
+ <groupId>org.apache.tomcat</groupId>
+ <artifactId>tomcat-servlet-api</artifactId>
+ <version>7.0.8</version>
<scope>provided</scope>
</dependency>
<dependency> | false |
Other | spring-projects | spring-framework | 11597c906dce28820ab323ac62f5a61f5ee9397f.json | Fix typo in reference documentation
Issue: SPR-8579 | spring-framework-reference/src/beans-dependencies.xml | @@ -366,7 +366,7 @@ public class ExampleBean {
set, and the relevant lifecycle methods (such as a <link
linkend="beans-factory-lifecycle-initializingbean">configured init
method</link> or the <link
- linkend="beans-factory-lifecycle-initializingbean">IntializingBean
+ linkend="beans-factory-lifecycle-initializingbean">InitializingBean
callback method</link>) are invoked.</para>
</section>
| false |
Other | spring-projects | spring-framework | 6404440cbf216111b4643e6cf5667b7e64fef9b5.json | Fix typo in SmartLifecycle Javadoc
Issue: SPR-8570 | org.springframework.context/src/main/java/org/springframework/context/SmartLifecycle.java | @@ -73,7 +73,7 @@ public interface SmartLifecycle extends Lifecycle, Phased {
* the SmartLifecycle component does indeed stop.
* <p>The {@code LifecycleProcessor} will call <i>only</i> this variant of the
* {@code stop} method; i.e. {@link Lifecycle#stop()} will not be called for
- * {@link SmartLifecycle} implementations unless explicitly delegated to within the
+ * {@link SmartLifecycle} implementations unless explicitly delegated to within
* this method.
*/
void stop(Runnable callback); | false |
Other | spring-projects | spring-framework | 18d8876dc8330ac816473aad1139b94be53c1794.json | Update RouterFunctionExtensions documentation | spring-webflux/src/main/kotlin/org/springframework/web/reactive/function/server/RouterFunctionExtensions.kt | @@ -22,29 +22,25 @@ import org.springframework.http.MediaType
import reactor.core.publisher.Mono
/**
- * Provide a routing DSL for [RouterFunctions] and [RouterFunction] in order to be able to
- * write idiomatic Kotlin code as below:
+ * Provide a [RouterFunction] Kotlin DSL in order to be able to write idiomatic Kotlin code as below:
*
* ```kotlin
*
- * @Controller
- * class FooController : RouterFunction<ServerResponse> {
+ * @Configuration
+ * class ApplicationRoutes(val userHandler: UserHandler) {
*
- * override fun route(req: ServerRequest) = route(req) {
- * accept(TEXT_HTML).apply {
- * (GET("/user/") or GET("/users/")) { findAllView() }
- * GET("/user/{login}", this@FooController::findViewById)
+ * @Bean
+ * fun mainRouter() = router {
+ * accept(TEXT_HTML).nest {
+ * (GET("/user/") or GET("/users/")).invoke(userHandler::findAllView)
+ * GET("/users/{login}", userHandler::findViewById)
* }
- * accept(APPLICATION_JSON).apply {
- * (GET("/api/user/") or GET("/api/users/")) { findAll() }
- * POST("/api/user/", this@FooController::create)
+ * accept(APPLICATION_JSON).nest {
+ * (GET("/api/user/") or GET("/api/users/")).invoke(userHandler::findAll)
+ * POST("/api/users/", userHandler::create)
* }
* }
*
- * fun findAllView() = ...
- * fun findViewById(req: ServerRequest) = ...
- * fun findAll() = ...
- * fun create(req: ServerRequest) =
* }
* ```
* | false |
Other | spring-projects | spring-framework | bf6e7d0c26199d65d840a081cba4d20ada78dcc5.json | Update copyright header
Closes gh-1382 | spring-aop/src/main/java/org/springframework/aop/framework/adapter/AfterReturningAdviceInterceptor.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. | false |
Other | spring-projects | spring-framework | 9a9166622eb08e5445ae64daea7ada56fd735d41.json | Fix ForwardedHeaderFilter getRequestURL()
Previously ForwardedHeaderFilter would return the same StringBuffer for every invocation. This
meant that users that modified the StringBuffer changed the state of the HttpServletRequest.
This commit ensures that a new StringBuffer is always returned for ForwardedHeaderFilter.
Issue: SPR-15423 | spring-web/src/main/java/org/springframework/web/filter/ForwardedHeaderFilter.java | @@ -118,7 +118,7 @@ private static class ForwardedHeaderRequestWrapper extends HttpServletRequestWra
private final String requestUri;
- private final StringBuffer requestUrl;
+ private final String requestUrl;
private final Map<String, List<String>> headers;
@@ -137,8 +137,8 @@ public ForwardedHeaderRequestWrapper(HttpServletRequest request, UrlPathHelper p
String prefix = getForwardedPrefix(request);
this.contextPath = (prefix != null ? prefix : request.getContextPath());
this.requestUri = this.contextPath + pathHelper.getPathWithinApplication(request);
- this.requestUrl = new StringBuffer(this.scheme + "://" + this.host +
- (port == -1 ? "" : ":" + port) + this.requestUri);
+ this.requestUrl = this.scheme + "://" + this.host +
+ (port == -1 ? "" : ":" + port) + this.requestUri;
this.headers = initHeaders(request);
}
@@ -206,7 +206,7 @@ public String getRequestURI() {
@Override
public StringBuffer getRequestURL() {
- return this.requestUrl;
+ return new StringBuffer(this.requestUrl);
}
// Override header accessors to not expose forwarded headers | true |
Other | spring-projects | spring-framework | 9a9166622eb08e5445ae64daea7ada56fd735d41.json | Fix ForwardedHeaderFilter getRequestURL()
Previously ForwardedHeaderFilter would return the same StringBuffer for every invocation. This
meant that users that modified the StringBuffer changed the state of the HttpServletRequest.
This commit ensures that a new StringBuffer is always returned for ForwardedHeaderFilter.
Issue: SPR-15423 | spring-web/src/test/java/org/springframework/web/filter/ForwardedHeaderFilterTests.java | @@ -204,6 +204,16 @@ public void requestUriWithForwardedPrefixTrailingSlash() throws Exception {
HttpServletRequest actual = filterAndGetWrappedRequest();
assertEquals("http://localhost/prefix/mvc-showcase", actual.getRequestURL().toString());
}
+
+ @Test
+ public void requestURLNewStringBuffer() throws Exception {
+ this.request.addHeader(X_FORWARDED_PREFIX, "/prefix/");
+ this.request.setRequestURI("/mvc-showcase");
+
+ HttpServletRequest actual = filterAndGetWrappedRequest();
+ actual.getRequestURL().append("?key=value");
+ assertEquals("http://localhost/prefix/mvc-showcase", actual.getRequestURL().toString());
+ }
@Test
public void contextPathWithForwardedPrefix() throws Exception { | true |
Other | spring-projects | spring-framework | b245918574024f4f0e576d984d3b336905d920e1.json | Fix compiler warning | spring-webflux/src/main/java/org/springframework/web/reactive/result/view/HttpMessageWriterView.java | @@ -117,12 +117,7 @@ public final Set<String> getModelKeys() {
@SuppressWarnings("unchecked")
public Mono<Void> render(Map<String, ?> model, MediaType contentType, ServerWebExchange exchange) {
return getObjectToRender(model)
- .map(value -> {
- Publisher stream = Mono.justOrEmpty(value);
- ResolvableType type = ResolvableType.forClass(value.getClass());
- ServerHttpResponse response = exchange.getResponse();
- return this.writer.write(stream, type, contentType, response, Collections.emptyMap());
- })
+ .map(value -> write(value, contentType, exchange))
.orElseGet(() -> exchange.getResponse().setComplete());
}
@@ -158,4 +153,12 @@ private boolean isMatch(Map.Entry<String, ?> entry) {
return getMessageWriter().canWrite(type, null);
}
+ @SuppressWarnings("unchecked")
+ private <T> Mono<Void> write(T value, MediaType contentType, ServerWebExchange exchange) {
+ Publisher<T> input = Mono.justOrEmpty(value);
+ ResolvableType elementType = ResolvableType.forClass(value.getClass());
+ return ((HttpMessageWriter<T>) this.writer).write(
+ input, elementType, contentType, exchange.getResponse(), Collections.emptyMap());
+ }
+
} | false |
Other | spring-projects | spring-framework | 68cc57549a56480b723b6112e1bee0de114eeda1.json | Restore correct order of terminated flag check | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ReactiveTypeHandler.java | @@ -274,7 +274,10 @@ public void run() {
this.elementRef.lazySet(null);
return;
}
-
+
+ // Check terminal signal before processing element..
+ boolean isTerminated = this.terminated;
+
Object element = this.elementRef.get();
if (element != null) {
this.elementRef.lazySet(null);
@@ -291,7 +294,7 @@ public void run() {
}
}
- if (this.terminated) {
+ if (isTerminated) {
this.done = true;
Throwable ex = this.error;
this.error = null; | false |
Other | spring-projects | spring-framework | c7c480610cae60434ffe8f6d496d04157f5e57f6.json | Polish doc changes | src/docs/asciidoc/web/web-mvc.adoc | @@ -2544,14 +2544,15 @@ Reactor 3, RxJava 2, and RxJava 1. Note that for RxJava 1 you will need to add
https://github.com/ReactiveX/RxJavaReactiveStreams["io.reactivex:rxjava-reactive-streams"]
to the classpath.
-A common assumption with reactive libraries is not block the processing thread.
+A common assumption with reactive libraries is to not block the processing thread.
The `WebClient` with Reactor Netty for example is based on event-loop style
handling using a small, fixed number of threads and those must not be blocked
when writing to the `ServletResponseOutputStream`. Reactive libraries have
operators for that but Spring MVC automatically writes asynchronously so you
-don't need to use that. The underlying `TaskExecutor` for this can be configured
+don't need to use them. The underlying `TaskExecutor` for this must be configured
through the MVC Java config and the MVC namespace as described in the following
-section.
+section which by default is a `SyncTaskExecutor` and hence not suitable for
+production use.
[NOTE]
==== | false |
Other | spring-projects | spring-framework | ae2306326edfbb8485e2b9a785189ab78cbc80a2.json | Add RxJava1 Reactive Streams adapters check | spring-core/src/main/java/org/springframework/core/ReactiveAdapterRegistry.java | @@ -28,6 +28,7 @@
import reactor.core.publisher.Mono;
import rx.RxReactiveStreams;
+import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import static org.springframework.core.ReactiveTypeDescriptor.*;
@@ -52,7 +53,7 @@ public class ReactiveAdapterRegistry {
private static final boolean rxJava1Present =
ClassUtils.isPresent("rx.Observable", ReactiveAdapterRegistry.class.getClassLoader());
- private static final boolean rxJava1Adapter =
+ private static final boolean rxReactiveStreamsPresent =
ClassUtils.isPresent("rx.RxReactiveStreams", ReactiveAdapterRegistry.class.getClassLoader());
private static final boolean rxJava2Present =
@@ -69,7 +70,7 @@ public ReactiveAdapterRegistry() {
if (reactorPresent) {
new ReactorRegistrar().registerAdapters(this);
}
- if (rxJava1Present && rxJava1Adapter) {
+ if (rxJava1Present && rxReactiveStreamsPresent) {
new RxJava1Registrar().registerAdapters(this);
}
if (rxJava2Present) {
@@ -120,13 +121,17 @@ public ReactiveAdapter getAdapter(Class<?> reactiveType) {
* (i.e. to adapt from; may be {@code null} if the reactive type is specified)
*/
public ReactiveAdapter getAdapter(Class<?> reactiveType, Object source) {
+
Object sourceToUse = (source instanceof Optional ? ((Optional<?>) source).orElse(null) : source);
Class<?> clazz = (sourceToUse != null ? sourceToUse.getClass() : reactiveType);
-
if (clazz == null) {
return null;
}
+ Assert.isTrue(!rxJava1Present || rxReactiveStreamsPresent || !clazz.getName().startsWith("rx."),
+ "For RxJava 1.x adapter support please add " +
+ "\"io.reactivex:rxjava-reactive-streams\": " + clazz.getName());
+
return this.adapters.stream()
.filter(adapter -> adapter.getReactiveType() == clazz)
.findFirst() | false |
Other | spring-projects | spring-framework | 279c56a385d9fae56a82531e4bfeed118880a80a.json | Fix typo in JavaDoc | spring-context/src/main/java/org/springframework/format/annotation/DateTimeFormat.java | @@ -26,7 +26,7 @@
* Declares that a field should be formatted as a date time.
*
* <p>Supports formatting by style pattern, ISO date time pattern, or custom format pattern string.
- * Can be applied to {@code java.util.Date}, {@code java.util.Calendar}, {@code java.long.Long},
+ * Can be applied to {@code java.util.Date}, {@code java.util.Calendar}, {@code java.lang.Long},
* Joda-Time value types; and as of Spring 4 and JDK 8, to JSR-310 <code>java.time</code> types too.
*
* <p>For style-based formatting, set the {@link #style} attribute to be the style pattern code. | false |
Other | spring-projects | spring-framework | 37f9c8675804d4282bed9d2d1fb9da9761aee86a.json | Fix failing tests due to last commit | spring-core/src/main/java/org/springframework/core/ReactiveAdapterRegistry.java | @@ -123,7 +123,7 @@ public ReactiveAdapter getAdapter(Class<?> reactiveType, Object source) {
Object sourceToUse = (source instanceof Optional ? ((Optional<?>) source).orElse(null) : source);
Class<?> clazz = (sourceToUse != null ? sourceToUse.getClass() : reactiveType);
- if (reactiveType == null) {
+ if (clazz == null) {
return null;
}
| false |
Other | spring-projects | spring-framework | 272f14513215150dbc104fdb4b67c0e07cb28370.json | Clarify Lifecycle#stop documentation
Issue: SPR-8570 | org.springframework.context/src/main/java/org/springframework/context/SmartLifecycle.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,7 +17,7 @@
package org.springframework.context;
/**
- * An extension of the Lifecycle interface for those objects that require to be
+ * An extension of the {@link Lifecycle} interface for those objects that require to be
* started upon ApplicationContext refresh and/or shutdown in a particular order.
* The {@link #isAutoStartup()} return value indicates whether this object should
* be started at the time of a context refresh. The callback-accepting
@@ -67,10 +67,14 @@ public interface SmartLifecycle extends Lifecycle, Phased {
/**
* Indicates that a Lifecycle component must stop if it is currently running.
- * <p>The provided callback is used by the LifecycleProcessor to support an
+ * <p>The provided callback is used by the {@link LifecycleProcessor} to support an
* ordered, and potentially concurrent, shutdown of all components having a
* common shutdown order value. The callback <b>must</b> be executed after
* the SmartLifecycle component does indeed stop.
+ * <p>The {@code LifecycleProcessor} will call <i>only</i> this variant of the
+ * {@code stop} method; i.e. {@link Lifecycle#stop()} will not be called for
+ * {@link SmartLifecycle} implementations unless explicitly delegated to within the
+ * this method.
*/
void stop(Runnable callback);
| false |
Other | spring-projects | spring-framework | 30f363bbc9b55e51e8576033cf91dc3f43bc7260.json | copy css and js resources as well | spring-framework.ipr | @@ -219,6 +219,8 @@
<entry name="*.jpeg" />
<entry name="*.jpg" />
<entry name="*.html" />
+ <entry name="*.css" />
+ <entry name="*.js" />
<entry name="*.dtd" />
<entry name="*.xsd" />
<entry name="*.tld" />
| false |
Other | spring-projects | spring-framework | f800a026cbbcdd9b2ada349126e67eb71e0d77b1.json | Fix typo in MVC docs | spring-framework-reference/src/mvc.xml | @@ -29,7 +29,7 @@
<para>Some methods in the core classes of Spring Web MVC are marked
<literal>final</literal>. As a developer you cannot override these
methods to supply your own behavior. This has not been done arbitrarily,
- but specifically with this principal in mind.</para>
+ but specifically with this principle in mind.</para>
<para>For an explanation of this principle, refer to <emphasis>Expert
Spring Web MVC and Web Flow</emphasis> by Seth Ladd and others; | false |
Other | spring-projects | spring-framework | 10be0ef9e763d368a24a7ac466da50a2224c5d41.json | Clarify BeanFactory#containsBean Javadoc
Previously, #containsBean Javadoc advertised that a true return value
indicates that a call to #getBean for the same name would succeed.
This is actually not the case, and has never been. The semantics
of #containsBean have always been to indicate whether a bean definition
with the given name is definied or a singleton instance with the given
name has been registered.
The Javadoc now reflects this accurately.
Issue: SPR-8690 | org.springframework.beans/src/main/java/org/springframework/beans/factory/BeanFactory.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2010 the original author or authors.
+ * Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -181,12 +181,19 @@ public interface BeanFactory {
Object getBean(String name, Object... args) throws BeansException;
/**
- * Does this bean factory contain a bean with the given name? More specifically,
- * is {@link #getBean} able to obtain a bean instance for the given name?
- * <p>Translates aliases back to the corresponding canonical bean name.
- * Will ask the parent factory if the bean cannot be found in this factory instance.
+ * Does this bean factory contain a bean definition or externally registered singleton
+ * instance with the given name?
+ * <p>If the given name is an alias, it will be translated back to the corresponding
+ * canonical bean name.
+ * <p>If this factory is hierarchical, will ask any parent factory if the bean cannot
+ * be found in this factory instance.
+ * <p>If a bean definition or singleton instance matching the given name is found,
+ * this method will return {@code true} whether the named bean definition is concrete
+ * or abstract, lazy or eager, in scope or not. Therefore, note that a {@code true}
+ * return value from this method does not necessarily indicate that {@link #getBean}
+ * will be able to obtain an instance for the same name.
* @param name the name of the bean to query
- * @return whether a bean with the given name is defined
+ * @return whether a bean with the given name is present
*/
boolean containsBean(String name);
| true |
Other | spring-projects | spring-framework | 10be0ef9e763d368a24a7ac466da50a2224c5d41.json | Clarify BeanFactory#containsBean Javadoc
Previously, #containsBean Javadoc advertised that a true return value
indicates that a call to #getBean for the same name would succeed.
This is actually not the case, and has never been. The semantics
of #containsBean have always been to indicate whether a bean definition
with the given name is definied or a singleton instance with the given
name has been registered.
The Javadoc now reflects this accurately.
Issue: SPR-8690 | org.springframework.beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java | @@ -16,14 +16,17 @@
package org.springframework.beans.factory;
+import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
@@ -74,7 +77,6 @@
import org.springframework.beans.factory.xml.ConstructorDependenciesBean;
import org.springframework.beans.factory.xml.DependenciesBean;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
-import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.DefaultConversionService;
@@ -2154,6 +2156,15 @@ public Object run() {
assertEquals("user1", bean.getUserName());
}
+ @Test
+ public void testContainsBeanReturnsTrueEvenForAbstractBeanDefinition() {
+ DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
+ bf.registerBeanDefinition("abs",
+ rootBeanDefinition(TestBean.class).setAbstract(true).getBeanDefinition());
+ assertThat(bf.containsBean("abs"), is(true));
+ assertThat(bf.containsBean("bogus"), is(false));
+ }
+
public static class NoDependencies {
| true |
Other | spring-projects | spring-framework | 49b38190eeaf3861b2f0784044270b9c899ecf14.json | Fix typo in cache abstraction reference doc
Issue: SPR-8670 | spring-framework-reference/src/cache.xml | @@ -76,7 +76,7 @@ public Book findBook(ISBN isbn) {...}]]></programlisting>
is checked to see whether the invocation has been already executed and does not have to be repeated. While in most cases, only one cache is declared, the annotation allows multiple
names to be specified so that more then one cache are being used. In this case, each of the caches will be checked before executing the method - if at least one cache is hit,
then the associated value will be returned:</para>
- <note>All the other caches that do not contain the method will be updated as well event though the cached method was not actually
+ <note>All the other caches that do not contain the method will be updated as well even though the cached method was not actually
executed.</note>
<programlisting language="java"><![CDATA[@Cacheable({ "books", "isbns" })
| false |
Other | spring-projects | spring-framework | 8759b20e4601d3a3e24301e2c6502038c95b9816.json | Include javax.jdo 3.x in spring-orm template.mf
Prior to this change, spring-orm/template.mf was exclusive of javax.jdo
3.0.0. Now, after local testing against the newly-released jdo-api 3.0
jar, the template has been updated to allow for use in OSGi containers.
Note that actually updating build dependency descriptors to JDO 3.0 such
that the framework is continually tested against this version is covered
by a separate issue (SPR-8668).
Issue: SPR-8667, SPR-8655 | org.springframework.orm/template.mf | @@ -9,7 +9,7 @@ Import-Package:
org.eclipse.persistence.expressions;version="[1.0.0, 3.0.0)";resolution:=optional
Import-Template:
com.ibatis.*;version="[2.3.0, 3.0.0)";resolution:=optional,
- javax.jdo.*;version="[2.0.0, 3.0.0)";resolution:=optional,
+ javax.jdo.*;version="[2.0.0, 4.0.0)";resolution:=optional,
javax.naming.*;version="0";resolution:=optional,
javax.persistence.*;version="[1.0.0, 3.0.0)";resolution:=optional,
javax.servlet.*;version="[2.4.0, 4.0.0)";resolution:=optional, | false |
Other | spring-projects | spring-framework | 2e5f3559d3bd2f9166d3a6cde7fc4c402bc0b802.json | Fix handling of @EnableLoadTimeWeaving AUTODETECT
Issue: SPR-8643 | org.springframework.context/src/main/java/org/springframework/context/annotation/LoadTimeWeavingConfiguration.java | @@ -84,7 +84,7 @@ public LoadTimeWeaver loadTimeWeaver() {
// AJ weaving is disabled -> do nothing
break;
case AUTODETECT:
- if (this.beanClassLoader.getResource(ASPECTJ_AOP_XML_RESOURCE) != null) {
+ if (this.beanClassLoader.getResource(ASPECTJ_AOP_XML_RESOURCE) == null) {
// No aop.xml present on the classpath -> treat as 'disabled'
break;
} | true |
Other | spring-projects | spring-framework | 2e5f3559d3bd2f9166d3a6cde7fc4c402bc0b802.json | Fix handling of @EnableLoadTimeWeaving AUTODETECT
Issue: SPR-8643 | org.springframework.context/src/test/java/org/springframework/context/annotation/EnableLoadTimeWeavingTests.java | @@ -16,10 +16,17 @@
package org.springframework.context.annotation;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expectLastCall;
+import static org.easymock.EasyMock.isA;
+import static org.easymock.EasyMock.replay;
+
+import java.lang.instrument.ClassFileTransformer;
+
import org.junit.Test;
+import org.springframework.context.annotation.EnableLoadTimeWeaving.AspectJWeaving;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.instrument.classloading.LoadTimeWeaver;
-import org.springframework.instrument.classloading.SimpleLoadTimeWeaver;
/**
* Unit tests for @EnableLoadTimeWeaving
@@ -37,19 +44,61 @@ public void control() {
}
@Test
- public void test() {
+ public void enableLTW_withAjWeavingDisabled() {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
+ ctx.register(EnableLTWConfig_withAjWeavingDisabled.class);
+ ctx.refresh();
+ ctx.getBean("loadTimeWeaver");
+ }
+
+ @Test
+ public void enableLTW_withAjWeavingAutodetect() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
- ctx.register(Config.class);
+ ctx.register(EnableLTWConfig_withAjWeavingAutodetect.class);
+ ctx.refresh();
+ ctx.getBean("loadTimeWeaver");
+ }
+
+ @Test
+ public void enableLTW_withAjWeavingEnabled() {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
+ ctx.register(EnableLTWConfig_withAjWeavingEnabled.class);
ctx.refresh();
ctx.getBean("loadTimeWeaver");
}
@Configuration
- @EnableLoadTimeWeaving
- static class Config implements LoadTimeWeavingConfigurer {
+ @EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.DISABLED)
+ static class EnableLTWConfig_withAjWeavingDisabled implements LoadTimeWeavingConfigurer {
+ public LoadTimeWeaver getLoadTimeWeaver() {
+ LoadTimeWeaver mockLTW = createMock(LoadTimeWeaver.class);
+ // no expectations -> a class file transformer should NOT be added
+ replay(mockLTW);
+ return mockLTW;
+ }
+ }
+ @Configuration
+ @EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.AUTODETECT)
+ static class EnableLTWConfig_withAjWeavingAutodetect implements LoadTimeWeavingConfigurer {
+ public LoadTimeWeaver getLoadTimeWeaver() {
+ LoadTimeWeaver mockLTW = createMock(LoadTimeWeaver.class);
+ // no expectations -> a class file transformer should NOT be added
+ // because no META-INF/aop.xml is present on the classpath
+ replay(mockLTW);
+ return mockLTW;
+ }
+ }
+
+ @Configuration
+ @EnableLoadTimeWeaving(aspectjWeaving=AspectJWeaving.ENABLED)
+ static class EnableLTWConfig_withAjWeavingEnabled implements LoadTimeWeavingConfigurer {
public LoadTimeWeaver getLoadTimeWeaver() {
- return new SimpleLoadTimeWeaver();
+ LoadTimeWeaver mockLTW = createMock(LoadTimeWeaver.class);
+ mockLTW.addTransformer(isA(ClassFileTransformer.class));
+ expectLastCall();
+ replay(mockLTW);
+ return mockLTW;
}
}
} | true |
Other | spring-projects | spring-framework | 4e522c0cc36f5d506d01e1906c70f1151bddf1b7.json | Fix Javadoc error in JdbcOperations
Issue: SPR-8664 | org.springframework.jdbc/src/main/java/org/springframework/jdbc/core/JdbcOperations.java | @@ -35,7 +35,7 @@
* As an alternative to a mock objects approach to testing data access code,
* consider the powerful integration testing support provided in the
* <code>org.springframework.test</code> package, shipped in
- * <code>spring-mock.jar</code>.
+ * <code>spring-test.jar</code>.
*
* @author Rod Johnson
* @author Juergen Hoeller | false |
Other | spring-projects | spring-framework | 818467b9e5afa37080ae5851fbb5e7a23037b7fd.json | Consolidate Environment tests | org.springframework.core/src/test/java/org/springframework/core/env/DefaultEnvironmentTests.java | @@ -1,35 +0,0 @@
-/*
- * Copyright 2002-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.core.env;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Test;
-
-public class DefaultEnvironmentTests {
-
- @Test
- public void propertySourceOrder() {
- ConfigurableEnvironment env = new DefaultEnvironment();
- MutablePropertySources sources = env.getPropertySources();
- assertThat(sources.precedenceOf(PropertySource.named(DefaultEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)), equalTo(0));
- assertThat(sources.precedenceOf(PropertySource.named(DefaultEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)), equalTo(1));
- assertThat(sources.size(), is(2));
- }
-} | true |
Other | spring-projects | spring-framework | 818467b9e5afa37080ae5851fbb5e7a23037b7fd.json | Consolidate Environment tests | org.springframework.core/src/test/java/org/springframework/core/env/EnvironmentTests.java | @@ -61,6 +61,15 @@ public class EnvironmentTests {
private ConfigurableEnvironment environment = new DefaultEnvironment();
+ @Test
+ public void propertySourceOrder() {
+ ConfigurableEnvironment env = new DefaultEnvironment();
+ MutablePropertySources sources = env.getPropertySources();
+ assertThat(sources.precedenceOf(PropertySource.named(DefaultEnvironment.SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME)), equalTo(0));
+ assertThat(sources.precedenceOf(PropertySource.named(DefaultEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)), equalTo(1));
+ assertThat(sources.size(), is(2));
+ }
+
@Test
public void activeProfiles() {
assertThat(environment.getActiveProfiles().length, is(0)); | true |
Other | spring-projects | spring-framework | 6fcea8b99da45f287149796ef2598f0d71758793.json | Remove ConfigurationClassParser from public API
Issue: SPR-8200 | org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java | @@ -197,9 +197,7 @@ public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
*/
private void processConfigurationClasses(BeanDefinitionRegistry registry) {
ConfigurationClassBeanDefinitionReader reader = getConfigurationClassBeanDefinitionReader(registry);
- ConfigurationClassParser parser = new ConfigurationClassParser(
- this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, registry);
- processConfigBeanDefinitions(parser, reader, registry);
+ processConfigBeanDefinitions(reader, registry);
enhanceConfigurationClasses((ConfigurableListableBeanFactory)registry);
}
@@ -215,7 +213,7 @@ private ConfigurationClassBeanDefinitionReader getConfigurationClassBeanDefiniti
* Build and validate a configuration model based on the registry of
* {@link Configuration} classes.
*/
- public void processConfigBeanDefinitions(ConfigurationClassParser parser, ConfigurationClassBeanDefinitionReader reader, BeanDefinitionRegistry registry) {
+ public void processConfigBeanDefinitions(ConfigurationClassBeanDefinitionReader reader, BeanDefinitionRegistry registry) {
Set<BeanDefinitionHolder> configCandidates = new LinkedHashSet<BeanDefinitionHolder>();
for (String beanName : registry.getBeanDefinitionNames()) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
@@ -230,6 +228,8 @@ public void processConfigBeanDefinitions(ConfigurationClassParser parser, Config
}
// Parse each @Configuration class
+ ConfigurationClassParser parser = new ConfigurationClassParser(
+ this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, registry);
for (BeanDefinitionHolder holder : configCandidates) {
BeanDefinition bd = holder.getBeanDefinition();
try { | false |
Other | spring-projects | spring-framework | 8dfcae535e19b0c80dabf8fdbad81fbcd8ba8246.json | revise cache API
+ update failing test | org.springframework.context/src/test/java/org/springframework/cache/vendor/AbstractNativeCacheTest.java | @@ -63,7 +63,7 @@ public void testCachePut() throws Exception {
assertNull(cache.get(key));
cache.put(key, value);
- assertEquals(value, cache.get(key));
+ assertEquals(value, cache.get(key).get());
}
@Test
| false |
Other | spring-projects | spring-framework | 0eb40e1e5e0d49638faba605dde992bebb933c26.json | revise cache API
+ update failing test | org.springframework.context/src/main/java/org/springframework/cache/ehcache/EhCacheCache.java | @@ -21,7 +21,7 @@
import net.sf.ehcache.Status;
import org.springframework.cache.Cache;
-import org.springframework.cache.interceptor.DefaultValue;
+import org.springframework.cache.interceptor.DefaultValueWrapper;
import org.springframework.util.Assert;
/**
@@ -60,7 +60,7 @@ public void clear() {
public ValueWrapper<Object> get(Object key) {
Element element = cache.get(key);
- return (element != null ? new DefaultValue<Object>(element.getObjectValue()) : null);
+ return (element != null ? new DefaultValueWrapper<Object>(element.getObjectValue()) : null);
}
public void put(Object key, Object value) {
| true |
Other | spring-projects | spring-framework | 0eb40e1e5e0d49638faba605dde992bebb933c26.json | revise cache API
+ update failing test | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java | @@ -185,11 +185,11 @@ protected Object execute(Callable<Object> invocation, Object target, Method meth
for (Iterator<Cache<?, ?>> iterator = caches.iterator(); iterator.hasNext() && !cacheHit;) {
Cache cache = iterator.next();
- Cache.ValueWrapper<Object> value = cache.get(key);
+ Cache.ValueWrapper<Object> wrapper = cache.get(key);
- if (value != null) {
+ if (wrapper != null) {
cacheHit = true;
- retVal = value.get();
+ retVal = wrapper.get();
}
}
@@ -199,16 +199,16 @@ protected Object execute(Callable<Object> invocation, Object target, Method meth
+ method);
}
retVal = invocation.call();
+
+ // update all caches
+ for (Cache cache : caches) {
+ cache.put(key, retVal);
+ }
} else {
if (log) {
logger.trace("Key " + key + " found in cache, returning value " + retVal);
}
}
-
- // update all caches
- for (Cache cache : caches) {
- cache.put(key, retVal);
- }
}
if (cacheOp instanceof CacheEvictOperation) {
| true |
Other | spring-projects | spring-framework | 0eb40e1e5e0d49638faba605dde992bebb933c26.json | revise cache API
+ update failing test | org.springframework.context/src/main/java/org/springframework/cache/interceptor/DefaultValueWrapper.java | @@ -23,11 +23,11 @@
*
* @author Costin Leau
*/
-public class DefaultValue<V> implements ValueWrapper<V> {
+public class DefaultValueWrapper<V> implements ValueWrapper<V> {
private final V value;
- public DefaultValue(V value) {
+ public DefaultValueWrapper(V value) {
this.value = value;
}
| true |
Other | spring-projects | spring-framework | 0eb40e1e5e0d49638faba605dde992bebb933c26.json | revise cache API
+ update failing test | org.springframework.context/src/main/java/org/springframework/cache/support/AbstractDelegatingCache.java | @@ -20,7 +20,7 @@
import java.util.Map;
import org.springframework.cache.Cache;
-import org.springframework.cache.interceptor.DefaultValue;
+import org.springframework.cache.interceptor.DefaultValueWrapper;
import org.springframework.util.Assert;
/**
@@ -76,7 +76,8 @@ public void clear() {
}
public ValueWrapper<V> get(Object key) {
- return new DefaultValue<V>(filterNull(delegate.get(key)));
+ V v = delegate.get(key);
+ return (v != null ? new DefaultValueWrapper<V>(filterNull(v)) : null);
}
@SuppressWarnings("unchecked")
@@ -85,8 +86,9 @@ public void put(K key, V value) {
Map map = delegate;
map.put(key, NULL_HOLDER);
}
-
- delegate.put(key, value);
+ else {
+ delegate.put(key, value);
+ }
}
public void evict(Object key) {
| true |
Other | spring-projects | spring-framework | 0eb40e1e5e0d49638faba605dde992bebb933c26.json | revise cache API
+ update failing test | org.springframework.context/src/test/resources/org/springframework/cache/config/annotationDrivenCacheConfig.xml | @@ -9,7 +9,7 @@
<bean id="apc" class="org.springframework.aop.framework.autoproxy.InfrastructureAdvisorAutoProxyCreator"/>
- <bean id="annotationSource" class="org.springframework.cache.annotation.AnnotationCacheDefinitionSource"/>
+ <bean id="annotationSource" class="org.springframework.cache.annotation.AnnotationCacheOperationSource"/>
<aop:config>
<aop:advisor advice-ref="debugInterceptor" pointcut="execution(* *..CacheableService.*(..))" order="1"/>
@@ -20,7 +20,7 @@
<property name="cacheDefinitionSources" ref="annotationSource"/>
</bean>
- <bean id="advisor" class="org.springframework.cache.interceptor.BeanFactoryCacheDefinitionSourceAdvisor">
+ <bean id="advisor" class="org.springframework.cache.interceptor.BeanFactoryCacheOperationSourceAdvisor">
<property name="cacheDefinitionSource" ref="annotationSource"/>
<property name="adviceBeanName" value="cacheInterceptor"/>
</bean>
| true |
Other | spring-projects | spring-framework | dea1fc933fa467e8c33f0aa0bc7e4c61a01ba3d7.json | revise cache API
+ update failing AJ test | org.springframework.aspects/src/test/java/org/springframework/cache/config/annotation-cache-aspectj.xml | @@ -5,7 +5,7 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
- <bean id="annotationSource" class="org.springframework.cache.annotation.AnnotationCacheDefinitionSource"/>
+ <bean id="annotationSource" class="org.springframework.cache.annotation.AnnotationCacheOperationSource"/>
<aop:config>
<aop:advisor advice-ref="debugInterceptor" pointcut="execution(* *..CacheableService.*(..))" order="1"/>
@@ -16,13 +16,6 @@
<property name="cacheDefinitionSources" ref="annotationSource"/>
</bean>
- <!--
- <bean id="advisor" class="org.springframework.cache.interceptor.BeanFactoryCacheDefinitionSourceAdvisor">
- <property name="cacheDefinitionSource" ref="annotationSource"/>
- <property name="adviceBeanName" value="cacheAspect"/>
- </bean>
- -->
-
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
| false |
Other | spring-projects | spring-framework | 861e4817559dfb956512775665c8f0c9da9c99c1.json | revise cache API
+ update failing test | org.springframework.context/src/test/java/org/springframework/cache/config/AbstractAnnotationTest.java | @@ -135,7 +135,7 @@ public void testMethodName(CacheableService service, String keyName)
assertSame(r1, service.name(key));
Cache<Object, Object> cache = cm.getCache("default");
// assert the method name is used
- assertTrue(cache.containsKey(keyName));
+ assertNotNull(cache.get(keyName));
}
public void testRootVars(CacheableService service) {
@@ -145,7 +145,7 @@ public void testRootVars(CacheableService service) {
Cache<Object, Object> cache = cm.getCache("default");
// assert the method name is used
String expectedKey = "rootVarsrootVars" + AopProxyUtils.ultimateTargetClass(service) + service;
- assertTrue(cache.containsKey(expectedKey));
+ assertNotNull(cache.get(expectedKey));
}
public void testNullArg(CacheableService service) {
| false |
Other | spring-projects | spring-framework | 3699a037a55ed4fbe43d66ecc73876f2378e3507.json | revise cache API
+ add missing files (remember to check "show unversioned files") | org.springframework.context/src/main/java/org/springframework/cache/annotation/AnnotationCacheOperationSource.java | @@ -0,0 +1,123 @@
+/*
+ * Copyright 2010-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cache.annotation;
+
+import java.io.Serializable;
+import java.lang.reflect.AnnotatedElement;
+import java.lang.reflect.Method;
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import org.springframework.cache.interceptor.AbstractFallbackCacheOperationSource;
+import org.springframework.cache.interceptor.CacheOperation;
+import org.springframework.util.Assert;
+
+/**
+ *
+ * Implementation of the {@link org.springframework.cache.interceptor.CacheOperationSource}
+ * interface for working with caching metadata in JDK 1.5+ annotation format.
+ *
+ * <p>This class reads Spring's JDK 1.5+ {@link Cacheable} and {@link CacheEvict}
+ * annotations and exposes corresponding caching operation definition to Spring's cache infrastructure.
+ * This class may also serve as base class for a custom CacheOperationSource.
+ *
+ * @author Costin Leau
+ */
+@SuppressWarnings("serial")
+public class AnnotationCacheOperationSource extends AbstractFallbackCacheOperationSource implements
+ Serializable {
+
+ private final boolean publicMethodsOnly;
+
+ private final Set<CacheAnnotationParser> annotationParsers;
+
+ /**
+ * Create a default AnnotationCacheOperationSource, supporting
+ * public methods that carry the <code>Cacheable</code> and <code>CacheEvict</code>
+ * annotations.
+ */
+ public AnnotationCacheOperationSource() {
+ this(true);
+ }
+
+ /**
+ * Create a custom AnnotationCacheOperationSource, supporting
+ * public methods that carry the <code>Cacheable</code> and
+ * <code>CacheEvict</code> annotations.
+ *
+ * @param publicMethodsOnly whether to support only annotated public methods
+ * typically for use with proxy-based AOP), or protected/private methods as well
+ * (typically used with AspectJ class weaving)
+ */
+ public AnnotationCacheOperationSource(boolean publicMethodsOnly) {
+ this.publicMethodsOnly = publicMethodsOnly;
+ this.annotationParsers = new LinkedHashSet<CacheAnnotationParser>(1);
+ this.annotationParsers.add(new SpringCachingAnnotationParser());
+ }
+
+ /**
+ * Create a custom AnnotationCacheOperationSource.
+ * @param annotationParsers the CacheAnnotationParser to use
+ */
+ public AnnotationCacheOperationSource(CacheAnnotationParser... annotationParsers) {
+ this.publicMethodsOnly = true;
+ Assert.notEmpty(annotationParsers, "At least one CacheAnnotationParser needs to be specified");
+ Set<CacheAnnotationParser> parsers = new LinkedHashSet<CacheAnnotationParser>(annotationParsers.length);
+ Collections.addAll(parsers, annotationParsers);
+ this.annotationParsers = parsers;
+ }
+
+ @Override
+ protected CacheOperation findCacheOperation(Class<?> clazz) {
+ return determineCacheOperation(clazz);
+ }
+
+ @Override
+ protected CacheOperation findCacheOperation(Method method) {
+ return determineCacheOperation(method);
+ }
+
+ /**
+ * Determine the cache operation definition for the given method or class.
+ * <p>This implementation delegates to configured
+ * {@link CacheAnnotationParser CacheAnnotationParsers}
+ * for parsing known annotations into Spring's metadata attribute class.
+ * Returns <code>null</code> if it's not cacheable.
+ * <p>Can be overridden to support custom annotations that carry caching metadata.
+ * @param ae the annotated method or class
+ * @return CacheOperation the configured caching operation,
+ * or <code>null</code> if none was found
+ */
+ protected CacheOperation determineCacheOperation(AnnotatedElement ae) {
+ for (CacheAnnotationParser annotationParser : this.annotationParsers) {
+ CacheOperation attr = annotationParser.parseCacheAnnotation(ae);
+ if (attr != null) {
+ return attr;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * By default, only public methods can be made cacheable.
+ */
+ @Override
+ protected boolean allowPublicMethodsOnly() {
+ return this.publicMethodsOnly;
+ }
+}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 3699a037a55ed4fbe43d66ecc73876f2378e3507.json | revise cache API
+ add missing files (remember to check "show unversioned files") | org.springframework.context/src/main/java/org/springframework/cache/interceptor/AbstractFallbackCacheOperationSource.java | @@ -0,0 +1,218 @@
+/*
+ * Copyright 2010-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cache.interceptor;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.springframework.core.BridgeMethodResolver;
+import org.springframework.util.ClassUtils;
+import org.springframework.util.ObjectUtils;
+
+/**
+ * Abstract implementation of {@link CacheOperation} that caches
+ * attributes for methods and implements a fallback policy: 1. specific target
+ * method; 2. target class; 3. declaring method; 4. declaring class/interface.
+ *
+ * <p>Defaults to using the target class's caching attribute if none is
+ * associated with the target method. Any caching attribute associated with
+ * the target method completely overrides a class caching attribute.
+ * If none found on the target class, the interface that the invoked method
+ * has been called through (in case of a JDK proxy) will be checked.
+ *
+ * <p>This implementation caches attributes by method after they are first used.
+ * If it is ever desirable to allow dynamic changing of cacheable attributes
+ * (which is very unlikely), caching could be made configurable.
+
+ * @author Costin Leau
+ * @see org.springframework.transaction.interceptor.AbstractFallbackTransactionAttributeSource
+ */
+public abstract class AbstractFallbackCacheOperationSource implements CacheOperationSource {
+
+ /**
+ * Canonical value held in cache to indicate no caching attribute was
+ * found for this method and we don't need to look again.
+ */
+ private final static CacheOperation NULL_CACHING_ATTRIBUTE = new CacheUpdateOperation();
+
+ /**
+ * Logger available to subclasses.
+ * <p>As this base class is not marked Serializable, the logger will be recreated
+ * after serialization - provided that the concrete subclass is Serializable.
+ */
+ protected final Log logger = LogFactory.getLog(getClass());
+
+ /**
+ * Cache of CacheOperationDefinitions, keyed by DefaultCacheKey (Method + target Class).
+ * <p>As this base class is not marked Serializable, the cache will be recreated
+ * after serialization - provided that the concrete subclass is Serializable.
+ */
+ final Map<Object, CacheOperation> attributeCache = new ConcurrentHashMap<Object, CacheOperation>();
+
+ /**
+ * Determine the caching attribute for this method invocation.
+ * <p>Defaults to the class's caching attribute if no method attribute is found.
+ * @param method the method for the current invocation (never <code>null</code>)
+ * @param targetClass the target class for this invocation (may be <code>null</code>)
+ * @return {@link CacheOperation} for this method, or <code>null</code> if the method
+ * is not cacheable
+ */
+ public CacheOperation getCacheOperation(Method method, Class<?> targetClass) {
+ // First, see if we have a cached value.
+ Object cacheKey = getCacheKey(method, targetClass);
+ CacheOperation cached = this.attributeCache.get(cacheKey);
+ if (cached != null) {
+ if (cached == NULL_CACHING_ATTRIBUTE) {
+ return null;
+ }
+ // Value will either be canonical value indicating there is no caching attribute,
+ // or an actual caching attribute.
+ return cached;
+ }
+ else {
+ // We need to work it out.
+ CacheOperation cacheDef = computeCacheOperationDefinition(method, targetClass);
+ // Put it in the cache.
+ if (cacheDef == null) {
+ this.attributeCache.put(cacheKey, NULL_CACHING_ATTRIBUTE);
+ }
+ else {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Adding cacheable method '" + method.getName() + "' with attribute: " + cacheDef);
+ }
+ this.attributeCache.put(cacheKey, cacheDef);
+ }
+ return cacheDef;
+ }
+ }
+
+ /**
+ * Determine a cache key for the given method and target class.
+ * <p>Must not produce same key for overloaded methods.
+ * Must produce same key for different instances of the same method.
+ * @param method the method (never <code>null</code>)
+ * @param targetClass the target class (may be <code>null</code>)
+ * @return the cache key (never <code>null</code>)
+ */
+ protected Object getCacheKey(Method method, Class<?> targetClass) {
+ return new DefaultCacheKey(method, targetClass);
+ }
+
+ /**
+ * Same signature as {@link #getTransactionAttribute}, but doesn't cache the result.
+ * {@link #getTransactionAttribute} is effectively a caching decorator for this method.
+ * @see #getTransactionAttribute
+ */
+ private CacheOperation computeCacheOperationDefinition(Method method, Class<?> targetClass) {
+ // Don't allow no-public methods as required.
+ if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
+ return null;
+ }
+
+ // The method may be on an interface, but we need attributes from the target class.
+ // If the target class is null, the method will be unchanged.
+ Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
+ // If we are dealing with method with generic parameters, find the original method.
+ specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
+
+ // First try is the method in the target class.
+ CacheOperation opDef = findCacheOperation(specificMethod);
+ if (opDef != null) {
+ return opDef;
+ }
+
+ // Second try is the caching operation on the target class.
+ opDef = findCacheOperation(specificMethod.getDeclaringClass());
+ if (opDef != null) {
+ return opDef;
+ }
+
+ if (specificMethod != method) {
+ // Fall back is to look at the original method.
+ opDef = findCacheOperation(method);
+ if (opDef != null) {
+ return opDef;
+ }
+ // Last fall back is the class of the original method.
+ return findCacheOperation(method.getDeclaringClass());
+ }
+ return null;
+ }
+
+ /**
+ * Subclasses need to implement this to return the caching attribute
+ * for the given method, if any.
+ * @param method the method to retrieve the attribute for
+ * @return all caching attribute associated with this method
+ * (or <code>null</code> if none)
+ */
+ protected abstract CacheOperation findCacheOperation(Method method);
+
+ /**
+ * Subclasses need to implement this to return the caching attribute
+ * for the given class, if any.
+ * @param clazz the class to retrieve the attribute for
+ * @return all caching attribute associated with this class
+ * (or <code>null</code> if none)
+ */
+ protected abstract CacheOperation findCacheOperation(Class<?> clazz);
+
+ /**
+ * Should only public methods be allowed to have caching semantics?
+ * <p>The default implementation returns <code>false</code>.
+ */
+ protected boolean allowPublicMethodsOnly() {
+ return false;
+ }
+
+ /**
+ * Default cache key for the CacheOperationDefinition cache.
+ */
+ private static class DefaultCacheKey {
+
+ private final Method method;
+
+ private final Class<?> targetClass;
+
+ public DefaultCacheKey(Method method, Class<?> targetClass) {
+ this.method = method;
+ this.targetClass = targetClass;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof DefaultCacheKey)) {
+ return false;
+ }
+ DefaultCacheKey otherKey = (DefaultCacheKey) other;
+ return (this.method.equals(otherKey.method) && ObjectUtils.nullSafeEquals(this.targetClass,
+ otherKey.targetClass));
+ }
+
+ @Override
+ public int hashCode() {
+ return this.method.hashCode() * 29 + (this.targetClass != null ? this.targetClass.hashCode() : 0);
+ }
+ }
+}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 3699a037a55ed4fbe43d66ecc73876f2378e3507.json | revise cache API
+ add missing files (remember to check "show unversioned files") | org.springframework.context/src/main/java/org/springframework/cache/interceptor/BeanFactoryCacheOperationSourceAdvisor.java | @@ -0,0 +1,62 @@
+/*
+ * Copyright 2010-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cache.interceptor;
+
+import org.springframework.aop.ClassFilter;
+import org.springframework.aop.Pointcut;
+import org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor;
+
+/**
+ * Advisor driven by a {@link CacheOperationSource}, used to include a
+ * cache advice bean for methods that are cacheable.
+ *
+ * @author Costin Leau
+ */
+@SuppressWarnings("serial")
+public class BeanFactoryCacheOperationSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor {
+
+ private CacheOperationSource cacheDefinitionSource;
+
+ private final CacheOperationSourcePointcut pointcut = new CacheOperationSourcePointcut() {
+ @Override
+ protected CacheOperationSource getCacheOperationSource() {
+ return cacheDefinitionSource;
+ }
+ };
+
+ /**
+ * Set the cache operation attribute source which is used to find cache
+ * attributes. This should usually be identical to the source reference
+ * set on the cache interceptor itself.
+ * @see CacheInterceptor#setCacheAttributeSource
+ */
+ public void setCacheDefinitionSource(CacheOperationSource cacheDefinitionSource) {
+ this.cacheDefinitionSource = cacheDefinitionSource;
+ }
+
+ /**
+ * Set the {@link ClassFilter} to use for this pointcut.
+ * Default is {@link ClassFilter#TRUE}.
+ */
+ public void setClassFilter(ClassFilter classFilter) {
+ this.pointcut.setClassFilter(classFilter);
+ }
+
+ public Pointcut getPointcut() {
+ return this.pointcut;
+ }
+}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 3699a037a55ed4fbe43d66ecc73876f2378e3507.json | revise cache API
+ add missing files (remember to check "show unversioned files") | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheEvictOperation.java | @@ -0,0 +1,43 @@
+/*
+ * Copyright 2010-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cache.interceptor;
+
+/**
+ * Class describing an 'evict' operation.
+ *
+ * @author Costin Leau
+ */
+public class CacheEvictOperation extends CacheOperation {
+
+ private boolean cacheWide = false;
+
+ public boolean isCacheWide() {
+ return cacheWide;
+ }
+
+ public void setCacheWide(boolean cacheWide) {
+ this.cacheWide = cacheWide;
+ }
+
+ @Override
+ protected StringBuilder getOperationDescription() {
+ StringBuilder sb = super.getOperationDescription();
+ sb.append(",");
+ sb.append(cacheWide);
+ return sb;
+ }
+}
| true |
Other | spring-projects | spring-framework | 3699a037a55ed4fbe43d66ecc73876f2378e3507.json | revise cache API
+ add missing files (remember to check "show unversioned files") | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheOperation.java | @@ -0,0 +1,128 @@
+/*
+ * Copyright 2010-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cache.interceptor;
+
+import java.util.Collections;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+import org.springframework.util.Assert;
+
+/**
+ * Base class implementing {@link CacheOperation}.
+ *
+ * @author Costin Leau
+ */
+public abstract class CacheOperation {
+
+ private Set<String> cacheNames = Collections.emptySet();
+ private String condition = "";
+ private String key = "";
+ private String name = "";
+
+
+ public Set<String> getCacheNames() {
+ return cacheNames;
+ }
+
+ public String getCondition() {
+ return condition;
+ }
+
+ public String getKey() {
+ return key;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setCacheName(String cacheName) {
+ Assert.hasText(cacheName);
+ this.cacheNames = Collections.singleton(cacheName);
+ }
+
+ public void setCacheNames(String[] cacheNames) {
+ Assert.notEmpty(cacheNames);
+ this.cacheNames = new LinkedHashSet<String>(cacheNames.length);
+ for (String string : cacheNames) {
+ this.cacheNames.add(string);
+ }
+ }
+
+ public void setCondition(String condition) {
+ Assert.notNull(condition);
+ this.condition = condition;
+ }
+
+ public void setKey(String key) {
+ Assert.notNull(key);
+ this.key = key;
+ }
+
+ public void setName(String name) {
+ Assert.hasText(name);
+ this.name = name;
+ }
+
+ /**
+ * This implementation compares the <code>toString()</code> results.
+ * @see #toString()
+ */
+ @Override
+ public boolean equals(Object other) {
+ return (other instanceof CacheOperation && toString().equals(other.toString()));
+ }
+
+ /**
+ * This implementation returns <code>toString()</code>'s hash code.
+ * @see #toString()
+ */
+ @Override
+ public int hashCode() {
+ return toString().hashCode();
+ }
+
+ /**
+ * Return an identifying description for this cache operation.
+ * <p>Has to be overridden in subclasses for correct <code>equals</code>
+ * and <code>hashCode</code> behavior. Alternatively, {@link #equals}
+ * and {@link #hashCode} can be overridden themselves.
+ */
+ @Override
+ public String toString() {
+ return getOperationDescription().toString();
+ }
+
+ /**
+ * Return an identifying description for this caching operation.
+ * <p>Available to subclasses, for inclusion in their <code>toString()</code> result.
+ */
+ protected StringBuilder getOperationDescription() {
+ StringBuilder result = new StringBuilder();
+ result.append("CacheDefinition[");
+ result.append(name);
+ result.append("] caches=");
+ result.append(cacheNames);
+ result.append(" | condition='");
+ result.append(condition);
+ result.append("' | key='");
+ result.append(key);
+ result.append("'");
+ return result;
+ }
+}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 3699a037a55ed4fbe43d66ecc73876f2378e3507.json | revise cache API
+ add missing files (remember to check "show unversioned files") | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheOperationSource.java | @@ -0,0 +1,41 @@
+/*
+ * Copyright 2010-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cache.interceptor;
+
+import java.lang.reflect.Method;
+
+
+/**
+ * Interface used by CacheInterceptor. Implementations know
+ * how to source cache operation attributes, whether from configuration,
+ * metadata attributes at source level, or anywhere else.
+ *
+ * @author Costin Leau
+ */
+public interface CacheOperationSource {
+
+ /**
+ * Return the cache operation definition for this method.
+ * Return null if the method is not cacheable.
+ * @param method method
+ * @param targetClass target class. May be <code>null</code>, in which
+ * case the declaring class of the method must be used.
+ * @return {@link CacheOperation} the matching cache operation,
+ * or <code>null</code> if none found
+ */
+ CacheOperation getCacheOperation(Method method, Class<?> targetClass);
+}
| true |
Other | spring-projects | spring-framework | 3699a037a55ed4fbe43d66ecc73876f2378e3507.json | revise cache API
+ add missing files (remember to check "show unversioned files") | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheOperationSourcePointcut.java | @@ -0,0 +1,68 @@
+/*
+ * Copyright 2010-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cache.interceptor;
+
+import java.io.Serializable;
+import java.lang.reflect.Method;
+
+import org.springframework.aop.support.StaticMethodMatcherPointcut;
+import org.springframework.util.ObjectUtils;
+
+/**
+ * Inner class that implements a Pointcut that matches if the underlying
+ * {@link CacheOperationSource} has an attribute for a given method.
+ *
+ * @author Costin Leau
+ */
+@SuppressWarnings("serial")
+abstract class CacheOperationSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {
+
+ public boolean matches(Method method, Class<?> targetClass) {
+ CacheOperationSource cas = getCacheOperationSource();
+ return (cas == null || cas.getCacheOperation(method, targetClass) != null);
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (!(other instanceof CacheOperationSourcePointcut)) {
+ return false;
+ }
+ CacheOperationSourcePointcut otherPc = (CacheOperationSourcePointcut) other;
+ return ObjectUtils.nullSafeEquals(getCacheOperationSource(),
+ otherPc.getCacheOperationSource());
+ }
+
+ @Override
+ public int hashCode() {
+ return CacheOperationSourcePointcut.class.hashCode();
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getName() + ": " + getCacheOperationSource();
+ }
+
+
+ /**
+ * Obtain the underlying CacheOperationDefinitionSource (may be <code>null</code>).
+ * To be implemented by subclasses.
+ */
+ protected abstract CacheOperationSource getCacheOperationSource();
+}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 3699a037a55ed4fbe43d66ecc73876f2378e3507.json | revise cache API
+ add missing files (remember to check "show unversioned files") | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheUpdateOperation.java | @@ -0,0 +1,26 @@
+/*
+ * Copyright 2010-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cache.interceptor;
+
+/**
+ * Class describing an 'update' operation.
+ *
+ * @author Costin Leau
+ */
+public class CacheUpdateOperation extends CacheOperation {
+
+}
| true |
Other | spring-projects | spring-framework | 3699a037a55ed4fbe43d66ecc73876f2378e3507.json | revise cache API
+ add missing files (remember to check "show unversioned files") | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CompositeCacheOperationSource.java | @@ -0,0 +1,63 @@
+/*
+ * Copyright 2010-2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cache.interceptor;
+
+import java.io.Serializable;
+import java.lang.reflect.Method;
+
+import org.springframework.util.Assert;
+
+/**
+ * Composite {@link CacheOperationSource} implementation that iterates
+ * over a given array of {@link CacheOperationSource} instances.
+ *
+ * @author Costin Leau
+ */
+@SuppressWarnings("serial")
+public class CompositeCacheOperationSource implements CacheOperationSource, Serializable {
+
+ private final CacheOperationSource[] cacheDefinitionSources;
+
+ /**
+ * Create a new CompositeCachingDefinitionSource for the given sources.
+ * @param cacheDefinitionSourcess the CacheDefinitionSource instances to combine
+ */
+ public CompositeCacheOperationSource(CacheOperationSource[] cacheDefinitionSources) {
+ Assert.notNull(cacheDefinitionSources, "cacheDefinitionSource array must not be null");
+ this.cacheDefinitionSources = cacheDefinitionSources;
+ }
+
+ /**
+ * Return the CacheDefinitionSource instances that this
+ * CompositeCachingDefinitionSource combines.
+ */
+ public final CacheOperationSource[] getCacheDefinitionSources() {
+ return this.cacheDefinitionSources;
+ }
+
+
+ public CacheOperation getCacheOperation(Method method, Class<?> targetClass) {
+ for (CacheOperationSource source : cacheDefinitionSources) {
+ CacheOperation definition = source.getCacheOperation(method, targetClass);
+ if (definition != null) {
+ return definition;
+ }
+ }
+
+ return null;
+ }
+}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 3699a037a55ed4fbe43d66ecc73876f2378e3507.json | revise cache API
+ add missing files (remember to check "show unversioned files") | org.springframework.context/src/main/java/org/springframework/cache/interceptor/DefaultValue.java | @@ -0,0 +1,37 @@
+/*
+ * Copyright 2011 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.springframework.cache.interceptor;
+
+import org.springframework.cache.Cache.ValueWrapper;
+
+/**
+ * Default implementation for {@link org.springframework.cache.Cache.ValueWrapper}.
+ *
+ * @author Costin Leau
+ */
+public class DefaultValue<V> implements ValueWrapper<V> {
+
+ private final V value;
+
+ public DefaultValue(V value) {
+ this.value = value;
+ }
+
+ public V get() {
+ return value;
+ }
+}
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.aspects/src/main/java/org/springframework/cache/aspectj/AbstractCacheAspect.aj | @@ -22,7 +22,7 @@ import java.util.concurrent.Callable;
import org.aspectj.lang.annotation.SuppressAjWarnings;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.cache.interceptor.CacheAspectSupport;
-import org.springframework.cache.interceptor.CacheDefinitionSource;
+import org.springframework.cache.interceptor.CacheOperationSource;
/**
* Abstract superaspect for AspectJ cache aspects. Concrete
@@ -46,11 +46,11 @@ public abstract aspect AbstractCacheAspect extends CacheAspectSupport {
/**
* Construct object using the given caching metadata retrieval strategy.
- * @param cds {@link CacheDefinitionSource} implementation, retrieving Spring
+ * @param cos {@link CacheOperationSource} implementation, retrieving Spring
* cache metadata for each joinpoint.
*/
- protected AbstractCacheAspect(CacheDefinitionSource... cds) {
- setCacheDefinitionSources(cds);
+ protected AbstractCacheAspect(CacheOperationSource... cos) {
+ setCacheDefinitionSources(cos);
}
@SuppressAjWarnings("adviceDidNotMatch")
@@ -75,7 +75,7 @@ public abstract aspect AbstractCacheAspect extends CacheAspectSupport {
/**
* Concrete subaspects must implement this pointcut, to identify
* cached methods. For each selected joinpoint, {@link CacheOperationDefinition}
- * will be retrieved using Spring's {@link CacheDefinitionSource} interface.
+ * will be retrieved using Spring's {@link CacheOperationSource} interface.
*/
protected abstract pointcut cacheMethodExecution(Object cachedObject);
}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.aspects/src/main/java/org/springframework/cache/aspectj/AnnotationCacheAspect.aj | @@ -16,7 +16,7 @@
package org.springframework.cache.aspectj;
-import org.springframework.cache.annotation.AnnotationCacheDefinitionSource;
+import org.springframework.cache.annotation.AnnotationCacheOperationSource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
@@ -43,7 +43,7 @@ import org.springframework.cache.annotation.Cacheable;
public aspect AnnotationCacheAspect extends AbstractCacheAspect {
public AnnotationCacheAspect() {
- super(new AnnotationCacheDefinitionSource(false));
+ super(new AnnotationCacheOperationSource(false));
}
/**
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/Cache.java | @@ -28,6 +28,18 @@
*/
public interface Cache<K, V> {
+ /**
+ * A (wrapper) object representing a cache value.
+ */
+ interface ValueWrapper<V> {
+ /**
+ * Returns the actual value in the cache.
+ *
+ * @return cache value
+ */
+ V get();
+ }
+
/**
* Returns the cache name.
*
@@ -38,164 +50,36 @@
/**
* Returns the the native, underlying cache provider.
*
- * @return
+ * @return the underlying native cache provider.
*/
Object getNativeCache();
/**
- * Returns <tt>true</tt> if this cache contains a mapping for the specified
- * key. More formally, returns <tt>true</tt> if and only if
- * this cache contains a mapping for a key <tt>k</tt> such that
- * <tt>(key==null ? k==null : key.equals(k))</tt>. (There can be
- * at most one such mapping.)
- *
- * @param key key whose presence in this cache is to be tested.
- * @return <tt>true</tt> if this cache contains a mapping for the specified
- * key.
- */
- boolean containsKey(Object key);
-
- /**
- * Returns the value to which this cache maps the specified key. Returns
- * <tt>null</tt> if the cache contains no mapping for this key. A return
- * value of <tt>null</tt> does not <i>necessarily</i> indicate that the
- * cache contains no mapping for the key; it's also possible that the cache
- * explicitly maps the key to <tt>null</tt>. The <tt>containsKey</tt>
- * operation may be used to distinguish these two cases.
- *
- * <p>More formally, if this cache contains a mapping from a key
- * <tt>k</tt> to a value <tt>v</tt> such that <tt>(key==null ? k==null :
- * key.equals(k))</tt>, then this method returns <tt>v</tt>; otherwise
- * it returns <tt>null</tt>. (There can be at most one such mapping.)
- *
+ * Returns the value to which this cache maps the specified key. Returns
+ * <tt>null</tt> if the cache contains no mapping for this key.
+ *
* @param key key whose associated value is to be returned.
* @return the value to which this cache maps the specified key, or
* <tt>null</tt> if the cache contains no mapping for this key.
- *
- * @see #containsKey(Object)
*/
- V get(Object key);
-
+ ValueWrapper<V> get(Object key);
/**
- * Associates the specified value with the specified key in this cache
- * (optional operation). If the cache previously contained a mapping for
- * this key, the old value is replaced by the specified value. (A cache
- * <tt>m</tt> is said to contain a mapping for a key <tt>k</tt> if and only
- * if {@link #containsKey(Object) m.containsKey(k)} would return
- * <tt>true</tt>.))
+ * Associates the specified value with the specified key in this cache.
+ * If the cache previously contained a mapping for this key, the old
+ * value is replaced by the specified value.
*
* @param key key with which the specified value is to be associated.
* @param value value to be associated with the specified key.
- * @return previous value associated with specified key, or <tt>null</tt>
- * if there was no mapping for key. A <tt>null</tt> return can
- * also indicate that the cache previously associated <tt>null</tt>
- * with the specified key, if the implementation supports
- * <tt>null</tt> values.
*/
- V put(K key, V value);
-
+ void put(K key, V value);
/**
- * If the specified key is not already associated with a value, associate it with the given value.
- *
- * This is equivalent to:
- * <pre>
- * if (!cache.containsKey(key))
- * return cache.put(key, value);
- * else
- * return cache.get(key);
- * </pre>
- *
- * @param key key with which the specified value is to be associated.
- * @param value value to be associated with the specified key.
- * @return previous value associated with specified key, or <tt>null</tt>
- * if there was no mapping for key. A <tt>null</tt> return can
- * also indicate that the cache previously associated <tt>null</tt>
- * with the specified key, if the implementation supports
- * <tt>null</tt> values.
- */
- V putIfAbsent(K key, V value);
-
-
- /**
- * Removes the mapping for this key from this cache if it is present
- * (optional operation). More formally, if this cache contains a mapping
- * from key <tt>k</tt> to value <tt>v</tt> such that
- * <code>(key==null ? k==null : key.equals(k))</code>, that mapping
- * is removed. (The cache can contain at most one such mapping.)
- *
- * <p>Returns the value to which the cache previously associated the key, or
- * <tt>null</tt> if the cache contained no mapping for this key. (A
- * <tt>null</tt> return can also indicate that the cache previously
- * associated <tt>null</tt> with the specified key if the implementation
- * supports <tt>null</tt> values.) The cache will not contain a mapping for
- * the specified key once the call returns.
+ * Evicts the mapping for this key from this cache if it is present.
*
* @param key key whose mapping is to be removed from the cache.
- * @return previous value associated with specified key, or <tt>null</tt>
- * if there was no mapping for key.
- */
- V remove(Object key);
-
-
- /**
- * Remove entry for key only if currently mapped to given value.
- *
- * Similar to:
- * <pre>
- * if ((cache.containsKey(key) && cache.get(key).equals(value)) {
- * cache.remove(key);
- * return true;
- * }
- * else
- * return false;
- * </pre>
- *
- * @param key key with which the specified value is associated.
- * @param value value associated with the specified key.
- * @return true if the value was removed, false otherwise
*/
- boolean remove(Object key, Object value);
-
-
- /**
- * Replace entry for key only if currently mapped to given value.
- *
- * Similar to:
- * <pre>
- * if ((cache.containsKey(key) && cache.get(key).equals(oldValue)) {
- * cache.put(key, newValue);
- * return true;
- * } else return false;
- * </pre>
-
- * @param key key with which the specified value is associated.
- * @param oldValue value expected to be associated with the specified key.
- * @param newValue value to be associated with the specified key.
- * @return true if the value was replaced
- */
- boolean replace(K key, V oldValue, V newValue);
-
- /**
- * Replace entry for key only if currently mapped to some value.
- * Acts as
- * <pre>
- * if ((cache.containsKey(key)) {
- * return cache.put(key, value);
- * } else return null;
- * </pre>
- * except that the action is performed atomically.
- * @param key key with which the specified value is associated.
- * @param value value to be associated with the specified key.
- * @return previous value associated with specified key, or <tt>null</tt>
- * if there was no mapping for key. A <tt>null</tt> return can
- * also indicate that the cache previously associated <tt>null</tt>
- * with the specified key, if the implementation supports
- * <tt>null</tt> values.
- */
- V replace(K key, V value);
-
+ void evict(Object key);
/**
* Removes all mappings from the cache.
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/annotation/AnnotationCacheDefinitionSource.java | @@ -1,125 +0,0 @@
-/*
- * Copyright 2010-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cache.annotation;
-
-import java.io.Serializable;
-import java.lang.reflect.AnnotatedElement;
-import java.lang.reflect.Method;
-import java.util.Collections;
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-import org.springframework.cache.interceptor.AbstractFallbackCacheDefinitionSource;
-import org.springframework.cache.interceptor.CacheDefinition;
-import org.springframework.util.Assert;
-
-/**
- *
- * Implementation of the
- * {@link org.springframework.cache.interceptor.CacheDefinitionSource}
- * interface for working with caching metadata in JDK 1.5+ annotation format.
- *
- * <p>This class reads Spring's JDK 1.5+ {@link Cacheable} and {@link CacheEvict}
- * annotations and
- * exposes corresponding caching operation definition to Spring's cache infrastructure.
- * This class may also serve as base class for a custom CacheDefinitionSource.
- *
- * @author Costin Leau
- */
-@SuppressWarnings("serial")
-public class AnnotationCacheDefinitionSource extends AbstractFallbackCacheDefinitionSource implements
- Serializable {
-
- private final boolean publicMethodsOnly;
-
- private final Set<CacheAnnotationParser> annotationParsers;
-
- /**
- * Create a default AnnotationCacheOperationDefinitionSource, supporting
- * public methods that carry the <code>Cacheable</code> and <code>CacheInvalidate</code>
- * annotations.
- */
- public AnnotationCacheDefinitionSource() {
- this(true);
- }
-
- /**
- * Create a custom AnnotationCacheOperationDefinitionSource, supporting
- * public methods that carry the <code>Cacheable</code> and
- * <code>CacheInvalidate</code> annotations.
- *
- * @param publicMethodsOnly whether to support only annotated public methods
- * typically for use with proxy-based AOP), or protected/private methods as well
- * (typically used with AspectJ class weaving)
- */
- public AnnotationCacheDefinitionSource(boolean publicMethodsOnly) {
- this.publicMethodsOnly = publicMethodsOnly;
- this.annotationParsers = new LinkedHashSet<CacheAnnotationParser>(1);
- this.annotationParsers.add(new SpringCachingAnnotationParser());
- }
-
- /**
- * Create a custom AnnotationCacheOperationDefinitionSource.
- * @param annotationParsers the CacheAnnotationParser to use
- */
- public AnnotationCacheDefinitionSource(CacheAnnotationParser... annotationParsers) {
- this.publicMethodsOnly = true;
- Assert.notEmpty(annotationParsers, "At least one CacheAnnotationParser needs to be specified");
- Set<CacheAnnotationParser> parsers = new LinkedHashSet<CacheAnnotationParser>(annotationParsers.length);
- Collections.addAll(parsers, annotationParsers);
- this.annotationParsers = parsers;
- }
-
- @Override
- protected CacheDefinition findCacheDefinition(Class<?> clazz) {
- return determineCacheDefinition(clazz);
- }
-
- @Override
- protected CacheDefinition findCacheOperation(Method method) {
- return determineCacheDefinition(method);
- }
-
- /**
- * Determine the cache operation definition for the given method or class.
- * <p>This implementation delegates to configured
- * {@link CacheAnnotationParser CacheAnnotationParsers}
- * for parsing known annotations into Spring's metadata attribute class.
- * Returns <code>null</code> if it's not cacheable.
- * <p>Can be overridden to support custom annotations that carry caching metadata.
- * @param ae the annotated method or class
- * @return CacheOperationDefinition the configured caching operation,
- * or <code>null</code> if none was found
- */
- protected CacheDefinition determineCacheDefinition(AnnotatedElement ae) {
- for (CacheAnnotationParser annotationParser : this.annotationParsers) {
- CacheDefinition attr = annotationParser.parseCacheAnnotation(ae);
- if (attr != null) {
- return attr;
- }
- }
- return null;
- }
-
- /**
- * By default, only public methods can be made cacheable.
- */
- @Override
- protected boolean allowPublicMethodsOnly() {
- return this.publicMethodsOnly;
- }
-}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/annotation/CacheAnnotationParser.java | @@ -18,7 +18,7 @@
import java.lang.reflect.AnnotatedElement;
-import org.springframework.cache.interceptor.CacheDefinition;
+import org.springframework.cache.interceptor.CacheOperation;
/**
@@ -38,9 +38,9 @@ public interface CacheAnnotationParser {
* metadata attribute class. Returns <code>null</code> if the method/class
* is not cacheable.
* @param ae the annotated method or class
- * @return CacheOperationDefinition the configured caching operation,
+ * @return CacheOperation the configured caching operation,
* or <code>null</code> if none was found
- * @see AnnotationCacheDefinitionSource#determineCacheOperationDefinition
+ * @see AnnotationCacheOperationSource#determineCacheOperation
*/
- CacheDefinition parseCacheAnnotation(AnnotatedElement ae);
+ CacheOperation parseCacheAnnotation(AnnotatedElement ae);
}
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/annotation/SpringCachingAnnotationParser.java | @@ -20,11 +20,9 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
-import org.springframework.cache.interceptor.CacheDefinition;
-import org.springframework.cache.interceptor.CacheInvalidateDefinition;
-import org.springframework.cache.interceptor.CacheUpdateDefinition;
-import org.springframework.cache.interceptor.DefaultCacheInvalidateDefinition;
-import org.springframework.cache.interceptor.DefaultCacheUpdateDefinition;
+import org.springframework.cache.interceptor.CacheEvictOperation;
+import org.springframework.cache.interceptor.CacheOperation;
+import org.springframework.cache.interceptor.CacheUpdateOperation;
/**
* Strategy implementation for parsing Spring's {@link Cacheable} and {@link CacheEvict} annotations.
@@ -34,7 +32,7 @@
@SuppressWarnings("serial")
public class SpringCachingAnnotationParser implements CacheAnnotationParser, Serializable {
- public CacheDefinition parseCacheAnnotation(AnnotatedElement ae) {
+ public CacheOperation parseCacheAnnotation(AnnotatedElement ae) {
Cacheable update = findAnnotation(ae, Cacheable.class);
if (update != null) {
@@ -44,7 +42,7 @@ public CacheDefinition parseCacheAnnotation(AnnotatedElement ae) {
CacheEvict invalidate = findAnnotation(ae, CacheEvict.class);
if (invalidate != null) {
- return parseInvalidateAnnotation(ae, invalidate);
+ return parseEvictAnnotation(ae, invalidate);
}
return null;
@@ -63,8 +61,8 @@ private <T extends Annotation> T findAnnotation(AnnotatedElement ae, Class<T> an
return ann;
}
- CacheUpdateDefinition parseCacheableAnnotation(AnnotatedElement target, Cacheable ann) {
- DefaultCacheUpdateDefinition dcud = new DefaultCacheUpdateDefinition();
+ CacheUpdateOperation parseCacheableAnnotation(AnnotatedElement target, Cacheable ann) {
+ CacheUpdateOperation dcud = new CacheUpdateOperation();
dcud.setCacheNames(ann.value());
dcud.setCondition(ann.condition());
dcud.setKey(ann.key());
@@ -73,8 +71,8 @@ CacheUpdateDefinition parseCacheableAnnotation(AnnotatedElement target, Cacheabl
return dcud;
}
- CacheInvalidateDefinition parseInvalidateAnnotation(AnnotatedElement target, CacheEvict ann) {
- DefaultCacheInvalidateDefinition dcid = new DefaultCacheInvalidateDefinition();
+ CacheEvictOperation parseEvictAnnotation(AnnotatedElement target, CacheEvict ann) {
+ CacheEvictOperation dcid = new CacheEvictOperation();
dcid.setCacheNames(ann.value());
dcid.setCondition(ann.condition());
dcid.setKey(ann.key());
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/concurrent/ConcurrentCache.java | @@ -54,52 +54,4 @@ public String getName() {
public ConcurrentMap<K, V> getNativeCache() {
return store;
}
-
- @SuppressWarnings("unchecked")
- public V putIfAbsent(K key, V value) {
- if (getAllowNullValues()) {
- if (value == null) {
- ConcurrentMap raw = store;
- return filterNull((V) raw.putIfAbsent(key, NULL_HOLDER));
- }
- }
- return filterNull(store.putIfAbsent(key, value));
- }
-
- @SuppressWarnings("unchecked")
- public boolean remove(Object key, Object value) {
- if (getAllowNullValues()) {
- if (value == null) {
- ConcurrentMap raw = store;
- return raw.remove(key, NULL_HOLDER);
- }
- }
-
- return store.remove(key, value);
- }
-
- @SuppressWarnings("unchecked")
- public boolean replace(K key, V oldValue, V newValue) {
- if (getAllowNullValues()) {
- Object rawOldValue = (oldValue == null ? NULL_HOLDER : oldValue);
- Object rawNewValue = (newValue == null ? NULL_HOLDER : newValue);
-
- ConcurrentMap raw = store;
- return raw.replace(key, rawOldValue, rawNewValue);
- }
-
- return store.replace(key, oldValue, newValue);
- }
-
- @SuppressWarnings("unchecked")
- public V replace(K key, V value) {
- if (getAllowNullValues()) {
- if (value == null) {
- ConcurrentMap raw = store;
- return filterNull((V) raw.replace(key, NULL_HOLDER));
- }
- }
-
- return filterNull(store.replace(key, value));
- }
}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/config/AnnotationDrivenCacheBeanDefinitionParser.java | @@ -16,9 +16,7 @@
package org.springframework.cache.config;
-import static org.springframework.context.annotation.AnnotationConfigUtils.CACHE_ADVISOR_BEAN_NAME;
-import static org.springframework.context.annotation.AnnotationConfigUtils.CACHE_ASPECT_BEAN_NAME;
-import static org.springframework.context.annotation.AnnotationConfigUtils.CACHE_ASPECT_CLASS_NAME;
+import static org.springframework.context.annotation.AnnotationConfigUtils.*;
import org.springframework.aop.config.AopNamespaceUtils;
import org.springframework.beans.factory.config.BeanDefinition;
@@ -28,8 +26,8 @@
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
-import org.springframework.cache.annotation.AnnotationCacheDefinitionSource;
-import org.springframework.cache.interceptor.BeanFactoryCacheDefinitionSourceAdvisor;
+import org.springframework.cache.annotation.AnnotationCacheOperationSource;
+import org.springframework.cache.interceptor.BeanFactoryCacheOperationSourceAdvisor;
import org.springframework.cache.interceptor.CacheInterceptor;
import org.w3c.dom.Element;
@@ -114,7 +112,7 @@ public static void configureAutoProxyCreator(Element element, ParserContext pars
Object eleSource = parserContext.extractSource(element);
// Create the CacheDefinitionSource definition.
- RootBeanDefinition sourceDef = new RootBeanDefinition(AnnotationCacheDefinitionSource.class);
+ RootBeanDefinition sourceDef = new RootBeanDefinition(AnnotationCacheOperationSource.class);
sourceDef.setSource(eleSource);
sourceDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
String sourceName = parserContext.getReaderContext().registerWithGeneratedName(sourceDef);
@@ -128,7 +126,7 @@ public static void configureAutoProxyCreator(Element element, ParserContext pars
String interceptorName = parserContext.getReaderContext().registerWithGeneratedName(interceptorDef);
// Create the CacheAdvisor definition.
- RootBeanDefinition advisorDef = new RootBeanDefinition(BeanFactoryCacheDefinitionSourceAdvisor.class);
+ RootBeanDefinition advisorDef = new RootBeanDefinition(BeanFactoryCacheOperationSourceAdvisor.class);
advisorDef.setSource(eleSource);
advisorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
advisorDef.getPropertyValues().add("cacheDefinitionSource", new RuntimeBeanReference(sourceName));
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/ehcache/EhCacheCache.java | @@ -21,6 +21,7 @@
import net.sf.ehcache.Status;
import org.springframework.cache.Cache;
+import org.springframework.cache.interceptor.DefaultValue;
import org.springframework.util.Assert;
/**
@@ -57,77 +58,16 @@ public void clear() {
cache.removeAll();
}
- public boolean containsKey(Object key) {
- // get the element to force the expiry check (since #isKeyInCache does not considers that)
- Element element = cache.getQuiet(key);
- return (element != null ? true : false);
- }
-
- public Object get(Object key) {
+ public ValueWrapper<Object> get(Object key) {
Element element = cache.get(key);
- return (element != null ? element.getObjectValue() : null);
+ return (element != null ? new DefaultValue<Object>(element.getObjectValue()) : null);
}
- public Object put(Object key, Object value) {
- Element previous = cache.getQuiet(key);
+ public void put(Object key, Object value) {
cache.put(new Element(key, value));
- return (previous != null ? previous.getValue() : null);
}
- public Object remove(Object key) {
- Element element = cache.getQuiet(key);
- Object value = (element != null ? element.getObjectValue() : null);
+ public void evict(Object key) {
cache.remove(key);
- return value;
- }
-
- public Object putIfAbsent(Object key, Object value) {
- // putIfAbsent supported only from Ehcache 2.1
- // return cache.putIfAbsent(new Element(key, value));
- Element existing = cache.getQuiet(key);
- if (existing == null) {
- cache.put(new Element(key, value));
- return null;
- }
- return existing.getObjectValue();
- }
-
- public boolean remove(Object key, Object value) {
- // remove(Element) supported only from Ehcache 2.1
- // return cache.removeElement(new Element(key, value));
- Element existing = cache.getQuiet(key);
-
- if (existing != null && existing.getObjectValue().equals(value)) {
- cache.remove(key);
- return true;
- }
-
- return false;
- }
-
- public Object replace(Object key, Object value) {
- // replace(Object, Object) supported only from Ehcache 2.1
- // return cache.replace(new Element(key, value));
- Element existing = cache.getQuiet(key);
-
- if (existing != null) {
- cache.put(new Element(key, value));
- return existing.getObjectValue();
- }
-
- return null;
- }
-
- public boolean replace(Object key, Object oldValue, Object newValue) {
- // replace(Object, Object, Object) supported only from Ehcache 2.1
- // return cache.replace(new Element(key, oldValue), new Element(key,
- // newValue));
- Element existing = cache.getQuiet(key);
-
- if (existing != null && existing.getObjectValue().equals(oldValue)) {
- cache.put(new Element(key, newValue));
- return true;
- }
- return false;
}
}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/interceptor/AbstractCacheDefinition.java | @@ -1,128 +0,0 @@
-/*
- * Copyright 2010-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cache.interceptor;
-
-import java.util.Collections;
-import java.util.LinkedHashSet;
-import java.util.Set;
-
-import org.springframework.util.Assert;
-
-/**
- * Base class implementing {@link CacheDefinition}.
- *
- * @author Costin Leau
- */
-abstract class AbstractCacheDefinition implements CacheDefinition {
-
- private Set<String> cacheNames = Collections.emptySet();
- private String condition = "";
- private String key = "";
- private String name = "";
-
-
- public Set<String> getCacheNames() {
- return cacheNames;
- }
-
- public String getCondition() {
- return condition;
- }
-
- public String getKey() {
- return key;
- }
-
- public String getName() {
- return name;
- }
-
- public void setCacheName(String cacheName) {
- Assert.hasText(cacheName);
- this.cacheNames = Collections.singleton(cacheName);
- }
-
- public void setCacheNames(String[] cacheNames) {
- Assert.notEmpty(cacheNames);
- this.cacheNames = new LinkedHashSet<String>(cacheNames.length);
- for (String string : cacheNames) {
- this.cacheNames.add(string);
- }
- }
-
- public void setCondition(String condition) {
- Assert.notNull(condition);
- this.condition = condition;
- }
-
- public void setKey(String key) {
- Assert.notNull(key);
- this.key = key;
- }
-
- public void setName(String name) {
- Assert.hasText(name);
- this.name = name;
- }
-
- /**
- * This implementation compares the <code>toString()</code> results.
- * @see #toString()
- */
- @Override
- public boolean equals(Object other) {
- return (other instanceof CacheDefinition && toString().equals(other.toString()));
- }
-
- /**
- * This implementation returns <code>toString()</code>'s hash code.
- * @see #toString()
- */
- @Override
- public int hashCode() {
- return toString().hashCode();
- }
-
- /**
- * Return an identifying description for this cache operation definition.
- * <p>Has to be overridden in subclasses for correct <code>equals</code>
- * and <code>hashCode</code> behavior. Alternatively, {@link #equals}
- * and {@link #hashCode} can be overridden themselves.
- */
- @Override
- public String toString() {
- return getDefinitionDescription().toString();
- }
-
- /**
- * Return an identifying description for this caching definition.
- * <p>Available to subclasses, for inclusion in their <code>toString()</code> result.
- */
- protected StringBuilder getDefinitionDescription() {
- StringBuilder result = new StringBuilder();
- result.append("CacheDefinition[");
- result.append(name);
- result.append("] caches=");
- result.append(cacheNames);
- result.append(" | condition='");
- result.append(condition);
- result.append("' | key='");
- result.append(key);
- result.append("'");
- return result;
- }
-}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/interceptor/AbstractFallbackCacheDefinitionSource.java | @@ -1,218 +0,0 @@
-/*
- * Copyright 2010-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cache.interceptor;
-
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.springframework.core.BridgeMethodResolver;
-import org.springframework.util.ClassUtils;
-import org.springframework.util.ObjectUtils;
-
-/**
- * Abstract implementation of {@link CacheDefinition} that caches
- * attributes for methods and implements a fallback policy: 1. specific target
- * method; 2. target class; 3. declaring method; 4. declaring class/interface.
- *
- * <p>Defaults to using the target class's caching attribute if none is
- * associated with the target method. Any caching attribute associated with
- * the target method completely overrides a class caching attribute.
- * If none found on the target class, the interface that the invoked method
- * has been called through (in case of a JDK proxy) will be checked.
- *
- * <p>This implementation caches attributes by method after they are first used.
- * If it is ever desirable to allow dynamic changing of cacheable attributes
- * (which is very unlikely), caching could be made configurable.
-
- * @author Costin Leau
- * @see org.springframework.transaction.interceptor.AbstractFallbackTransactionAttributeSource
- */
-public abstract class AbstractFallbackCacheDefinitionSource implements CacheDefinitionSource {
-
- /**
- * Canonical value held in cache to indicate no caching attribute was
- * found for this method, and we don't need to look again.
- */
- private final static CacheDefinition NULL_CACHING_ATTRIBUTE = new DefaultCacheUpdateDefinition();
-
- /**
- * Logger available to subclasses.
- * <p>As this base class is not marked Serializable, the logger will be recreated
- * after serialization - provided that the concrete subclass is Serializable.
- */
- protected final Log logger = LogFactory.getLog(getClass());
-
- /**
- * Cache of CacheOperationDefinitions, keyed by DefaultCacheKey (Method + target Class).
- * <p>As this base class is not marked Serializable, the cache will be recreated
- * after serialization - provided that the concrete subclass is Serializable.
- */
- final Map<Object, CacheDefinition> attributeCache = new ConcurrentHashMap<Object, CacheDefinition>();
-
- /**
- * Determine the caching attribute for this method invocation.
- * <p>Defaults to the class's caching attribute if no method attribute is found.
- * @param method the method for the current invocation (never <code>null</code>)
- * @param targetClass the target class for this invocation (may be <code>null</code>)
- * @return {@link CacheDefinition} for this method, or <code>null</code> if the method
- * is not cacheable
- */
- public CacheDefinition getCacheDefinition(Method method, Class<?> targetClass) {
- // First, see if we have a cached value.
- Object cacheKey = getCacheKey(method, targetClass);
- CacheDefinition cached = this.attributeCache.get(cacheKey);
- if (cached != null) {
- if (cached == NULL_CACHING_ATTRIBUTE) {
- return null;
- }
- // Value will either be canonical value indicating there is no caching attribute,
- // or an actual caching attribute.
- return cached;
- }
- else {
- // We need to work it out.
- CacheDefinition cacheDef = computeCacheOperationDefinition(method, targetClass);
- // Put it in the cache.
- if (cacheDef == null) {
- this.attributeCache.put(cacheKey, NULL_CACHING_ATTRIBUTE);
- }
- else {
- if (logger.isDebugEnabled()) {
- logger.debug("Adding cacheable method '" + method.getName() + "' with attribute: " + cacheDef);
- }
- this.attributeCache.put(cacheKey, cacheDef);
- }
- return cacheDef;
- }
- }
-
- /**
- * Determine a cache key for the given method and target class.
- * <p>Must not produce same key for overloaded methods.
- * Must produce same key for different instances of the same method.
- * @param method the method (never <code>null</code>)
- * @param targetClass the target class (may be <code>null</code>)
- * @return the cache key (never <code>null</code>)
- */
- protected Object getCacheKey(Method method, Class<?> targetClass) {
- return new DefaultCacheKey(method, targetClass);
- }
-
- /**
- * Same signature as {@link #getTransactionAttribute}, but doesn't cache the result.
- * {@link #getTransactionAttribute} is effectively a caching decorator for this method.
- * @see #getTransactionAttribute
- */
- private CacheDefinition computeCacheOperationDefinition(Method method, Class<?> targetClass) {
- // Don't allow no-public methods as required.
- if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
- return null;
- }
-
- // The method may be on an interface, but we need attributes from the target class.
- // If the target class is null, the method will be unchanged.
- Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
- // If we are dealing with method with generic parameters, find the original method.
- specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
-
- // First try is the method in the target class.
- CacheDefinition opDef = findCacheOperation(specificMethod);
- if (opDef != null) {
- return opDef;
- }
-
- // Second try is the caching operation on the target class.
- opDef = findCacheDefinition(specificMethod.getDeclaringClass());
- if (opDef != null) {
- return opDef;
- }
-
- if (specificMethod != method) {
- // Fall back is to look at the original method.
- opDef = findCacheOperation(method);
- if (opDef != null) {
- return opDef;
- }
- // Last fall back is the class of the original method.
- return findCacheDefinition(method.getDeclaringClass());
- }
- return null;
- }
-
- /**
- * Subclasses need to implement this to return the caching attribute
- * for the given method, if any.
- * @param method the method to retrieve the attribute for
- * @return all caching attribute associated with this method
- * (or <code>null</code> if none)
- */
- protected abstract CacheDefinition findCacheOperation(Method method);
-
- /**
- * Subclasses need to implement this to return the caching attribute
- * for the given class, if any.
- * @param clazz the class to retrieve the attribute for
- * @return all caching attribute associated with this class
- * (or <code>null</code> if none)
- */
- protected abstract CacheDefinition findCacheDefinition(Class<?> clazz);
-
- /**
- * Should only public methods be allowed to have caching semantics?
- * <p>The default implementation returns <code>false</code>.
- */
- protected boolean allowPublicMethodsOnly() {
- return false;
- }
-
- /**
- * Default cache key for the CacheOperationDefinition cache.
- */
- private static class DefaultCacheKey {
-
- private final Method method;
-
- private final Class<?> targetClass;
-
- public DefaultCacheKey(Method method, Class<?> targetClass) {
- this.method = method;
- this.targetClass = targetClass;
- }
-
- @Override
- public boolean equals(Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof DefaultCacheKey)) {
- return false;
- }
- DefaultCacheKey otherKey = (DefaultCacheKey) other;
- return (this.method.equals(otherKey.method) && ObjectUtils.nullSafeEquals(this.targetClass,
- otherKey.targetClass));
- }
-
- @Override
- public int hashCode() {
- return this.method.hashCode() * 29 + (this.targetClass != null ? this.targetClass.hashCode() : 0);
- }
- }
-}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/interceptor/BeanFactoryCacheDefinitionSourceAdvisor.java | @@ -1,62 +0,0 @@
-/*
- * Copyright 2010-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cache.interceptor;
-
-import org.springframework.aop.ClassFilter;
-import org.springframework.aop.Pointcut;
-import org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor;
-
-/**
- * Advisor driven by a {@link CacheDefinitionSource}, used to include a
- * transaction advice bean for methods that are transactional.
- *
- * @author Costin Leau
- */
-@SuppressWarnings("serial")
-public class BeanFactoryCacheDefinitionSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor {
-
- private CacheDefinitionSource cacheDefinitionSource;
-
- private final CacheDefinitionSourcePointcut pointcut = new CacheDefinitionSourcePointcut() {
- @Override
- protected CacheDefinitionSource getCacheDefinitionSource() {
- return cacheDefinitionSource;
- }
- };
-
- /**
- * Set the cache operation attribute source which is used to find cache
- * attributes. This should usually be identical to the source reference
- * set on the cache interceptor itself.
- * @see CacheInterceptor#setCacheAttributeSource
- */
- public void setCacheDefinitionSource(CacheDefinitionSource cacheDefinitionSource) {
- this.cacheDefinitionSource = cacheDefinitionSource;
- }
-
- /**
- * Set the {@link ClassFilter} to use for this pointcut.
- * Default is {@link ClassFilter#TRUE}.
- */
- public void setClassFilter(ClassFilter classFilter) {
- this.pointcut.setClassFilter(classFilter);
- }
-
- public Pointcut getPointcut() {
- return this.pointcut;
- }
-}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java | @@ -64,7 +64,7 @@ public abstract class CacheAspectSupport implements InitializingBean {
private CacheManager cacheManager;
- private CacheDefinitionSource cacheDefinitionSource;
+ private CacheOperationSource cacheDefinitionSource;
private final ExpressionEvaluator evaluator = new ExpressionEvaluator();
@@ -102,7 +102,7 @@ public void setCacheManager(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
- public CacheDefinitionSource getCacheDefinitionSource() {
+ public CacheOperationSource getCacheDefinitionSource() {
return cacheDefinitionSource;
}
@@ -118,31 +118,31 @@ public <K> void setKeyGenerator(KeyGenerator<K> keyGenerator) {
* Set multiple cache definition sources which are used to find the cache
* attributes. Will build a CompositeCachingDefinitionSource for the given sources.
*/
- public void setCacheDefinitionSources(CacheDefinitionSource... cacheDefinitionSources) {
+ public void setCacheDefinitionSources(CacheOperationSource... cacheDefinitionSources) {
Assert.notEmpty(cacheDefinitionSources);
- this.cacheDefinitionSource = (cacheDefinitionSources.length > 1 ? new CompositeCacheDefinitionSource(
+ this.cacheDefinitionSource = (cacheDefinitionSources.length > 1 ? new CompositeCacheOperationSource(
cacheDefinitionSources) : cacheDefinitionSources[0]);
}
- protected Collection<Cache<?, ?>> getCaches(CacheDefinition definition) {
- Set<String> cacheNames = definition.getCacheNames();
+ protected Collection<Cache<?, ?>> getCaches(CacheOperation operation) {
+ Set<String> cacheNames = operation.getCacheNames();
Collection<Cache<?, ?>> caches = new ArrayList<Cache<?, ?>>(cacheNames.size());
for (String cacheName : cacheNames) {
Cache<Object, Object> cache = cacheManager.getCache(cacheName);
if (cache == null) {
- throw new IllegalArgumentException("Cannot find cache named [" + cacheName + "] for " + definition);
+ throw new IllegalArgumentException("Cannot find cache named [" + cacheName + "] for " + operation);
}
caches.add(cache);
}
return caches;
}
- protected CacheOperationContext getOperationContext(CacheDefinition definition, Method method, Object[] args,
+ protected CacheOperationContext getOperationContext(CacheOperation operation, Method method, Object[] args,
Object target, Class<?> targetClass) {
- return new CacheOperationContext(definition, method, args, target, targetClass);
+ return new CacheOperationContext(operation, method, args, target, targetClass);
}
@SuppressWarnings("unchecked")
@@ -156,112 +156,63 @@ protected Object execute(Callable<Object> invocation, Object target, Method meth
boolean log = logger.isTraceEnabled();
- final CacheDefinition cacheDef = getCacheDefinitionSource().getCacheDefinition(method, targetClass);
+ final CacheOperation cacheOp = getCacheDefinitionSource().getCacheOperation(method, targetClass);
Object retVal = null;
// analyze caching information
- if (cacheDef != null) {
- CacheOperationContext context = getOperationContext(cacheDef, method, args, target, targetClass);
+ if (cacheOp != null) {
+ CacheOperationContext context = getOperationContext(cacheOp, method, args, target, targetClass);
Collection<Cache<?, ?>> caches = context.getCaches();
if (context.hasConditionPassed()) {
// check operation
- if (cacheDef instanceof CacheUpdateDefinition) {
+ if (cacheOp instanceof CacheUpdateOperation) {
Object key = context.generateKey();
if (log) {
- logger.trace("Computed cache key " + key + " for definition " + cacheDef);
+ logger.trace("Computed cache key " + key + " for definition " + cacheOp);
}
if (key == null) {
throw new IllegalArgumentException(
"Null key returned for cache definition (maybe you are using named params on classes without debug info?) "
- + cacheDef);
+ + cacheOp);
}
- //
- // check usage of single cache
- // very common case which allows for some optimization
- // in exchange for code readability
- //
+ // for each cache
+ boolean cacheHit = false;
- if (caches.size() == 1) {
- Cache cache = caches.iterator().next();
+ for (Iterator<Cache<?, ?>> iterator = caches.iterator(); iterator.hasNext() && !cacheHit;) {
+ Cache cache = iterator.next();
+ Cache.ValueWrapper<Object> value = cache.get(key);
- // always get the value
- retVal = cache.get(key);
- // to avoid race-conditions of entries being removed between contains/get calls
- if (cache.containsKey(key)) {
- if (log) {
- logger.trace("Key " + key + " found in cache, returning value " + retVal);
- }
- return retVal;
- } else {
- if (log) {
- logger.trace("Key " + key + " NOT found in cache, invoking target method for caching "
- + method);
- }
-
- retVal = invocation.call();
- cache.put(key, retVal);
+ if (value != null) {
+ cacheHit = true;
+ retVal = value.get();
}
}
- //
- // multi cache path
- //
- else {
- // to avoid the contains/get race condition we can:
- // a. get the value in advanced (aka 'eagerGet')
- // b. double check 'contains' before and after get
- // a implies more calls in total if more then 3 caches are used (n*2 calls)
- // b uses less calls in total but is 1 call heavier for one cache (n+2 calls)
- // --
- // for balance, a) is used for up to 3 caches, b for more then 4
-
- boolean eagerGet = caches.size() <= 3;
-
- // for each cache
- boolean cacheHit = false;
-
- for (Iterator<Cache<?, ?>> iterator = caches.iterator(); iterator.hasNext() && !cacheHit;) {
- Cache cache = iterator.next();
- if (eagerGet) {
- retVal = cache.get(key);
- }
- if (cache.containsKey(key)) {
- if (eagerGet) {
- cacheHit = true;
- } else {
- retVal = cache.get(key);
- cacheHit = cache.containsKey(key);
- }
- }
+ if (!cacheHit) {
+ if (log) {
+ logger.trace("Key " + key + " NOT found in cache(s), invoking cached target method "
+ + method);
}
-
- if (!cacheHit) {
- if (log) {
- logger.trace("Key " + key + " NOT found in cache(s), invoking cached target method "
- + method);
- }
- retVal = invocation.call();
- }
- else {
- if (log) {
- logger.trace("Key " + key + " found in cache, returning value " + retVal);
- }
+ retVal = invocation.call();
+ } else {
+ if (log) {
+ logger.trace("Key " + key + " found in cache, returning value " + retVal);
}
+ }
- // update all caches (if needed)
- for (Cache cache : caches) {
- cache.putIfAbsent(key, retVal);
- }
+ // update all caches
+ for (Cache cache : caches) {
+ cache.put(key, retVal);
}
}
- if (cacheDef instanceof CacheInvalidateDefinition) {
- CacheInvalidateDefinition invalidateDef = (CacheInvalidateDefinition) cacheDef;
+ if (cacheOp instanceof CacheEvictOperation) {
+ CacheEvictOperation evictOp = (CacheEvictOperation) cacheOp;
retVal = invocation.call();
// for each cache
@@ -270,10 +221,10 @@ protected Object execute(Callable<Object> invocation, Object target, Method meth
for (Cache cache : caches) {
// flush the cache (ignore arguments)
- if (invalidateDef.isCacheWide()) {
+ if (evictOp.isCacheWide()) {
cache.clear();
if (log) {
- logger.trace("Invalidating entire cache for definition " + cacheDef + " on method "
+ logger.trace("Invalidating entire cache for definition " + cacheOp + " on method "
+ method);
}
} else {
@@ -282,19 +233,18 @@ protected Object execute(Callable<Object> invocation, Object target, Method meth
key = context.generateKey();
}
if (log) {
- logger.trace("Invalidating cache key " + key + " for definition " + cacheDef
+ logger.trace("Invalidating cache key " + key + " for definition " + cacheOp
+ " on method " + method);
}
- cache.remove(key);
+ cache.evict(key);
}
}
}
return retVal;
- }
- else {
+ } else {
if (log) {
- logger.trace("Cache condition failed on method " + method + " for definition " + cacheDef);
+ logger.trace("Cache condition failed on method " + method + " for definition " + cacheOp);
}
}
}
@@ -304,7 +254,7 @@ protected Object execute(Callable<Object> invocation, Object target, Method meth
protected class CacheOperationContext {
- private CacheDefinition definition;
+ private CacheOperation operation;
private final Collection<Cache<?, ?>> caches;
private final Object target;
private final Method method;
@@ -315,10 +265,10 @@ protected class CacheOperationContext {
private final KeyGenerator<?> keyGenerator = CacheAspectSupport.this.keyGenerator;
- public CacheOperationContext(CacheDefinition operationDefinition, Method method, Object[] args,
- Object target, Class<?> targetClass) {
- this.definition = operationDefinition;
- this.caches = CacheAspectSupport.this.getCaches(definition);
+ public CacheOperationContext(CacheOperation operation, Method method, Object[] args, Object target,
+ Class<?> targetClass) {
+ this.operation = operation;
+ this.caches = CacheAspectSupport.this.getCaches(operation);
this.target = target;
this.method = method;
this.args = args;
@@ -329,29 +279,29 @@ public CacheOperationContext(CacheDefinition operationDefinition, Method method,
/**
* Evaluates the definition condition.
*
- * @param definition
+ * @param operation
* @return
*/
protected boolean hasConditionPassed() {
- if (StringUtils.hasText(definition.getCondition())) {
- return evaluator.condition(definition.getCondition(), method, evalContext);
+ if (StringUtils.hasText(operation.getCondition())) {
+ return evaluator.condition(operation.getCondition(), method, evalContext);
}
return true;
}
/**
* Computes the key for the given caching definition.
*
- * @param definition
+ * @param operation
* @param method
* method being invoked
* @param objects
* arguments passed during the method invocation
* @return generated key (null if none can be generated)
*/
protected Object generateKey() {
- if (StringUtils.hasText(definition.getKey())) {
- return evaluator.key(definition.getKey(), method, evalContext);
+ if (StringUtils.hasText(operation.getKey())) {
+ return evaluator.key(operation.getKey(), method, evalContext);
}
return keyGenerator.extract(target, method, args);
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheDefinition.java | @@ -1,58 +0,0 @@
-/*
- * Copyright 2010-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cache.interceptor;
-
-import java.util.Set;
-
-/**
- * Interface describing Spring-compliant caching operation.
- *
- * @author Costin Leau
- */
-public interface CacheDefinition {
-
- /**
- * Returns the name of this operation. Can be <tt>null</tt>.
- * In case of Spring's declarative caching, the exposed name will be:
- * <tt>fully qualified class name.method name</tt>.
- *
- * @return the operation name
- */
- String getName();
-
- /**
- * Returns the names of the cache against which this operation is performed.
- *
- * @return names of the cache on which the operation is performed.
- */
- Set<String> getCacheNames();
-
- /**
- * Returns the SpEL expression conditioning the operation.
- *
- * @return operation condition (as SpEL expression).
- */
- String getCondition();
-
- /**
- * Returns the SpEL expression identifying the cache key.
- *
- * @return
- */
- String getKey();
-
-}
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheDefinitionSource.java | @@ -1,41 +0,0 @@
-/*
- * Copyright 2010-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cache.interceptor;
-
-import java.lang.reflect.Method;
-
-
-/**
- * Interface used by CacheInterceptor. Implementations know
- * how to source cache operation attributes, whether from configuration,
- * metadata attributes at source level, or anywhere else.
- *
- * @author Costin Leau
- */
-public interface CacheDefinitionSource {
-
- /**
- * Return the cache operation definition for this method.
- * Return null if the method is not cacheable.
- * @param method method
- * @param targetClass target class. May be <code>null</code>, in which
- * case the declaring class of the method must be used.
- * @return {@link CacheDefinition} the matching cache operation definition,
- * or <code>null</code> if none found
- */
- CacheDefinition getCacheDefinition(Method method, Class<?> targetClass);
-}
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheDefinitionSourcePointcut.java | @@ -1,68 +0,0 @@
-/*
- * Copyright 2010-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cache.interceptor;
-
-import java.io.Serializable;
-import java.lang.reflect.Method;
-
-import org.springframework.aop.support.StaticMethodMatcherPointcut;
-import org.springframework.util.ObjectUtils;
-
-/**
- * Inner class that implements a Pointcut that matches if the underlying
- * {@link CacheDefinitionSource} has an attribute for a given method.
- *
- * @author Costin Leau
- */
-@SuppressWarnings("serial")
-abstract class CacheDefinitionSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {
-
- public boolean matches(Method method, Class<?> targetClass) {
- CacheDefinitionSource cas = getCacheDefinitionSource();
- return (cas == null || cas.getCacheDefinition(method, targetClass) != null);
- }
-
- @Override
- public boolean equals(Object other) {
- if (this == other) {
- return true;
- }
- if (!(other instanceof CacheDefinitionSourcePointcut)) {
- return false;
- }
- CacheDefinitionSourcePointcut otherPc = (CacheDefinitionSourcePointcut) other;
- return ObjectUtils.nullSafeEquals(getCacheDefinitionSource(),
- otherPc.getCacheDefinitionSource());
- }
-
- @Override
- public int hashCode() {
- return CacheDefinitionSourcePointcut.class.hashCode();
- }
-
- @Override
- public String toString() {
- return getClass().getName() + ": " + getCacheDefinitionSource();
- }
-
-
- /**
- * Obtain the underlying CacheOperationDefinitionSource (may be <code>null</code>).
- * To be implemented by subclasses.
- */
- protected abstract CacheDefinitionSource getCacheDefinitionSource();
-}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheInvalidateDefinition.java | @@ -1,33 +0,0 @@
-/*
- * Copyright 2010-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cache.interceptor;
-
-
-/**
- * Interface describing a Spring cache invalidation.
- *
- * @author Costin Leau
- */
-public interface CacheInvalidateDefinition extends CacheDefinition {
-
- /**
- * Returns whether the operation affects the entire cache or not.
- *
- * @return whether the operation is cache wide or not.
- */
- boolean isCacheWide();
-}
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheProxyFactoryBean.java | @@ -49,7 +49,7 @@ protected Object createMainInterceptor() {
*
* @param cacheDefinitionSources cache definition sources
*/
- public void setCacheDefinitionSources(CacheDefinitionSource... cacheDefinitionSources) {
+ public void setCacheDefinitionSources(CacheOperationSource... cacheDefinitionSources) {
this.cachingInterceptor.setCacheDefinitionSources(cacheDefinitionSources);
}
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CacheUpdateDefinition.java | @@ -1,32 +0,0 @@
-/*
- * Copyright 2010-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cache.interceptor;
-
-/**
- * Interface describing a Spring cache update.
- *
- * @author Costin Leau
- */
-public interface CacheUpdateDefinition extends CacheDefinition {
-
- /**
- * Returns the SpEL expression identifying the cache key.
- *
- * @return
- */
- String getKey();
-}
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/interceptor/CompositeCacheDefinitionSource.java | @@ -1,63 +0,0 @@
-/*
- * Copyright 2010-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cache.interceptor;
-
-import java.io.Serializable;
-import java.lang.reflect.Method;
-
-import org.springframework.util.Assert;
-
-/**
- * Composite {@link CacheDefinitionSource} implementation that iterates
- * over a given array of {@link CacheDefinitionSource} instances.
- *
- * @author Costin Leau
- */
-@SuppressWarnings("serial")
-public class CompositeCacheDefinitionSource implements CacheDefinitionSource, Serializable {
-
- private final CacheDefinitionSource[] cacheDefinitionSources;
-
- /**
- * Create a new CompositeCachingDefinitionSource for the given sources.
- * @param cacheDefinitionSourcess the CacheDefinitionSource instances to combine
- */
- public CompositeCacheDefinitionSource(CacheDefinitionSource[] cacheDefinitionSources) {
- Assert.notNull(cacheDefinitionSources, "cacheDefinitionSource array must not be null");
- this.cacheDefinitionSources = cacheDefinitionSources;
- }
-
- /**
- * Return the CacheDefinitionSource instances that this
- * CompositeCachingDefinitionSource combines.
- */
- public final CacheDefinitionSource[] getCacheDefinitionSources() {
- return this.cacheDefinitionSources;
- }
-
-
- public CacheDefinition getCacheDefinition(Method method, Class<?> targetClass) {
- for (CacheDefinitionSource source : cacheDefinitionSources) {
- CacheDefinition definition = source.getCacheDefinition(method, targetClass);
- if (definition != null) {
- return definition;
- }
- }
-
- return null;
- }
-}
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/interceptor/DefaultCacheInvalidateDefinition.java | @@ -1,44 +0,0 @@
-/*
- * Copyright 2010-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cache.interceptor;
-
-/**
- * Default implementation of the {@link CacheInvalidateDefinition} interface.
- *
- * @author Costin Leau
- */
-public class DefaultCacheInvalidateDefinition extends AbstractCacheDefinition implements
- CacheInvalidateDefinition {
-
- private boolean cacheWide = false;
-
- public boolean isCacheWide() {
- return cacheWide;
- }
-
- public void setCacheWide(boolean cacheWide) {
- this.cacheWide = cacheWide;
- }
-
- @Override
- protected StringBuilder getDefinitionDescription() {
- StringBuilder sb = super.getDefinitionDescription();
- sb.append(",");
- sb.append(cacheWide);
- return sb;
- }
-}
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/interceptor/DefaultCacheUpdateDefinition.java | @@ -1,27 +0,0 @@
-/*
- * Copyright 2010-2011 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.cache.interceptor;
-
-/**
- * Default implementation of the {@link CacheUpdateDefinition} interface.
- *
- * @author Costin Leau
- */
-public class DefaultCacheUpdateDefinition extends AbstractCacheDefinition implements CacheUpdateDefinition {
-
-
-}
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/main/java/org/springframework/cache/support/AbstractDelegatingCache.java | @@ -20,14 +20,16 @@
import java.util.Map;
import org.springframework.cache.Cache;
+import org.springframework.cache.interceptor.DefaultValue;
import org.springframework.util.Assert;
/**
* Abstract base class delegating most of the {@link Map}-like methods
* to the underlying cache.
*
- * <b>Note:</b>Allows null values to be stored, even if the underlying map
- * does not support them.
+ * <b>Note:</b>Allows null values to be stored even (for cases where the
+ * underlying cache does not support them) as long as arbitrary serialized
+ * objects are supported.
*
* @author Costin Leau
*/
@@ -57,7 +59,7 @@ public <D extends Map<K, V>> AbstractDelegatingCache(D delegate) {
*
* @param <D> map type
* @param delegate map delegate
- * @param allowNullValues flag indicating whether null values are allowed or not
+ * @param allowNullValues flag indicating whether null values should be replaced or not
*/
public <D extends Map<K, V>> AbstractDelegatingCache(D delegate, boolean allowNullValues) {
Assert.notNull(delegate);
@@ -73,30 +75,22 @@ public void clear() {
delegate.clear();
}
- public boolean containsKey(Object key) {
- return delegate.containsKey(key);
- }
-
- public V get(Object key) {
- return filterNull(delegate.get(key));
+ public ValueWrapper<V> get(Object key) {
+ return new DefaultValue<V>(filterNull(delegate.get(key)));
}
@SuppressWarnings("unchecked")
- public V put(K key, V value) {
+ public void put(K key, V value) {
if (allowNullValues && value == null) {
Map map = delegate;
- Object val = map.put(key, NULL_HOLDER);
- if (val == NULL_HOLDER) {
- return null;
- }
- return (V) val;
+ map.put(key, NULL_HOLDER);
}
- return filterNull(delegate.put(key, value));
+ delegate.put(key, value);
}
- public V remove(Object key) {
- return filterNull(delegate.remove(key));
+ public void evict(Object key) {
+ delegate.remove(key);
}
protected V filterNull(V val) {
| true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/test/java/org/springframework/cache/ehcache/EhCacheCacheTest.java | @@ -54,11 +54,9 @@ public void testExpiredElements() throws Exception {
brancusi.setTimeToLive(3);
nativeCache.put(brancusi);
- assertTrue(cache.containsKey(key));
- assertEquals(value, cache.get(key));
+ assertEquals(value, cache.get(key).get());
// wait for the entry to expire
Thread.sleep(5 * 1000);
- assertFalse("expired entry returned", cache.containsKey(key));
assertNull(cache.get(key));
}
}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 0b917e3f9ced6449fdc47a5fcae2105e94212c28.json | revise cache API
- eliminate unneeded methods
+ introduced value wrapper (name still to be decided) to avoid cache race conditions
+ improved name consistency | org.springframework.context/src/test/java/org/springframework/cache/vendor/AbstractNativeCacheTest.java | @@ -58,7 +58,6 @@ public void testNativeCache() throws Exception {
@Test
public void testCachePut() throws Exception {
-
Object key = "enescu";
Object value = "george";
@@ -74,8 +73,6 @@ public void testCacheRemove() throws Exception {
assertNull(cache.get(key));
cache.put(key, value);
- assertEquals(value, cache.remove(key));
- assertNull(cache.get(key));
}
@Test
@@ -88,66 +85,4 @@ public void testCacheClear() throws Exception {
assertNull(cache.get("vlaicu"));
assertNull(cache.get("enescu"));
}
-
- // concurrent map tests
- @Test
- public void testPutIfAbsent() throws Exception {
- Object key = "enescu";
- Object value1 = "george";
- Object value2 = "geo";
-
- assertNull(cache.get("enescu"));
- cache.put(key, value1);
- cache.putIfAbsent(key, value2);
- assertEquals(value1, cache.get(key));
- }
-
- @Test
- public void testConcurrentRemove() throws Exception {
- Object key = "enescu";
- Object value1 = "george";
- Object value2 = "geo";
-
- assertNull(cache.get("enescu"));
- cache.put(key, value1);
- // no remove
- cache.remove(key, value2);
- assertEquals(value1, cache.get(key));
- // one remove
- cache.remove(key, value1);
- assertNull(cache.get("enescu"));
- }
-
- @Test
- public void testConcurrentReplace() throws Exception {
- Object key = "enescu";
- Object value1 = "george";
- Object value2 = "geo";
-
- assertNull(cache.get("enescu"));
- cache.put(key, value1);
- cache.replace(key, value2);
- assertEquals(value2, cache.get(key));
- cache.remove(key);
- cache.replace(key, value1);
- assertNull(cache.get("enescu"));
- }
-
- @Test
- public void testConcurrentReplaceIfEqual() throws Exception {
- Object key = "enescu";
- Object value1 = "george";
- Object value2 = "geo";
-
- assertNull(cache.get("enescu"));
- cache.put(key, value1);
- assertEquals(value1, cache.get(key));
- // no replace
- cache.replace(key, value2, value1);
- assertEquals(value1, cache.get(key));
- cache.replace(key, value1, value2);
- assertEquals(value2, cache.get(key));
- cache.replace(key, value2, value1);
- assertEquals(value1, cache.get(key));
- }
}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 2afeb08e3c387715374c81a82074bae4235b5082.json | Fix @Autowired+@PostConstruct+@Configuration issue
A subtle issue existed with the way we relied on isCurrentlyInCreation
to determine whether a @Bean method is being called by the container
or by user code. This worked in most cases, but in the particular
scenario laid out by SPR-8080, this approach was no longer sufficient.
This change introduces a ThreadLocal that contains the factory method
currently being invoked by the container, such that enhanced @Bean
methods can check against it to see if they are being called by the
container or not. If so, that is the cue that the user-defined @Bean
method implementation should be invoked in order to actually create
the bean for the first time. If not, then the cached instance of
the already-created bean should be looked up and returned.
See ConfigurationClassPostConstructAndAutowiringTests for
reproduction cases and more detail.
Issue: SPR-8080 | org.springframework.beans/src/main/java/org/springframework/beans/factory/config/ConfigurableBeanFactory.java | @@ -320,6 +320,15 @@ public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, Single
*/
boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException;
+ /**
+ * Explicitly control in-creation status of the specified bean. For
+ * container internal use only.
+ * @param beanName the name of the bean
+ * @param inCreation whether the bean is currently in creation
+ * @since 3.1
+ */
+ void setCurrentlyInCreation(String beanName, boolean inCreation);
+
/**
* Determine whether the specified bean is currently in creation.
* @param beanName the name of the bean | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.