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 | 6d882b149d0b32bab116a49ac5486abeb819f4f1.json | Add targetIsClass to SpEL property cache key
Update the `CacheKey` class used by `ReflectivePropertyAccessor` to
include if the target object is class. The prevents an incorrect cache
hit from being returned when a property with the same name is read on
both an object and its class. For example:
#{class.name}
#{name}
Issue: SPR-10486 | spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java | @@ -29,6 +29,7 @@
import org.springframework.core.MethodParameter;
import org.springframework.core.convert.Property;
import org.springframework.core.convert.TypeDescriptor;
+import org.springframework.core.style.ToStringCreator;
import org.springframework.expression.AccessException;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.EvaluationException;
@@ -73,7 +74,7 @@ public boolean canRead(EvaluationContext context, Object target, String name) th
if (type.isArray() && name.equals("length")) {
return true;
}
- CacheKey cacheKey = new CacheKey(type, name);
+ CacheKey cacheKey = new CacheKey(type, name, target instanceof Class);
if (this.readerCache.containsKey(cacheKey)) {
return true;
}
@@ -113,7 +114,7 @@ public TypedValue read(EvaluationContext context, Object target, String name) th
return new TypedValue(Array.getLength(target));
}
- CacheKey cacheKey = new CacheKey(type, name);
+ CacheKey cacheKey = new CacheKey(type, name, target instanceof Class);
InvokerPair invoker = this.readerCache.get(cacheKey);
if (invoker == null || invoker.member instanceof Method) {
@@ -172,7 +173,7 @@ public boolean canWrite(EvaluationContext context, Object target, String name) t
return false;
}
Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());
- CacheKey cacheKey = new CacheKey(type, name);
+ CacheKey cacheKey = new CacheKey(type, name, target instanceof Class);
if (this.writerCache.containsKey(cacheKey)) {
return true;
}
@@ -214,7 +215,7 @@ public void write(EvaluationContext context, Object target, String name, Object
throw new AccessException("Type conversion failure",evaluationException);
}
}
- CacheKey cacheKey = new CacheKey(type, name);
+ CacheKey cacheKey = new CacheKey(type, name, target instanceof Class);
Member cachedMember = this.writerCache.get(cacheKey);
if (cachedMember == null || cachedMember instanceof Method) {
@@ -271,7 +272,7 @@ private TypeDescriptor getTypeDescriptor(EvaluationContext context, Object targe
if (type.isArray() && name.equals("length")) {
return TypeDescriptor.valueOf(Integer.TYPE);
}
- CacheKey cacheKey = new CacheKey(type, name);
+ CacheKey cacheKey = new CacheKey(type, name, target instanceof Class);
TypeDescriptor typeDescriptor = this.typeDescriptorCache.get(cacheKey);
if (typeDescriptor == null) {
// attempt to populate the cache entry
@@ -431,7 +432,7 @@ public PropertyAccessor createOptimalAccessor(EvaluationContext eContext, Object
return this;
}
- CacheKey cacheKey = new CacheKey(type, name);
+ CacheKey cacheKey = new CacheKey(type, name, target instanceof Class);
InvokerPair invocationTarget = this.readerCache.get(cacheKey);
if (invocationTarget == null || invocationTarget.member instanceof Method) {
@@ -490,9 +491,12 @@ private static class CacheKey {
private final String name;
- public CacheKey(Class clazz, String name) {
+ private boolean targetIsClass;
+
+ public CacheKey(Class clazz, String name, boolean targetIsClass) {
this.clazz = clazz;
this.name = name;
+ this.targetIsClass = targetIsClass;
}
@Override
@@ -504,13 +508,23 @@ public boolean equals(Object other) {
return false;
}
CacheKey otherKey = (CacheKey) other;
- return (this.clazz.equals(otherKey.clazz) && this.name.equals(otherKey.name));
+ boolean rtn = true;
+ rtn &= this.clazz.equals(otherKey.clazz);
+ rtn &= this.name.equals(otherKey.name);
+ rtn &= this.targetIsClass == otherKey.targetIsClass;
+ return rtn;
}
@Override
public int hashCode() {
return this.clazz.hashCode() * 29 + this.name.hashCode();
}
+
+ @Override
+ public String toString() {
+ return new ToStringCreator(this).append("clazz", this.clazz).append("name",
+ this.name).append("targetIsClass", this.targetIsClass).toString();
+ }
}
| true |
Other | spring-projects | spring-framework | 6d882b149d0b32bab116a49ac5486abeb819f4f1.json | Add targetIsClass to SpEL property cache key
Update the `CacheKey` class used by `ReflectivePropertyAccessor` to
include if the target object is class. The prevents an incorrect cache
hit from being returned when a property with the same name is read on
both an object and its class. For example:
#{class.name}
#{name}
Issue: SPR-10486 | spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java | @@ -1820,6 +1820,19 @@ public TypedValue execute(EvaluationContext context, Object target, Object... ar
assertEquals(XYZ.Z, Array.get(result, 2));
}
+ @Test
+ public void SPR_10486() throws Exception {
+ SpelExpressionParser parser = new SpelExpressionParser();
+ StandardEvaluationContext context = new StandardEvaluationContext();
+ SPR10486 rootObject = new SPR10486();
+ Expression classNameExpression = parser.parseExpression("class.name");
+ Expression nameExpression = parser.parseExpression("name");
+ assertThat(classNameExpression.getValue(context, rootObject),
+ equalTo((Object) SPR10486.class.getName()));
+ assertThat(nameExpression.getValue(context, rootObject),
+ equalTo((Object) "name"));
+ }
+
private static enum ABC {A, B, C}
@@ -1887,4 +1900,20 @@ public static class StaticFinalImpl1 extends AbstractStaticFinal implements Stat
public static class StaticFinalImpl2 extends AbstractStaticFinal {
}
+ /**
+ * The Class TestObject.
+ */
+ public static class SPR10486 {
+
+ private String name = "name";
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ }
} | true |
Other | spring-projects | spring-framework | 7658d856cac027ae367f04833bee6c43c62b5534.json | Assert context uniqueness against merged config
Prior to this commit, the uniqueness check for @ContextConfiguration
attributes within a @ContextHierarchy was performed at a single test
class level instead of against the merged configuration for all test
class levels in the test class hierarchy.
This commit addresses this issue by moving the uniqueness check
algorithm from resolveContextHierarchyAttributes() to
buildContextHierarchyMap() within ContextLoaderUtils.
Issue: SPR-10997 | spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java | @@ -237,11 +237,9 @@ private static void convertContextConfigToConfigAttributesAndAddToList(ContextCo
* never {@code null}
* @throws IllegalArgumentException if the supplied class is {@code null}; if
* neither {@code @ContextConfiguration} nor {@code @ContextHierarchy} is
- * <em>present</em> on the supplied class; if a given class in the class hierarchy
+ * <em>present</em> on the supplied class; or if a given class in the class hierarchy
* declares both {@code @ContextConfiguration} and {@code @ContextHierarchy} as
- * top-level annotations; or if individual {@code @ContextConfiguration}
- * elements within a {@code @ContextHierarchy} declaration on a given class
- * in the class hierarchy do not define unique context configuration.
+ * top-level annotations.
*
* @since 3.2.2
* @see #buildContextHierarchyMap(Class)
@@ -287,17 +285,6 @@ else if (contextHierarchyDeclaredLocally) {
convertContextConfigToConfigAttributesAndAddToList(contextConfiguration, declaringClass,
configAttributesList);
}
-
- // Check for uniqueness
- Set<ContextConfigurationAttributes> configAttributesSet = new HashSet<ContextConfigurationAttributes>(
- configAttributesList);
- if (configAttributesSet.size() != configAttributesList.size()) {
- String msg = String.format("The @ContextConfiguration elements configured via "
- + "@ContextHierarchy in test class [%s] must define unique contexts to load.",
- declaringClass.getName());
- logger.error(msg);
- throw new IllegalStateException(msg);
- }
}
else {
// This should theoretically actually never happen...
@@ -336,6 +323,9 @@ else if (contextHierarchyDeclaredLocally) {
* (must not be {@code null})
* @return a map of context configuration attributes for the context hierarchy,
* keyed by context hierarchy level name; never {@code null}
+ * @throws IllegalArgumentException if the lists of context configuration
+ * attributes for each level in the {@code @ContextHierarchy} do not define
+ * unique context configuration within the overall hierarchy.
*
* @since 3.2.2
* @see #resolveContextHierarchyAttributes(Class)
@@ -363,6 +353,16 @@ static Map<String, List<ContextConfigurationAttributes>> buildContextHierarchyMa
}
}
+ // Check for uniqueness
+ Set<List<ContextConfigurationAttributes>> set = new HashSet<List<ContextConfigurationAttributes>>(map.values());
+ if (set.size() != map.size()) {
+ String msg = String.format("The @ContextConfiguration elements configured via "
+ + "@ContextHierarchy in test class [%s] and its superclasses must "
+ + "define unique contexts per hierarchy level.", testClass.getName());
+ logger.error(msg);
+ throw new IllegalStateException(msg);
+ }
+
return map;
}
| true |
Other | spring-projects | spring-framework | 7658d856cac027ae367f04833bee6c43c62b5534.json | Assert context uniqueness against merged config
Prior to this commit, the uniqueness check for @ContextConfiguration
attributes within a @ContextHierarchy was performed at a single test
class level instead of against the merged configuration for all test
class levels in the test class hierarchy.
This commit addresses this issue by moving the uniqueness check
algorithm from resolveContextHierarchyAttributes() to
buildContextHierarchyMap() within ContextLoaderUtils.
Issue: SPR-10997 | spring-test/src/test/java/org/springframework/test/context/ContextLoaderUtilsContextHierarchyTests.java | @@ -21,6 +21,8 @@
import java.util.Map;
import org.junit.Test;
+import org.springframework.context.ApplicationContextInitializer;
+import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import static org.hamcrest.CoreMatchers.*;
@@ -152,29 +154,6 @@ public void resolveContextHierarchyAttributesForTestClassHierarchyWithMultiLevel
assertThat(configAttributesListClassLevel3.get(2).getLocations()[0], equalTo("3-C.xml"));
}
- private void assertContextConfigEntriesAreNotUnique(Class<?> testClass) {
- try {
- resolveContextHierarchyAttributes(testClass);
- fail("Should throw an IllegalStateException");
- }
- catch (IllegalStateException e) {
- String msg = String.format(
- "The @ContextConfiguration elements configured via @ContextHierarchy in test class [%s] must define unique contexts to load.",
- testClass.getName());
- assertEquals(msg, e.getMessage());
- }
- }
-
- @Test
- public void resolveContextHierarchyAttributesForSingleTestClassWithMultiLevelContextHierarchyWithEmptyContextConfig() {
- assertContextConfigEntriesAreNotUnique(SingleTestClassWithMultiLevelContextHierarchyWithEmptyContextConfig.class);
- }
-
- @Test
- public void resolveContextHierarchyAttributesForSingleTestClassWithMultiLevelContextHierarchyWithDuplicatedContextConfig() {
- assertContextConfigEntriesAreNotUnique(SingleTestClassWithMultiLevelContextHierarchyWithDuplicatedContextConfig.class);
- }
-
@Test
public void buildContextHierarchyMapForTestClassHierarchyWithMultiLevelContextHierarchies() {
Map<String, List<ContextConfigurationAttributes>> map = buildContextHierarchyMap(TestClass3WithMultiLevelContextHierarchy.class);
@@ -262,6 +241,58 @@ public void buildContextHierarchyMapForTestClassHierarchyWithMultiLevelContextHi
assertThat(level3Config.get(0).getLocations()[0], is("2-C.xml"));
}
+ private void assertContextConfigEntriesAreNotUnique(Class<?> testClass) {
+ try {
+ buildContextHierarchyMap(testClass);
+ fail("Should throw an IllegalStateException");
+ }
+ catch (IllegalStateException e) {
+ String msg = String.format(
+ "The @ContextConfiguration elements configured via @ContextHierarchy in test class [%s] and its superclasses must define unique contexts per hierarchy level.",
+ testClass.getName());
+ assertEquals(msg, e.getMessage());
+ }
+ }
+
+ @Test
+ public void buildContextHierarchyMapForSingleTestClassWithMultiLevelContextHierarchyWithEmptyContextConfig() {
+ assertContextConfigEntriesAreNotUnique(SingleTestClassWithMultiLevelContextHierarchyWithEmptyContextConfig.class);
+ }
+
+ @Test
+ public void buildContextHierarchyMapForSingleTestClassWithMultiLevelContextHierarchyWithDuplicatedContextConfig() {
+ assertContextConfigEntriesAreNotUnique(SingleTestClassWithMultiLevelContextHierarchyWithDuplicatedContextConfig.class);
+ }
+
+ /**
+ * Used to reproduce bug reported in https://jira.springsource.org/browse/SPR-10997
+ */
+ @Test
+ public void buildContextHierarchyMapForTestClassHierarchyWithMultiLevelContextHierarchiesAndOverriddenInitializers() {
+ Map<String, List<ContextConfigurationAttributes>> map = buildContextHierarchyMap(TestClass2WithMultiLevelContextHierarchyWithOverriddenInitializers.class);
+
+ assertThat(map.size(), is(2));
+ assertThat(map.keySet(), hasItems("alpha", "beta"));
+
+ List<ContextConfigurationAttributes> alphaConfig = map.get("alpha");
+ assertThat(alphaConfig.size(), is(2));
+ assertThat(alphaConfig.get(0).getLocations().length, is(1));
+ assertThat(alphaConfig.get(0).getLocations()[0], is("1-A.xml"));
+ assertThat(alphaConfig.get(0).getInitializers().length, is(0));
+ assertThat(alphaConfig.get(1).getLocations().length, is(0));
+ assertThat(alphaConfig.get(1).getInitializers().length, is(1));
+ assertEquals(DummyApplicationContextInitializer.class, alphaConfig.get(1).getInitializers()[0]);
+
+ List<ContextConfigurationAttributes> betaConfig = map.get("beta");
+ assertThat(betaConfig.size(), is(2));
+ assertThat(betaConfig.get(0).getLocations().length, is(1));
+ assertThat(betaConfig.get(0).getLocations()[0], is("1-B.xml"));
+ assertThat(betaConfig.get(0).getInitializers().length, is(0));
+ assertThat(betaConfig.get(1).getLocations().length, is(0));
+ assertThat(betaConfig.get(1).getInitializers().length, is(1));
+ assertEquals(DummyApplicationContextInitializer.class, betaConfig.get(1).getInitializers()[0]);
+ }
+
// -------------------------------------------------------------------------
@@ -401,4 +432,40 @@ private static class SingleTestClassWithMultiLevelContextHierarchyWithEmptyConte
private static class SingleTestClassWithMultiLevelContextHierarchyWithDuplicatedContextConfig {
}
+ /**
+ * Used to reproduce bug reported in https://jira.springsource.org/browse/SPR-10997
+ */
+ @ContextHierarchy({//
+ //
+ @ContextConfiguration(name = "alpha", locations = "1-A.xml"),//
+ @ContextConfiguration(name = "beta", locations = "1-B.xml") //
+ })
+ private static class TestClass1WithMultiLevelContextHierarchyWithUniqueContextConfig {
+ }
+
+ /**
+ * Used to reproduce bug reported in https://jira.springsource.org/browse/SPR-10997
+ */
+ @ContextHierarchy({//
+ //
+ @ContextConfiguration(name = "alpha", initializers = DummyApplicationContextInitializer.class),//
+ @ContextConfiguration(name = "beta", initializers = DummyApplicationContextInitializer.class) //
+ })
+ private static class TestClass2WithMultiLevelContextHierarchyWithOverriddenInitializers extends
+ TestClass1WithMultiLevelContextHierarchyWithUniqueContextConfig {
+ }
+
+ /**
+ * Used to reproduce bug reported in https://jira.springsource.org/browse/SPR-10997
+ */
+ private static class DummyApplicationContextInitializer implements
+ ApplicationContextInitializer<ConfigurableApplicationContext> {
+
+ @Override
+ public void initialize(ConfigurableApplicationContext applicationContext) {
+ /* no-op */
+ }
+
+ }
+
} | true |
Other | spring-projects | spring-framework | b25e91a550beaf428a6e696959b717341a04f27d.json | Relax JavaBean rules for SpEL property access
Relax the method search algorithm used by `ReflectivePropertyAccessor`
to include methods of the form `getXY()` for properties of the form
`xy`.
Although the JavaBean specification indicates that a property `xy`
should use the accessors `getxY()` and `setxY()`, in practice many
developers choose to have an uppercase first character. The
`ReflectivePropertyAccessor` will now consider these style methods if
the traditional conventions fail to find a match.
Issue: SPR-10716 | spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java | @@ -318,42 +318,34 @@ private Field findField(String name, Class<?> clazz, Object target) {
* Find a getter method for the specified property.
*/
protected Method findGetterForProperty(String propertyName, Class<?> clazz, boolean mustBeStatic) {
- Method[] ms = getSortedClassMethods(clazz);
- String propertyMethodSuffix = getPropertyMethodSuffix(propertyName);
-
- // Try "get*" method...
- String getterName = "get" + propertyMethodSuffix;
- for (Method method : ms) {
- if (method.getName().equals(getterName) && method.getParameterTypes().length == 0 &&
- (!mustBeStatic || Modifier.isStatic(method.getModifiers()))) {
- return method;
- }
- }
- // Try "is*" method...
- getterName = "is" + propertyMethodSuffix;
- for (Method method : ms) {
- if (method.getName().equals(getterName) && method.getParameterTypes().length == 0 &&
- (boolean.class.equals(method.getReturnType()) || Boolean.class.equals(method.getReturnType())) &&
- (!mustBeStatic || Modifier.isStatic(method.getModifiers()))) {
- return method;
- }
- }
- return null;
+ return findMethodForProperty(getPropertyMethodSuffixes(propertyName),
+ new String[] { "get", "is" }, clazz, mustBeStatic, 0);
}
/**
* Find a setter method for the specified property.
*/
protected Method findSetterForProperty(String propertyName, Class<?> clazz, boolean mustBeStatic) {
+ return findMethodForProperty(getPropertyMethodSuffixes(propertyName),
+ new String[] { "set" }, clazz, mustBeStatic, 1);
+ }
+
+ private Method findMethodForProperty(String[] methodSuffixes, String[] prefixes, Class<?> clazz,
+ boolean mustBeStatic, int numberOfParams) {
Method[] methods = getSortedClassMethods(clazz);
- String setterName = "set" + getPropertyMethodSuffix(propertyName);
- for (Method method : methods) {
- if (method.getName().equals(setterName) && method.getParameterTypes().length == 1 &&
- (!mustBeStatic || Modifier.isStatic(method.getModifiers()))) {
- return method;
+ for (String methodSuffix : methodSuffixes) {
+ for (String prefix : prefixes) {
+ for (Method method : methods) {
+ if (method.getName().equals(prefix + methodSuffix)
+ && method.getParameterTypes().length == numberOfParams
+ && (!mustBeStatic || Modifier.isStatic(method.getModifiers()))) {
+ return method;
+ }
+ }
}
}
return null;
+
}
/**
@@ -370,13 +362,29 @@ public int compare(Method o1, Method o2) {
return methods;
}
+ /**
+ * Return the method suffixes for a given property name. The default implementation
+ * uses JavaBean conventions with additional support for properties of the form 'xY'
+ * where the method 'getXY()' is used in preference to the JavaBean convention of
+ * 'getxY()'.
+ */
+ protected String[] getPropertyMethodSuffixes(String propertyName) {
+ String suffix = getPropertyMethodSuffix(propertyName);
+ if (suffix.length() > 0 && Character.isUpperCase(suffix.charAt(0))) {
+ return new String[] { suffix };
+ }
+ return new String[] { suffix, StringUtils.capitalize(suffix) };
+ }
+
+ /**
+ * Return the method suffix for a given property name. The default implementation
+ * uses JavaBean conventions.
+ */
protected String getPropertyMethodSuffix(String propertyName) {
if (propertyName.length() > 1 && Character.isUpperCase(propertyName.charAt(1))) {
return propertyName;
}
- else {
- return StringUtils.capitalize(propertyName);
- }
+ return StringUtils.capitalize(propertyName);
}
/** | true |
Other | spring-projects | spring-framework | b25e91a550beaf428a6e696959b717341a04f27d.json | Relax JavaBean rules for SpEL property access
Relax the method search algorithm used by `ReflectivePropertyAccessor`
to include methods of the form `getXY()` for properties of the form
`xy`.
Although the JavaBean specification indicates that a property `xy`
should use the accessors `getxY()` and `setxY()`, in practice many
developers choose to have an uppercase first character. The
`ReflectivePropertyAccessor` will now consider these style methods if
the traditional conventions fail to find a match.
Issue: SPR-10716 | spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java | @@ -335,6 +335,12 @@ public void testReflectivePropertyResolver() throws Exception {
assertEquals("id",rpr.read(ctx,t,"Id").getValue());
assertTrue(rpr.canRead(ctx,t,"Id"));
+ // repro SPR-10994
+ assertEquals("xyZ",rpr.read(ctx,t,"xyZ").getValue());
+ assertTrue(rpr.canRead(ctx,t,"xyZ"));
+ assertEquals("xY",rpr.read(ctx,t,"xY").getValue());
+ assertTrue(rpr.canRead(ctx,t,"xY"));
+
// SPR-10122, ReflectivePropertyAccessor JavaBean property names compliance tests - setters
rpr.write(ctx, t, "pEBS","Test String");
assertEquals("Test String",rpr.read(ctx,t,"pEBS").getValue());
@@ -429,6 +435,8 @@ static class Tester {
String id = "id";
String ID = "ID";
String pEBS = "pEBS";
+ String xY = "xY";
+ String xyZ = "xyZ";
public String getProperty() { return property; }
public void setProperty(String value) { property = value; }
@@ -445,6 +453,10 @@ static class Tester {
public String getID() { return ID; }
+ public String getXY() { return xY; }
+
+ public String getXyZ() { return xyZ; }
+
public String getpEBS() {
return pEBS;
} | true |
Other | spring-projects | spring-framework | 59fcf5014feac51687cad6222166356bda309147.json | Increase timeout for Stomp integration tests | spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java | @@ -595,7 +595,7 @@ public void expectAvailabilityStatusChanges(Boolean... expected) {
public void awaitAndAssert() throws InterruptedException {
synchronized(this.monitor) {
- long endTime = System.currentTimeMillis() + 5000;
+ long endTime = System.currentTimeMillis() + 6000;
while (this.expected.size() != this.actual.size() && System.currentTimeMillis() < endTime) {
this.monitor.wait(500);
} | false |
Other | spring-projects | spring-framework | efa86e80d8be934519de189cecaaba9f05c6ebbc.json | Upgrade json-path to 0.9.0 version
This version fixed bugs and improved performance.
New features: "select multiple attributes" and
"Array operations and slicing improved" (a new example
has been added in tests to reflect that).
See https://github.com/jayway/JsonPath/blob/master/README
Issue: SPR-10990 | build.gradle | @@ -756,7 +756,7 @@ project("spring-test") {
optional(project(":spring-orm"))
optional(project(":spring-web"))
optional(project(":spring-webmvc"))
- optional(project(":spring-webmvc-portlet"), )
+ optional(project(":spring-webmvc-portlet"))
optional("junit:junit:${junitVersion}")
optional("org.testng:testng:6.8.5")
optional("javax.servlet:javax.servlet-api:3.0.1")
@@ -799,9 +799,10 @@ project("spring-test-mvc") {
dependencies {
optional(project(":spring-context"))
provided(project(":spring-webmvc"))
+ provided(project(":spring-webmvc-tiles3"))
provided("javax.servlet:javax.servlet-api:3.0.1")
optional("org.hamcrest:hamcrest-core:1.3")
- optional("com.jayway.jsonpath:json-path:0.8.1")
+ optional("com.jayway.jsonpath:json-path:0.9.0")
optional("xmlunit:xmlunit:1.3")
testCompile("org.slf4j:slf4j-jcl:${slf4jVersion}")
testCompile("javax.servlet:jstl:1.2") | true |
Other | spring-projects | spring-framework | efa86e80d8be934519de189cecaaba9f05c6ebbc.json | Upgrade json-path to 0.9.0 version
This version fixed bugs and improved performance.
New features: "select multiple attributes" and
"Array operations and slicing improved" (a new example
has been added in tests to reflect that).
See https://github.com/jayway/JsonPath/blob/master/README
Issue: SPR-10990 | spring-test-mvc/src/test/java/org/springframework/test/web/client/samples/matchers/JsonPathRequestMatcherTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 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.
@@ -18,6 +18,7 @@
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.isIn;
import static org.hamcrest.Matchers.startsWith;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
@@ -92,8 +93,8 @@ public void testExists() throws Exception {
public void testDoesNotExist() throws Exception {
this.mockServer.expect(requestTo("/composers"))
.andExpect(content().contentType("application/json;charset=UTF-8"))
- .andExpect(jsonPath("$.composers[?(@.name = 'Edvard Grieeeeeeg')]").doesNotExist())
- .andExpect(jsonPath("$.composers[?(@.name = 'Robert Schuuuuuuman')]").doesNotExist())
+ .andExpect(jsonPath("$.composers[?(@.name == 'Edvard Grieeeeeeg')]").doesNotExist())
+ .andExpect(jsonPath("$.composers[?(@.name == 'Robert Schuuuuuuman')]").doesNotExist())
.andExpect(jsonPath("$.composers[-1]").doesNotExist())
.andExpect(jsonPath("$.composers[4]").doesNotExist())
.andRespond(withSuccess());
@@ -124,6 +125,7 @@ public void testHamcrestMatcher() throws Exception {
.andExpect(jsonPath("$.performers[0].name", endsWith("Ashkenazy")))
.andExpect(jsonPath("$.performers[1].name", containsString("di Me")))
.andExpect(jsonPath("$.composers[1].name", isIn(Arrays.asList("Johann Sebastian Bach", "Johannes Brahms"))))
+ .andExpect(jsonPath("$.composers[:3].name", hasItem("Johannes Brahms")))
.andRespond(withSuccess());
this.restTemplate.put(new URI("/composers"), this.people); | true |
Other | spring-projects | spring-framework | c4a8bf9c4dd745183d918c05f63752a5a7d317a0.json | Add new features on @ControllerAdvice
Prior to this commit, @ControllerAdvice annotated beans would
assist all known Controllers, by applying @ExceptionHandler,
@InitBinder, and @ModelAttribute.
This commit updates the @ControllerAdvice annotation,
which accepts now base package names, assignableTypes,
annotations and basePackageClasses.
If attributes are set, only Controllers that match those
selectors will be assisted by the annotated class.
This commit does not change the default behavior when
no value is set, i.e. @ControllerAdvice().
Issue: SPR-10222 | spring-web/src/main/java/org/springframework/web/bind/annotation/ControllerAdvice.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,7 +34,21 @@
* {@link InitBinder @InitBinder}, and {@link ModelAttribute @ModelAttribute}
* methods that apply to all {@link RequestMapping @RequestMapping} methods.
*
+ * <p>One of {@link #annotations()}, {@link #basePackageClasses()},
+ * {@link #basePackages()} or its alias {@link #value()}
+ * may be specified to define specific subsets of Controllers
+ * to assist. When multiple selectors are applied, OR logic is applied -
+ * meaning selected Controllers should match at least one selector.
+ *
+ * <p>The default behavior (i.e. if used without any selector),
+ * the {@code @ControllerAdvice} annotated class will
+ * assist all known Controllers.
+ *
+ * <p>Note that those checks are done at runtime, so adding many attributes and using
+ * multiple strategies may have negative impacts (complexity, performance).
+ *
* @author Rossen Stoyanchev
+ * @author Brian Clozel
* @since 3.2
*/
@Target(ElementType.TYPE)
@@ -43,4 +57,56 @@
@Component
public @interface ControllerAdvice {
+ /**
+ * Alias for the {@link #basePackages()} attribute.
+ * Allows for more concise annotation declarations e.g.:
+ * {@code @ControllerAdvice("org.my.pkg")} instead of
+ * {@code @ControllerAdvice(basePackages="org.my.pkg")}.
+ * @since 4.0
+ */
+ String[] value() default {};
+
+ /**
+ * Array of base packages.
+ * Controllers that belong to those base packages will be selected
+ * to be assisted by the annotated class, e.g.:
+ * {@code @ControllerAdvice(basePackages="org.my.pkg")}
+ * {@code @ControllerAdvice(basePackages={"org.my.pkg","org.my.other.pkg"})}
+ *
+ * <p>{@link #value()} is an alias for this attribute.
+ * <p>Use {@link #basePackageClasses()} for a type-safe alternative to String-based package names.
+ * @since 4.0
+ */
+ String[] basePackages() default {};
+
+ /**
+ * Array of classes.
+ * Controllers that are assignable to at least one of the given types
+ * will be assisted by the {@code @ControllerAdvice} annotated class.
+ * @since 4.0
+ */
+ Class<?>[] assignableTypes() default {};
+
+
+ /**
+ * Array of annotations.
+ * Controllers that are annotated with this/one of those annotation(s)
+ * will be assisted by the {@code @ControllerAdvice} annotated class.
+ *
+ * <p>Consider creating a special annotation or use a predefined one,
+ * like {@link RestController @RestController}.
+ * @since 4.0
+ */
+ Class<?>[] annotations() default {};
+
+ /**
+ * Type-safe alternative to {@link #value()} for specifying the packages
+ * to select Controllers to be assisted by the {@code @ControllerAdvice}
+ * annotated class.
+ *
+ * <p>Consider creating a special no-op marker class or interface in each package
+ * that serves no purpose other than being referenced by this attribute.
+ * @since 4.0
+ */
+ Class<?>[] basePackageClasses() default {};
} | true |
Other | spring-projects | spring-framework | c4a8bf9c4dd745183d918c05f63752a5a7d317a0.json | Add new features on @ControllerAdvice
Prior to this commit, @ControllerAdvice annotated beans would
assist all known Controllers, by applying @ExceptionHandler,
@InitBinder, and @ModelAttribute.
This commit updates the @ControllerAdvice annotation,
which accepts now base package names, assignableTypes,
annotations and basePackageClasses.
If attributes are set, only Controllers that match those
selectors will be assisted by the annotated class.
This commit does not change the default behavior when
no value is set, i.e. @ControllerAdvice().
Issue: SPR-10222 | spring-web/src/main/java/org/springframework/web/method/ControllerAdviceBean.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 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.
@@ -15,16 +15,21 @@
*/
package org.springframework.web.method;
+import java.lang.annotation.Annotation;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
+import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
/**
@@ -36,6 +41,7 @@
* any object, including ones without an {@code @ControllerAdvice}.
*
* @author Rossen Stoyanchev
+ * @author Brian Clozel
* @since 3.2
*/
public class ControllerAdviceBean implements Ordered {
@@ -46,6 +52,13 @@ public class ControllerAdviceBean implements Ordered {
private final BeanFactory beanFactory;
+ private final List<Package> basePackages = new ArrayList<Package>();
+
+ private final List<Class<Annotation>> annotations = new ArrayList<Class<Annotation>>();
+
+ private final List<Class<?>> assignableTypes = new ArrayList<Class<?>>();
+
+ private static final Log logger = LogFactory.getLog(ControllerAdviceBean.class);
/**
* Create an instance using the given bean name.
@@ -59,14 +72,68 @@ public ControllerAdviceBean(String beanName, BeanFactory beanFactory) {
"Bean factory [" + beanFactory + "] does not contain bean " + "with name [" + beanName + "]");
this.bean = beanName;
this.beanFactory = beanFactory;
- this.order = initOrderFromBeanType(this.beanFactory.getType(beanName));
+ Class<?> beanType = this.beanFactory.getType(beanName);
+ this.order = initOrderFromBeanType(beanType);
+ this.basePackages.addAll(initBasePackagesFromBeanType(beanType));
+ this.annotations.addAll(initAnnotationsFromBeanType(beanType));
+ this.assignableTypes.addAll(initAssignableTypesFromBeanType(beanType));
}
private static int initOrderFromBeanType(Class<?> beanType) {
Order annot = AnnotationUtils.findAnnotation(beanType, Order.class);
return (annot != null) ? annot.value() : Ordered.LOWEST_PRECEDENCE;
}
+ private static List<Package> initBasePackagesFromBeanType(Class<?> beanType) {
+ List<Package> basePackages = new ArrayList<Package>();
+ ControllerAdvice annotation = AnnotationUtils.findAnnotation(beanType,ControllerAdvice.class);
+ Assert.notNull(annotation,"BeanType ["+beanType.getName()+"] is not annotated @ControllerAdvice");
+ for (String pkgName : (String[])AnnotationUtils.getValue(annotation)) {
+ if (StringUtils.hasText(pkgName)) {
+ Package pack = Package.getPackage(pkgName);
+ if(pack != null) {
+ basePackages.add(pack);
+ } else {
+ logger.warn("Package [" + pkgName + "] was not found, see ["
+ + beanType.getName() + "]");
+ }
+ }
+ }
+ for (String pkgName : (String[])AnnotationUtils.getValue(annotation,"basePackages")) {
+ if (StringUtils.hasText(pkgName)) {
+ Package pack = Package.getPackage(pkgName);
+ if(pack != null) {
+ basePackages.add(pack);
+ } else {
+ logger.warn("Package [" + pkgName + "] was not found, see ["
+ + beanType.getName() + "]");
+ }
+ }
+ }
+ for (Class<?> markerClass : (Class<?>[])AnnotationUtils.getValue(annotation,"basePackageClasses")) {
+ Package pack = markerClass.getPackage();
+ if(pack != null) {
+ basePackages.add(pack);
+ } else {
+ logger.warn("Package was not found for class [" + markerClass.getName()
+ + "], see [" + beanType.getName() + "]");
+ }
+ }
+ return basePackages;
+ }
+
+ private static List<Class<Annotation>> initAnnotationsFromBeanType(Class<?> beanType) {
+ ControllerAdvice annotation = AnnotationUtils.findAnnotation(beanType,ControllerAdvice.class);
+ Class<Annotation>[] annotations = (Class<Annotation>[])AnnotationUtils.getValue(annotation,"annotations");
+ return Arrays.asList(annotations);
+ }
+
+ private static List<Class<?>> initAssignableTypesFromBeanType(Class<?> beanType) {
+ ControllerAdvice annotation = AnnotationUtils.findAnnotation(beanType,ControllerAdvice.class);
+ Class<?>[] assignableTypes = (Class<?>[])AnnotationUtils.getValue(annotation,"assignableTypes");
+ return Arrays.asList(assignableTypes);
+ }
+
/**
* Create an instance using the given bean instance.
* @param bean the bean
@@ -75,6 +142,9 @@ public ControllerAdviceBean(Object bean) {
Assert.notNull(bean, "'bean' must not be null");
this.bean = bean;
this.order = initOrderFromBean(bean);
+ this.basePackages.addAll(initBasePackagesFromBeanType(bean.getClass()));
+ this.annotations.addAll(initAnnotationsFromBeanType(bean.getClass()));
+ this.assignableTypes.addAll(initAssignableTypesFromBeanType(bean.getClass()));
this.beanFactory = null;
}
@@ -124,6 +194,45 @@ public Object resolveBean() {
return (this.bean instanceof String) ? this.beanFactory.getBean((String) this.bean) : this.bean;
}
+ /**
+ * Checks whether the bean type given as a parameter should be assisted by
+ * the current {@code @ControllerAdvice} annotated bean.
+ *
+ * @param beanType the type of the bean
+ * @see org.springframework.web.bind.annotation.ControllerAdvice
+ * @since 4.0
+ */
+ public boolean isApplicableToBeanType(Class<?> beanType) {
+ if(hasNoSelector()) {
+ return true;
+ }
+ else if(beanType != null) {
+ String packageName = beanType.getPackage().getName();
+ for(Package basePackage : this.basePackages) {
+ if(packageName.startsWith(basePackage.getName())) {
+ return true;
+ }
+ }
+ for(Class<Annotation> annotationClass : this.annotations) {
+ if(AnnotationUtils.findAnnotation(beanType, annotationClass) != null) {
+ return true;
+ }
+ }
+ for(Class<?> clazz : this.assignableTypes) {
+ if(ClassUtils.isAssignable(clazz, beanType)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private boolean hasNoSelector() {
+ return this.basePackages.isEmpty() && this.annotations.isEmpty()
+ && this.assignableTypes.isEmpty();
+ }
+
+
@Override
public boolean equals(Object o) {
if (this == o) { | true |
Other | spring-projects | spring-framework | c4a8bf9c4dd745183d918c05f63752a5a7d317a0.json | Add new features on @ControllerAdvice
Prior to this commit, @ControllerAdvice annotated beans would
assist all known Controllers, by applying @ExceptionHandler,
@InitBinder, and @ModelAttribute.
This commit updates the @ControllerAdvice annotation,
which accepts now base package names, assignableTypes,
annotations and basePackageClasses.
If attributes are set, only Controllers that match those
selectors will be assisted by the annotated class.
This commit does not change the default behavior when
no value is set, i.e. @ControllerAdvice().
Issue: SPR-10222 | spring-web/src/test/java/org/springframework/web/method/ControllerAdviceBeanTests.java | @@ -0,0 +1,144 @@
+package org.springframework.web.method;
+
+import org.junit.Test;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+import static org.junit.Assert.*;
+
+/**
+ * @author Brian Clozel
+ */
+public class ControllerAdviceBeanTests {
+
+ @Test
+ public void shouldMatchAll() {
+ ControllerAdviceBean bean = new ControllerAdviceBean(new SimpleControllerAdvice());
+ assertApplicable("should match all", bean, AnnotatedController.class);
+ assertApplicable("should match all", bean, ImplementationController.class);
+ assertApplicable("should match all", bean, InheritanceController.class);
+ assertApplicable("should match all", bean, String.class);
+ }
+
+ @Test
+ public void basePackageSupport() {
+ ControllerAdviceBean bean = new ControllerAdviceBean(new BasePackageSupport());
+ assertApplicable("base package support", bean, AnnotatedController.class);
+ assertApplicable("base package support", bean, ImplementationController.class);
+ assertApplicable("base package support", bean, InheritanceController.class);
+ assertNotApplicable("bean not in package", bean, String.class);
+ }
+
+ @Test
+ public void basePackageValueSupport() {
+ ControllerAdviceBean bean = new ControllerAdviceBean(new BasePackageValueSupport());
+ assertApplicable("base package support", bean, AnnotatedController.class);
+ assertApplicable("base package support", bean, ImplementationController.class);
+ assertApplicable("base package support", bean, InheritanceController.class);
+ assertNotApplicable("bean not in package", bean, String.class);
+ }
+
+ @Test
+ public void annotationSupport() {
+ ControllerAdviceBean bean = new ControllerAdviceBean(new AnnotationSupport());
+ assertApplicable("annotation support", bean, AnnotatedController.class);
+ assertNotApplicable("this bean is not annotated", bean, InheritanceController.class);
+ }
+
+ @Test
+ public void markerClassSupport() {
+ ControllerAdviceBean bean = new ControllerAdviceBean(new MarkerClassSupport());
+ assertApplicable("base package class support", bean, AnnotatedController.class);
+ assertApplicable("base package class support", bean, ImplementationController.class);
+ assertApplicable("base package class support", bean, InheritanceController.class);
+ assertNotApplicable("bean not in package", bean, String.class);
+ }
+
+ @Test
+ public void shouldNotMatch() {
+ ControllerAdviceBean bean = new ControllerAdviceBean(new ShouldNotMatch());
+ assertNotApplicable("should not match", bean, AnnotatedController.class);
+ assertNotApplicable("should not match", bean, ImplementationController.class);
+ assertNotApplicable("should not match", bean, InheritanceController.class);
+ assertNotApplicable("should not match", bean, String.class);
+ }
+
+ @Test
+ public void assignableTypesSupport() {
+ ControllerAdviceBean bean = new ControllerAdviceBean(new AssignableTypesSupport());
+ assertApplicable("controller implements assignable", bean, ImplementationController.class);
+ assertApplicable("controller inherits assignable", bean, InheritanceController.class);
+ assertNotApplicable("not assignable", bean, AnnotatedController.class);
+ assertNotApplicable("not assignable", bean, String.class);
+ }
+
+ @Test
+ public void multipleMatch() {
+ ControllerAdviceBean bean = new ControllerAdviceBean(new MultipleSelectorsSupport());
+ assertApplicable("controller implements assignable", bean, ImplementationController.class);
+ assertApplicable("controller is annotated", bean, AnnotatedController.class);
+ assertNotApplicable("should not match", bean, InheritanceController.class);
+ }
+
+ private void assertApplicable(String message, ControllerAdviceBean controllerAdvice,
+ Class<?> controllerBeanType) {
+ assertNotNull(controllerAdvice);
+ assertTrue(message,controllerAdvice.isApplicableToBeanType(controllerBeanType));
+ }
+
+ private void assertNotApplicable(String message, ControllerAdviceBean controllerAdvice,
+ Class<?> controllerBeanType) {
+ assertNotNull(controllerAdvice);
+ assertFalse(message,controllerAdvice.isApplicableToBeanType(controllerBeanType));
+ }
+
+ // ControllerAdvice classes
+
+ @ControllerAdvice
+ static class SimpleControllerAdvice {}
+
+ @ControllerAdvice(annotations = ControllerAnnotation.class)
+ static class AnnotationSupport {}
+
+ @ControllerAdvice(basePackageClasses = MarkerClass.class)
+ static class MarkerClassSupport {}
+
+ @ControllerAdvice(assignableTypes = {ControllerInterface.class,
+ AbstractController.class})
+ static class AssignableTypesSupport {}
+
+ @ControllerAdvice(basePackages = "org.springframework.web.method")
+ static class BasePackageSupport {}
+
+ @ControllerAdvice("org.springframework.web.method")
+ static class BasePackageValueSupport {}
+
+ @ControllerAdvice(annotations = ControllerAnnotation.class,
+ assignableTypes = ControllerInterface.class)
+ static class MultipleSelectorsSupport {}
+
+ @ControllerAdvice(basePackages = "java.util",
+ annotations = RestController.class)
+ static class ShouldNotMatch {}
+
+ // Support classes
+
+ static class MarkerClass {}
+
+ @Retention(RetentionPolicy.RUNTIME)
+ static @interface ControllerAnnotation {}
+
+ @ControllerAnnotation
+ public static class AnnotatedController {}
+
+ static interface ControllerInterface {}
+
+ static class ImplementationController implements ControllerInterface {}
+
+ static abstract class AbstractController {}
+
+ static class InheritanceController extends AbstractController {}
+} | true |
Other | spring-projects | spring-framework | c4a8bf9c4dd745183d918c05f63752a5a7d317a0.json | Add new features on @ControllerAdvice
Prior to this commit, @ControllerAdvice annotated beans would
assist all known Controllers, by applying @ExceptionHandler,
@InitBinder, and @ModelAttribute.
This commit updates the @ControllerAdvice annotation,
which accepts now base package names, assignableTypes,
annotations and basePackageClasses.
If attributes are set, only Controllers that match those
selectors will be assisted by the annotated class.
This commit does not change the default behavior when
no value is set, i.e. @ControllerAdvice().
Issue: SPR-10222 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 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.
@@ -351,8 +351,8 @@ protected ModelAndView doResolveHandlerMethodException(HttpServletRequest reques
* @return a method to handle the exception, or {@code null}
*/
protected ServletInvocableHandlerMethod getExceptionHandlerMethod(HandlerMethod handlerMethod, Exception exception) {
+ Class<?> handlerType = (handlerMethod != null) ? handlerMethod.getBeanType() : null;
if (handlerMethod != null) {
- Class<?> handlerType = handlerMethod.getBeanType();
ExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.get(handlerType);
if (resolver == null) {
resolver = new ExceptionHandlerMethodResolver(handlerType);
@@ -364,9 +364,11 @@ protected ServletInvocableHandlerMethod getExceptionHandlerMethod(HandlerMethod
}
}
for (Entry<ControllerAdviceBean, ExceptionHandlerMethodResolver> entry : this.exceptionHandlerAdviceCache.entrySet()) {
- Method method = entry.getValue().resolveMethod(exception);
- if (method != null) {
- return new ServletInvocableHandlerMethod(entry.getKey().resolveBean(), method);
+ if(entry.getKey().isApplicableToBeanType(handlerType)) {
+ Method method = entry.getValue().resolveMethod(exception);
+ if (method != null) {
+ return new ServletInvocableHandlerMethod(entry.getKey().resolveBean(), method);
+ }
}
}
return null; | true |
Other | spring-projects | spring-framework | c4a8bf9c4dd745183d918c05f63752a5a7d317a0.json | Add new features on @ControllerAdvice
Prior to this commit, @ControllerAdvice annotated beans would
assist all known Controllers, by applying @ExceptionHandler,
@InitBinder, and @ModelAttribute.
This commit updates the @ControllerAdvice annotation,
which accepts now base package names, assignableTypes,
annotations and basePackageClasses.
If attributes are set, only Controllers that match those
selectors will be assisted by the annotated class.
This commit does not change the default behavior when
no value is set, i.e. @ControllerAdvice().
Issue: SPR-10222 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java | @@ -776,9 +776,11 @@ private ModelFactory getModelFactory(HandlerMethod handlerMethod, WebDataBinderF
List<InvocableHandlerMethod> attrMethods = new ArrayList<InvocableHandlerMethod>();
// Global methods first
for (Entry<ControllerAdviceBean, Set<Method>> entry : this.modelAttributeAdviceCache.entrySet()) {
- Object bean = entry.getKey().resolveBean();
- for (Method method : entry.getValue()) {
- attrMethods.add(createModelAttributeMethod(binderFactory, bean, method));
+ if(entry.getKey().isApplicableToBeanType(handlerType)) {
+ Object bean = entry.getKey().resolveBean();
+ for (Method method : entry.getValue()) {
+ attrMethods.add(createModelAttributeMethod(binderFactory, bean, method));
+ }
}
}
for (Method method : methods) {
@@ -806,9 +808,11 @@ private WebDataBinderFactory getDataBinderFactory(HandlerMethod handlerMethod) t
List<InvocableHandlerMethod> initBinderMethods = new ArrayList<InvocableHandlerMethod>();
// Global methods first
for (Entry<ControllerAdviceBean, Set<Method>> entry : this.initBinderAdviceCache .entrySet()) {
- Object bean = entry.getKey().resolveBean();
- for (Method method : entry.getValue()) {
- initBinderMethods.add(createInitBinderMethod(bean, method));
+ if(entry.getKey().isApplicableToBeanType(handlerType)) {
+ Object bean = entry.getKey().resolveBean();
+ for (Method method : entry.getValue()) {
+ initBinderMethods.add(createInitBinderMethod(bean, method));
+ }
}
}
for (Method method : methods) { | true |
Other | spring-projects | spring-framework | c4a8bf9c4dd745183d918c05f63752a5a7d317a0.json | Add new features on @ControllerAdvice
Prior to this commit, @ControllerAdvice annotated beans would
assist all known Controllers, by applying @ExceptionHandler,
@InitBinder, and @ModelAttribute.
This commit updates the @ControllerAdvice annotation,
which accepts now base package names, assignableTypes,
annotations and basePackageClasses.
If attributes are set, only Controllers that match those
selectors will be assisted by the annotated class.
This commit does not change the default behavior when
no value is set, i.e. @ControllerAdvice().
Issue: SPR-10222 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolverTests.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 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.
@@ -204,6 +204,35 @@ public void resolveExceptionGlobalHandlerOrdered() throws Exception {
assertEquals("TestExceptionResolver: IllegalStateException", this.response.getContentAsString());
}
+ @Test
+ public void resolveExceptionControllerAdviceHandler() throws Exception {
+ AnnotationConfigApplicationContext cxt = new AnnotationConfigApplicationContext(MyControllerAdviceConfig.class);
+ this.resolver.setApplicationContext(cxt);
+ this.resolver.afterPropertiesSet();
+
+ IllegalStateException ex = new IllegalStateException();
+ HandlerMethod handlerMethod = new HandlerMethod(new ResponseBodyController(), "handle");
+ ModelAndView mav = this.resolver.resolveException(this.request, this.response, handlerMethod, ex);
+
+ assertNotNull("Exception was not handled", mav);
+ assertTrue(mav.isEmpty());
+ assertEquals("BasePackageTestExceptionResolver: IllegalStateException", this.response.getContentAsString());
+ }
+
+ @Test
+ public void resolveExceptionControllerAdviceNoHandler() throws Exception {
+ AnnotationConfigApplicationContext cxt = new AnnotationConfigApplicationContext(MyControllerAdviceConfig.class);
+ this.resolver.setApplicationContext(cxt);
+ this.resolver.afterPropertiesSet();
+
+ IllegalStateException ex = new IllegalStateException();
+ ModelAndView mav = this.resolver.resolveException(this.request, this.response, null, ex);
+
+ assertNotNull("Exception was not handled", mav);
+ assertTrue(mav.isEmpty());
+ assertEquals("DefaultTestExceptionResolver: IllegalStateException", this.response.getContentAsString());
+ }
+
private void assertMethodProcessorCount(int resolverCount, int handlerCount) {
assertEquals(resolverCount, this.resolver.getArgumentResolvers().getResolvers().size());
@@ -288,4 +317,51 @@ static class MyConfig {
}
}
+ @ControllerAdvice("java.lang")
+ @Order(1)
+ static class NotCalledTestExceptionResolver {
+
+ @ExceptionHandler
+ @ResponseBody
+ public String handleException(IllegalStateException ex) {
+ return "NotCalledTestExceptionResolver: " + ClassUtils.getShortName(ex.getClass());
+ }
+ }
+
+ @ControllerAdvice("org.springframework.web.servlet.mvc.method.annotation")
+ @Order(2)
+ static class BasePackageTestExceptionResolver {
+
+ @ExceptionHandler
+ @ResponseBody
+ public String handleException(IllegalStateException ex) {
+ return "BasePackageTestExceptionResolver: " + ClassUtils.getShortName(ex.getClass());
+ }
+ }
+
+ @ControllerAdvice
+ @Order(3)
+ static class DefaultTestExceptionResolver {
+
+ @ExceptionHandler
+ @ResponseBody
+ public String handleException(IllegalStateException ex) {
+ return "DefaultTestExceptionResolver: " + ClassUtils.getShortName(ex.getClass());
+ }
+ }
+
+ @Configuration
+ static class MyControllerAdviceConfig {
+ @Bean public NotCalledTestExceptionResolver notCalledTestExceptionResolver() {
+ return new NotCalledTestExceptionResolver();
+ }
+
+ @Bean public BasePackageTestExceptionResolver basePackageTestExceptionResolver() {
+ return new BasePackageTestExceptionResolver();
+ }
+
+ @Bean public DefaultTestExceptionResolver defaultTestExceptionResolver() {
+ return new DefaultTestExceptionResolver();
+ }
+ }
}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | c4a8bf9c4dd745183d918c05f63752a5a7d317a0.json | Add new features on @ControllerAdvice
Prior to this commit, @ControllerAdvice annotated beans would
assist all known Controllers, by applying @ExceptionHandler,
@InitBinder, and @ModelAttribute.
This commit updates the @ControllerAdvice annotation,
which accepts now base package names, assignableTypes,
annotations and basePackageClasses.
If attributes are set, only Controllers that match those
selectors will be assisted by the annotated class.
This commit does not change the default behavior when
no value is set, i.e. @ControllerAdvice().
Issue: SPR-10222 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterTests.java | @@ -25,7 +25,9 @@
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.ui.Model;
+import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.support.StaticWebApplicationContext;
@@ -184,6 +186,21 @@ public void modelAttributeAdvice() throws Exception {
assertEquals("gAttr2", mav.getModel().get("attr2"));
}
+ @Test
+ public void modelAttributePackageNameAdvice() throws Exception {
+ this.webAppContext.registerSingleton("mapa", ModelAttributePackageAdvice.class);
+ this.webAppContext.registerSingleton("manupa", ModelAttributeNotUsedPackageAdvice.class);
+ this.webAppContext.refresh();
+
+ HandlerMethod handlerMethod = handlerMethod(new SimpleController(), "handle");
+ this.handlerAdapter.afterPropertiesSet();
+ ModelAndView mav = this.handlerAdapter.handle(this.request, this.response, handlerMethod);
+
+ assertEquals("lAttr1", mav.getModel().get("attr1"));
+ assertEquals("gAttr2", mav.getModel().get("attr2"));
+ assertEquals(null,mav.getModel().get("attr3"));
+ }
+
private HandlerMethod handlerMethod(Object handler, String methodName, Class<?>... paramTypes) throws Exception {
Method method = handler.getClass().getDeclaredMethod(methodName, paramTypes);
@@ -237,4 +254,21 @@ public void addAttributes(Model model) {
}
}
+ @ControllerAdvice({"org.springframework.web.servlet.mvc.method.annotation","java.lang"})
+ private static class ModelAttributePackageAdvice {
+
+ @ModelAttribute
+ public void addAttributes(Model model) {
+ model.addAttribute("attr2", "gAttr2");
+ }
+ }
+
+ @ControllerAdvice("java.lang")
+ private static class ModelAttributeNotUsedPackageAdvice {
+
+ @ModelAttribute
+ public void addAttributes(Model model) {
+ model.addAttribute("attr3", "gAttr3");
+ }
+ }
}
\ No newline at end of file | true |
Other | spring-projects | spring-framework | 29934d7c0249e54897cb06c1d779dcaec4d6f4ee.json | Add TCP abstractions to spring-messaging
This change adds abstractions for opening and managing TCP connections
primarily for use with the STOMP broker support. As one immediate
benefit the change makes the StompBrokerRelayMessageHandler more
easy to test. | spring-messaging/src/main/java/org/springframework/messaging/MessageDeliveryException.java | @@ -37,6 +37,10 @@ public MessageDeliveryException(Message<?> undeliveredMessage, String descriptio
super(undeliveredMessage, description);
}
+ public MessageDeliveryException(Message<?> message, Throwable cause) {
+ super(message, cause);
+ }
+
public MessageDeliveryException(Message<?> undeliveredMessage, String description, Throwable cause) {
super(undeliveredMessage, description, cause);
} | true |
Other | spring-projects | spring-framework | 29934d7c0249e54897cb06c1d779dcaec4d6f4ee.json | Add TCP abstractions to spring-messaging
This change adds abstractions for opening and managing TCP connections
primarily for use with the STOMP broker support. As one immediate
benefit the change makes the StompBrokerRelayMessageHandler more
easy to test. | spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java | @@ -16,11 +16,10 @@
package org.springframework.messaging.simp.stomp;
-import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.Map;
+import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicReference;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
@@ -29,21 +28,15 @@
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.handler.AbstractBrokerMessageHandler;
import org.springframework.messaging.support.MessageBuilder;
+import org.springframework.messaging.support.tcp.FixedIntervalReconnectStrategy;
+import org.springframework.messaging.support.tcp.ReactorNettyTcpClient;
+import org.springframework.messaging.support.tcp.TcpConnection;
+import org.springframework.messaging.support.tcp.TcpConnectionHandler;
+import org.springframework.messaging.support.tcp.TcpOperations;
import org.springframework.util.Assert;
-
-import reactor.core.Environment;
-import reactor.core.composable.Composable;
-import reactor.core.composable.Deferred;
-import reactor.core.composable.Promise;
-import reactor.core.composable.spec.DeferredPromiseSpec;
-import reactor.function.Consumer;
-import reactor.tcp.Reconnect;
-import reactor.tcp.TcpClient;
-import reactor.tcp.TcpConnection;
-import reactor.tcp.netty.NettyTcpClient;
-import reactor.tcp.spec.TcpClientSpec;
-import reactor.tuple.Tuple;
-import reactor.tuple.Tuple2;
+import org.springframework.util.concurrent.ListenableFuture;
+import org.springframework.util.concurrent.ListenableFutureCallback;
+import org.springframework.util.concurrent.ListenableFutureTask;
/**
@@ -61,7 +54,7 @@
* opposed to from a client). Such messages are recognized because they are not associated
* with any client and therefore do not have a session id header. The "system" connection
* is effectively shared and cannot be used to receive messages. Several properties are
- * provided to configure the "system" session including the the
+ * provided to configure the "system" connection including the the
* {@link #setSystemLogin(String) login} {@link #setSystemPasscode(String) passcode},
* heartbeat {@link #setSystemHeartbeatSendInterval(long) send} and
* {@link #setSystemHeartbeatReceiveInterval(long) receive} intervals.
@@ -72,6 +65,13 @@
*/
public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler {
+ private static final byte[] EMPTY_PAYLOAD = new byte[0];
+
+ private static final Message<byte[]> HEARTBEAT_MESSAGE = MessageBuilder.withPayload(new byte[] {'\n'}).build();
+
+ private static final long HEARTBEAT_MULTIPLIER = 3;
+
+
private final MessageChannel messageChannel;
private String relayHost = "127.0.0.1";
@@ -88,11 +88,10 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
private String virtualHost;
- private Environment environment;
+ private TcpOperations<byte[]> tcpClient;
- private TcpClient<Message<byte[]>, Message<byte[]>> tcpClient;
-
- private final Map<String, StompRelaySession> relaySessions = new ConcurrentHashMap<String, StompRelaySession>();
+ private final Map<String, StompConnectionHandler> connectionHandlers =
+ new ConcurrentHashMap<String, StompConnectionHandler>();
/**
@@ -137,78 +136,89 @@ public int getRelayPort() {
}
/**
- * Set the interval, in milliseconds, at which the "system" relay session will, in the
+ * Configure the TCP client to for managing STOMP over TCP connections to the message
+ * broker. This is an optional property that can be used to replace the default
+ * implementation used for example for testing purposes.
+ * <p>
+ * By default an instance of {@link ReactorNettyTcpClient} is used.
+ */
+ public void setTcpClient(TcpOperations<byte[]> tcpClient) {
+ this.tcpClient = tcpClient;
+ }
+
+ /**
+ * Set the interval, in milliseconds, at which the "system" connection will, in the
* absence of any other data being sent, send a heartbeat to the STOMP broker. A value
* of zero will prevent heartbeats from being sent to the broker.
* <p>
* The default value is 10000.
* <p>
- * See class-level documentation for more information on the "system" session.
+ * See class-level documentation for more information on the "system" connection.
*/
public void setSystemHeartbeatSendInterval(long systemHeartbeatSendInterval) {
this.systemHeartbeatSendInterval = systemHeartbeatSendInterval;
}
/**
- * @return The interval, in milliseconds, at which the "system" relay session will
+ * @return The interval, in milliseconds, at which the "system" connection will
* send heartbeats to the STOMP broker.
*/
public long getSystemHeartbeatSendInterval() {
return this.systemHeartbeatSendInterval;
}
/**
- * Set the maximum interval, in milliseconds, at which the "system" relay session
+ * Set the maximum interval, in milliseconds, at which the "system" connection
* expects, in the absence of any other data, to receive a heartbeat from the STOMP
- * broker. A value of zero will configure the relay session to expect not to receive
+ * broker. A value of zero will configure the connection to expect not to receive
* heartbeats from the broker.
* <p>
* The default value is 10000.
* <p>
- * See class-level documentation for more information on the "system" session.
+ * See class-level documentation for more information on the "system" connection.
*/
public void setSystemHeartbeatReceiveInterval(long heartbeatReceiveInterval) {
this.systemHeartbeatReceiveInterval = heartbeatReceiveInterval;
}
/**
- * @return The interval, in milliseconds, at which the "system" relay session expects
+ * @return The interval, in milliseconds, at which the "system" connection expects
* to receive heartbeats from the STOMP broker.
*/
public long getSystemHeartbeatReceiveInterval() {
return this.systemHeartbeatReceiveInterval;
}
/**
- * Set the login for the "system" relay session used to send messages to the STOMP
+ * Set the login for the "system" connection used to send messages to the STOMP
* broker without having a client session (e.g. REST/HTTP request handling method).
* <p>
- * See class-level documentation for more information on the "system" session.
+ * See class-level documentation for more information on the "system" connection.
*/
public void setSystemLogin(String systemLogin) {
Assert.hasText(systemLogin, "systemLogin must not be empty");
this.systemLogin = systemLogin;
}
/**
- * @return the login used by the "system" relay session to connect to the STOMP broker
+ * @return the login used by the "system" connection to connect to the STOMP broker
*/
public String getSystemLogin() {
return this.systemLogin;
}
/**
- * Set the passcode for the "system" relay session used to send messages to the STOMP
+ * Set the passcode for the "system" connection used to send messages to the STOMP
* broker without having a client session (e.g. REST/HTTP request handling method).
* <p>
- * See class-level documentation for more information on the "system" session.
+ * See class-level documentation for more information on the "system" connection.
*/
public void setSystemPasscode(String systemPasscode) {
this.systemPasscode = systemPasscode;
}
/**
- * @return the passcode used by the "system" relay session to connect to the STOMP broker
+ * @return the passcode used by the "system" connection to connect to the STOMP broker
*/
public String getSystemPasscode() {
return this.systemPasscode;
@@ -237,12 +247,8 @@ public String getVirtualHost() {
@Override
protected void startInternal() {
- this.environment = new Environment();
- this.tcpClient = new TcpClientSpec<Message<byte[]>, Message<byte[]>>(NettyTcpClient.class)
- .env(this.environment)
- .codec(new StompCodec())
- .connect(this.relayHost, this.relayPort)
- .get();
+
+ this.tcpClient = new ReactorNettyTcpClient<byte[]>(this.relayHost, this.relayPort, new StompCodec());
if (logger.isDebugEnabled()) {
logger.debug("Initializing \"system\" TCP connection");
@@ -254,30 +260,28 @@ protected void startInternal() {
headers.setPasscode(this.systemPasscode);
headers.setHeartbeat(this.systemHeartbeatSendInterval, this.systemHeartbeatReceiveInterval);
headers.setHost(getVirtualHost());
- Message<?> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
- SystemStompRelaySession session = new SystemStompRelaySession();
- session.connect(message);
+ SystemStompConnectionHandler handler = new SystemStompConnectionHandler(headers);
+ this.connectionHandlers.put(handler.getSessionId(), handler);
- this.relaySessions.put(session.getId(), session);
+ this.tcpClient.connect(handler, new FixedIntervalReconnectStrategy(5000));
}
@Override
protected void stopInternal() {
- for (StompRelaySession session: this.relaySessions.values()) {
- session.disconnect();
- }
- try {
- this.tcpClient.close().await();
- }
- catch (Throwable t) {
- logger.error("Failed to close reactor TCP client", t);
+ for (StompConnectionHandler handler : this.connectionHandlers.values()) {
+ try {
+ handler.resetTcpConnection();
+ }
+ catch (Throwable t) {
+ logger.error("Failed to close STOMP connection " + t.getMessage());
+ }
}
try {
- this.environment.shutdown();
+ this.tcpClient.shutdown();
}
catch (Throwable t) {
- logger.error("Failed to shut down reactor Environment", t);
+ logger.error("Error while shutting down TCP client", t);
}
}
@@ -291,7 +295,7 @@ protected void handleMessageInternal(Message<?> message) {
SimpMessageType messageType = headers.getMessageType();
if (SimpMessageType.MESSAGE.equals(messageType)) {
- sessionId = (sessionId == null) ? SystemStompRelaySession.ID : sessionId;
+ sessionId = (sessionId == null) ? SystemStompConnectionHandler.SESSION_ID : sessionId;
headers.setSessionId(sessionId);
command = headers.updateStompCommandAsClientMessage();
message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
@@ -309,369 +313,278 @@ protected void handleMessageInternal(Message<?> message) {
if (SimpMessageType.CONNECT.equals(messageType)) {
if (getVirtualHost() != null) {
headers.setHost(getVirtualHost());
- message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
}
- StompRelaySession session = new StompRelaySession(sessionId);
- session.connect(message);
- this.relaySessions.put(sessionId, session);
+ StompConnectionHandler handler = new StompConnectionHandler(sessionId, headers);
+ this.connectionHandlers.put(sessionId, handler);
+ this.tcpClient.connect(handler);
}
else if (SimpMessageType.DISCONNECT.equals(messageType)) {
- StompRelaySession session = this.relaySessions.remove(sessionId);
- if (session == null) {
+ StompConnectionHandler handler = removeConnectionHandler(sessionId);
+ if (handler == null) {
if (logger.isTraceEnabled()) {
- logger.trace("Session already removed, sessionId=" + sessionId);
+ logger.trace("Connection already removed for sessionId=" + sessionId);
}
return;
}
- session.forward(message);
+ handler.forward(message);
}
else {
- StompRelaySession session = this.relaySessions.get(sessionId);
- if (session == null) {
- logger.warn("Session id=" + sessionId + " not found. Ignoring message: " + message);
+ StompConnectionHandler handler = this.connectionHandlers.get(sessionId);
+ if (handler == null) {
+ logger.warn("Connection for sessionId=" + sessionId + " not found. Ignoring message: " + message);
return;
}
- session.forward(message);
+ handler.forward(message);
}
}
+ private StompConnectionHandler removeConnectionHandler(String sessionId) {
+ return SystemStompConnectionHandler.SESSION_ID.equals(sessionId)
+ ? null : this.connectionHandlers.remove(sessionId);
+ }
- private class StompRelaySession {
- private static final long HEARTBEAT_MULTIPLIER = 3;
+ private class StompConnectionHandler implements TcpConnectionHandler<byte[]> {
private final String sessionId;
private final boolean isRemoteClientSession;
- private final long reconnectInterval;
-
- private volatile StompConnection stompConnection = new StompConnection();
+ private final StompHeaderAccessor connectHeaders;
- private volatile StompHeaderAccessor connectHeaders;
+ private volatile TcpConnection<byte[]> tcpConnection;
- private volatile StompHeaderAccessor connectedHeaders;
+ private volatile boolean isStompConnected;
- private StompRelaySession(String sessionId) {
- this(sessionId, true, 0);
+ private StompConnectionHandler(String sessionId, StompHeaderAccessor connectHeaders) {
+ this(sessionId, connectHeaders, true);
}
- private StompRelaySession(String sessionId, boolean isRemoteClientSession, long reconnectInterval) {
+ private StompConnectionHandler(String sessionId, StompHeaderAccessor connectHeaders,
+ boolean isRemoteClientSession) {
+
Assert.notNull(sessionId, "sessionId is required");
+ Assert.notNull(connectHeaders, "connectHeaders is required");
+
this.sessionId = sessionId;
+ this.connectHeaders = connectHeaders;
this.isRemoteClientSession = isRemoteClientSession;
- this.reconnectInterval = reconnectInterval;
}
-
- public String getId() {
+ public String getSessionId() {
return this.sessionId;
}
- public void connect(final Message<?> connectMessage) {
-
- Assert.notNull(connectMessage, "connectMessage is required");
- this.connectHeaders = StompHeaderAccessor.wrap(connectMessage);
-
- Composable<TcpConnection<Message<byte[]>, Message<byte[]>>> promise;
- if (this.reconnectInterval > 0) {
- promise = tcpClient.open(new Reconnect() {
- @Override
- public Tuple2<InetSocketAddress, Long> reconnect(InetSocketAddress address, int attempt) {
- return Tuple.of(address, 5000L);
- }
- });
- }
- else {
- promise = tcpClient.open();
- }
-
- promise.consume(new Consumer<TcpConnection<Message<byte[]>, Message<byte[]>>>() {
- @Override
- public void accept(TcpConnection<Message<byte[]>, Message<byte[]>> connection) {
- handleConnectionReady(connection, connectMessage);
- }
- });
- promise.when(Throwable.class, new Consumer<Throwable>() {
- @Override
- public void accept(Throwable ex) {
- relaySessions.remove(sessionId);
- handleTcpClientFailure("Failed to connect to message broker", ex);
- }
- });
+ @Override
+ public void afterConnected(TcpConnection<byte[]> connection) {
+ this.tcpConnection = connection;
+ connection.send(MessageBuilder.withPayload(EMPTY_PAYLOAD).setHeaders(this.connectHeaders).build());
}
- public void disconnect() {
- this.stompConnection.setDisconnected();
+ @Override
+ public void afterConnectFailure(Throwable ex) {
+ handleTcpConnectionFailure("Failed to connect to message broker", ex);
}
- protected void handleConnectionReady(
- TcpConnection<Message<byte[]>, Message<byte[]>> tcpConn, final Message<?> connectMessage) {
+ /**
+ * Invoked when any TCP connectivity issue is detected, i.e. failure to establish
+ * the TCP connection, failure to send a message, missed heartbeat.
+ */
+ protected void handleTcpConnectionFailure(String errorMessage, Throwable ex) {
+ if (logger.isErrorEnabled()) {
+ logger.error(errorMessage + ", sessionId=" + this.sessionId, ex);
+ }
+ resetTcpConnection();
+ sendStompErrorToClient(errorMessage);
+ }
- this.stompConnection.setTcpConnection(tcpConn);
- tcpConn.on().close(new Runnable() {
- @Override
- public void run() {
- connectionClosed();
- }
- });
- tcpConn.in().consume(new Consumer<Message<byte[]>>() {
- @Override
- public void accept(Message<byte[]> message) {
- readStompFrame(message);
+ private void sendStompErrorToClient(String errorText) {
+ if (this.isRemoteClientSession) {
+ StompConnectionHandler removed = removeConnectionHandler(this.sessionId);
+ if (removed != null) {
+ StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.ERROR);
+ headers.setSessionId(this.sessionId);
+ headers.setMessage(errorText);
+ Message<?> errorMessage = MessageBuilder.withPayload(EMPTY_PAYLOAD).setHeaders(headers).build();
+ sendMessageToClient(errorMessage);
}
- });
- forwardInternal(connectMessage, tcpConn);
+ }
}
- protected void connectionClosed() {
- relaySessions.remove(this.sessionId);
- if (this.stompConnection.isReady()) {
- sendError("Lost connection to the broker");
+ protected void sendMessageToClient(Message<?> message) {
+ if (this.isRemoteClientSession) {
+ StompBrokerRelayMessageHandler.this.messageChannel.send(message);
}
}
- private void readStompFrame(Message<byte[]> message) {
+ @Override
+ public void handleMessage(Message<byte[]> message) {
if (logger.isTraceEnabled()) {
- logger.trace("Reading message for sessionId=" + sessionId + ", " + message);
+ logger.trace("Reading message for sessionId=" + this.sessionId + ", " + message);
}
StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
if (StompCommand.CONNECTED == headers.getCommand()) {
- this.connectedHeaders = headers;
- connected();
+ afterStompConnected(headers);
}
headers.setSessionId(this.sessionId);
message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
sendMessageToClient(message);
}
- private void initHeartbeats() {
+ /**
+ * Invoked after the STOMP CONNECTED frame is received. At this point the
+ * connection is ready for sending STOMP messages to the broker.
+ */
+ protected void afterStompConnected(StompHeaderAccessor connectedHeaders) {
+ this.isStompConnected = true;
+ initHeartbeats(connectedHeaders);
+ }
+
+ private void initHeartbeats(StompHeaderAccessor connectedHeaders) {
+
+ // Remote clients do their own heartbeat management
+ if (this.isRemoteClientSession) {
+ return;
+ }
long clientSendInterval = this.connectHeaders.getHeartbeat()[0];
long clientReceiveInterval = this.connectHeaders.getHeartbeat()[1];
- long serverSendInterval = this.connectedHeaders.getHeartbeat()[0];
- long serverReceiveInterval = this.connectedHeaders.getHeartbeat()[1];
+ long serverSendInterval = connectedHeaders.getHeartbeat()[0];
+ long serverReceiveInterval = connectedHeaders.getHeartbeat()[1];
if ((clientSendInterval > 0) && (serverReceiveInterval > 0)) {
long interval = Math.max(clientSendInterval, serverReceiveInterval);
- stompConnection.connection.on().writeIdle(interval, new Runnable() {
-
+ this.tcpConnection.onWriteInactivity(new Runnable() {
@Override
public void run() {
- TcpConnection<Message<byte[]>, Message<byte[]>> tcpConn = stompConnection.connection;
- if (tcpConn != null) {
- tcpConn.send(MessageBuilder.withPayload(new byte[] {'\n'}).build(),
- new Consumer<Boolean>() {
- @Override
- public void accept(Boolean result) {
- if (!result) {
- handleTcpClientFailure("Failed to send heartbeat to the broker", null);
+ TcpConnection<byte[]> conn = tcpConnection;
+ if (conn != null) {
+ conn.send(HEARTBEAT_MESSAGE).addCallback(
+ new ListenableFutureCallback<Boolean>() {
+ public void onFailure(Throwable t) {
+ handleTcpConnectionFailure("Failed to send heartbeat", null);
}
- }
- });
+ public void onSuccess(Boolean result) {}
+ });
}
}
- });
+ }, interval);
}
if (clientReceiveInterval > 0 && serverSendInterval > 0) {
final long interval = Math.max(clientReceiveInterval, serverSendInterval) * HEARTBEAT_MULTIPLIER;
- stompConnection.connection.on().readIdle(interval, new Runnable() {
-
+ this.tcpConnection.onReadInactivity(new Runnable() {
@Override
public void run() {
- String message = "Broker hearbeat missed: connection idle for more than " + interval + "ms";
- if (logger.isWarnEnabled()) {
- logger.warn(message);
- }
- disconnected(message);
+ handleTcpConnectionFailure("No hearbeat from broker for more than " +
+ interval + "ms, closing connection", null);
}
- });
- }
- }
-
- protected void connected() {
- if (!this.isRemoteClientSession) {
- initHeartbeats();
- }
- this.stompConnection.setReady();
- }
-
- protected void handleTcpClientFailure(String message, Throwable ex) {
- if (logger.isErrorEnabled()) {
- logger.error(message + ", sessionId=" + this.sessionId, ex);
+ }, interval);
}
- disconnected(message);
}
- protected void disconnected(String errorMessage) {
- this.stompConnection.setDisconnected();
- sendError(errorMessage);
+ @Override
+ public void afterConnectionClosed() {
+ sendStompErrorToClient("Connection to broker closed");
}
- private void sendError(String errorText) {
- StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.ERROR);
- headers.setSessionId(this.sessionId);
- headers.setMessage(errorText);
- Message<?> errorMessage = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
- sendMessageToClient(errorMessage);
- }
+ public ListenableFuture<Boolean> forward(final Message<?> message) {
- protected void sendMessageToClient(Message<?> message) {
- if (this.isRemoteClientSession) {
- messageChannel.send(message);
- }
- else {
- StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
- if (StompCommand.ERROR.equals(headers.getCommand())) {
- if (logger.isErrorEnabled()) {
- logger.error("STOMP ERROR on sessionId=" + this.sessionId + ": " + message);
- }
+ if (!this.isStompConnected) {
+ if (logger.isWarnEnabled()) {
+ logger.warn("Connection to broker inactive or not ready, ignoring message=" + message);
}
- // ignore otherwise
- }
- }
-
- private void forward(Message<?> message) {
- TcpConnection<Message<byte[]>, Message<byte[]>> tcpConnection = this.stompConnection.getReadyConnection();
- if (tcpConnection == null) {
- logger.warn("Connection to STOMP broker is not active");
- handleForwardFailure(message);
- }
- else if (!forwardInternal(message, tcpConnection)) {
- handleForwardFailure(message);
- }
- }
-
- protected void handleForwardFailure(Message<?> message) {
- if (logger.isWarnEnabled()) {
- logger.warn("Failed to forward message to the broker. message=" + message);
+ return new ListenableFutureTask<Boolean>(new Callable<Boolean>() {
+ @Override
+ public Boolean call() throws Exception {
+ return Boolean.FALSE;
+ }
+ });
}
- }
-
- private boolean forwardInternal(
- Message<?> message, TcpConnection<Message<byte[]>, Message<byte[]>> tcpConnection) {
-
- Assert.isInstanceOf(byte[].class, message.getPayload(), "Message's payload must be a byte[]");
- @SuppressWarnings("unchecked")
- Message<byte[]> byteMessage = (Message<byte[]>) message;
if (logger.isTraceEnabled()) {
- logger.trace("Forwarding to STOMP broker, message: " + message);
+ logger.trace("Forwarding message to broker: " + message);
}
- StompCommand command = StompHeaderAccessor.wrap(message).getCommand();
+ @SuppressWarnings("unchecked")
+ ListenableFuture<Boolean> future = this.tcpConnection.send((Message<byte[]>) message);
- final Deferred<Boolean, Promise<Boolean>> deferred = new DeferredPromiseSpec<Boolean>().get();
- tcpConnection.send(byteMessage, new Consumer<Boolean>() {
+ future.addCallback(new ListenableFutureCallback<Boolean>() {
@Override
- public void accept(Boolean success) {
- deferred.accept(success);
- }
- });
-
- Boolean success = null;
- try {
- success = deferred.compose().await();
- if (success == null) {
- handleTcpClientFailure("Timed out waiting for message to be forwarded to the broker", null);
- }
- else if (!success) {
- handleTcpClientFailure("Failed to forward message to the broker", null);
- }
- else {
+ public void onSuccess(Boolean result) {
+ StompCommand command = StompHeaderAccessor.wrap(message).getCommand();
if (command == StompCommand.DISCONNECT) {
- this.stompConnection.setDisconnected();
+ resetTcpConnection();
}
}
- }
- catch (InterruptedException ex) {
- Thread.currentThread().interrupt();
- handleTcpClientFailure("Interrupted while forwarding message to the broker", ex);
- }
- return (success != null) ? success : false;
- }
- }
-
- private static class StompConnection {
-
- private volatile TcpConnection<Message<byte[]>, Message<byte[]>> connection;
-
- private AtomicReference<TcpConnection<Message<byte[]>, Message<byte[]>>> readyConnection =
- new AtomicReference<TcpConnection<Message<byte[]>, Message<byte[]>>>();
-
-
- public void setTcpConnection(TcpConnection<Message<byte[]>, Message<byte[]>> connection) {
- Assert.notNull(connection, "connection must not be null");
- this.connection = connection;
- }
-
- /**
- * Return the underlying {@link TcpConnection} but only after the CONNECTED STOMP
- * frame is received.
- */
- public TcpConnection<Message<byte[]>, Message<byte[]>> getReadyConnection() {
- return this.readyConnection.get();
- }
-
- public void setReady() {
- this.readyConnection.set(this.connection);
- }
+ @Override
+ public void onFailure(Throwable t) {
+ handleTcpConnectionFailure("Failed to send message " + message, t);
+ }
+ });
- public boolean isReady() {
- return (this.readyConnection.get() != null);
+ return future;
}
- public void setDisconnected() {
- this.readyConnection.set(null);
-
- TcpConnection<Message<byte[]>, Message<byte[]>> localConnection = this.connection;
- if (localConnection != null) {
- localConnection.close();
- this.connection = null;
+ public void resetTcpConnection() {
+ TcpConnection<byte[]> conn = this.tcpConnection;
+ this.isStompConnected = false;
+ this.tcpConnection = null;
+ if (conn != null) {
+ try {
+ this.tcpConnection.close();
+ }
+ catch (Throwable t) {
+ // ignore
+ }
}
}
- @Override
- public String toString() {
- return "StompConnection [ready=" + isReady() + "]";
- }
}
- private class SystemStompRelaySession extends StompRelaySession {
+ private class SystemStompConnectionHandler extends StompConnectionHandler {
- public static final String ID = "stompRelaySystemSessionId";
+ public static final String SESSION_ID = "stompRelaySystemSessionId";
- public SystemStompRelaySession() {
- super(ID, false, 5000);
+ public SystemStompConnectionHandler(StompHeaderAccessor connectHeaders) {
+ super(SESSION_ID, connectHeaders, false);
}
@Override
- protected void connected() {
- super.connected();
+ protected void afterStompConnected(StompHeaderAccessor connectedHeaders) {
+ super.afterStompConnected(connectedHeaders);
publishBrokerAvailableEvent();
}
@Override
- protected void disconnected(String errorMessage) {
- super.disconnected(errorMessage);
+ protected void handleTcpConnectionFailure(String errorMessage, Throwable t) {
+ super.handleTcpConnectionFailure(errorMessage, t);
publishBrokerUnavailableEvent();
}
@Override
- protected void connectionClosed() {
+ public void afterConnectionClosed() {
+ super.afterConnectionClosed();
publishBrokerUnavailableEvent();
}
@Override
- protected void handleForwardFailure(Message<?> message) {
- super.handleForwardFailure(message);
- throw new MessageDeliveryException(message);
+ public ListenableFuture<Boolean> forward(Message<?> message) {
+ try {
+ ListenableFuture<Boolean> future = super.forward(message);
+ if (!future.get()) {
+ throw new MessageDeliveryException(message);
+ }
+ return future;
+ }
+ catch (Throwable t) {
+ throw new MessageDeliveryException(message, t);
+ }
}
}
| true |
Other | spring-projects | spring-framework | 29934d7c0249e54897cb06c1d779dcaec4d6f4ee.json | Add TCP abstractions to spring-messaging
This change adds abstractions for opening and managing TCP connections
primarily for use with the STOMP broker support. As one immediate
benefit the change makes the StompBrokerRelayMessageHandler more
easy to test. | spring-messaging/src/main/java/org/springframework/messaging/support/tcp/FixedIntervalReconnectStrategy.java | @@ -0,0 +1,43 @@
+/*
+ * Copyright 2002-2013 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.messaging.support.tcp;
+
+
+/**
+ * A simple strategy for making reconnect attempts at a fixed interval.
+ *
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public class FixedIntervalReconnectStrategy implements ReconnectStrategy {
+
+ private final long interval;
+
+
+ /**
+ * @param interval the frequency, in millisecond, at which to try to reconnect
+ */
+ public FixedIntervalReconnectStrategy(long interval) {
+ this.interval = interval;
+ }
+
+ @Override
+ public Long getTimeToNextAttempt(int attemptCount) {
+ return this.interval;
+ }
+
+} | true |
Other | spring-projects | spring-framework | 29934d7c0249e54897cb06c1d779dcaec4d6f4ee.json | Add TCP abstractions to spring-messaging
This change adds abstractions for opening and managing TCP connections
primarily for use with the STOMP broker support. As one immediate
benefit the change makes the StompBrokerRelayMessageHandler more
easy to test. | spring-messaging/src/main/java/org/springframework/messaging/support/tcp/PromiseToListenableFutureAdapter.java | @@ -0,0 +1,110 @@
+/*
+ * Copyright 2002-2013 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.messaging.support.tcp;
+
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import org.springframework.util.Assert;
+import org.springframework.util.concurrent.ListenableFuture;
+import org.springframework.util.concurrent.ListenableFutureCallback;
+import org.springframework.util.concurrent.ListenableFutureCallbackRegistry;
+
+import reactor.core.composable.Promise;
+import reactor.function.Consumer;
+
+/**
+ * Adapts a reactor {@link Promise} to {@link ListenableFuture} optionally converting
+ * the result Object type {@code <S>} to the expected target type {@code <T>}.
+ *
+ * @param <S> the type of object expected from the {@link Promise}
+ * @param <T> the type of object expected from the {@link ListenableFuture}
+ *
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+abstract class PromiseToListenableFutureAdapter<S, T> implements ListenableFuture<T> {
+
+ private final Promise<S> promise;
+
+ private final ListenableFutureCallbackRegistry<T> registry = new ListenableFutureCallbackRegistry<T>();
+
+
+ protected PromiseToListenableFutureAdapter(Promise<S> promise) {
+
+ Assert.notNull(promise, "promise is required");
+ this.promise = promise;
+
+ this.promise.onSuccess(new Consumer<S>() {
+ @Override
+ public void accept(S result) {
+ try {
+ registry.success(adapt(result));
+ }
+ catch (Throwable t) {
+ registry.failure(t);
+ }
+ }
+ });
+
+ this.promise.onError(new Consumer<Throwable>() {
+ @Override
+ public void accept(Throwable t) {
+ registry.failure(t);
+ }
+ });
+ }
+
+ protected abstract T adapt(S adapteeResult);
+
+ @Override
+ public T get() {
+ S result = this.promise.get();
+ return adapt(result);
+ }
+
+ @Override
+ public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
+ S result = this.promise.await(timeout, unit);
+ if (result == null) {
+ throw new TimeoutException();
+ }
+ return adapt(result);
+ }
+
+ @Override
+ public boolean cancel(boolean mayInterruptIfRunning) {
+ return false;
+ }
+
+ @Override
+ public boolean isCancelled() {
+ return false;
+ }
+
+ @Override
+ public boolean isDone() {
+ return this.promise.isComplete();
+ }
+
+ @Override
+ public void addCallback(ListenableFutureCallback<? super T> callback) {
+ this.registry.addCallback(callback);
+ }
+
+} | true |
Other | spring-projects | spring-framework | 29934d7c0249e54897cb06c1d779dcaec4d6f4ee.json | Add TCP abstractions to spring-messaging
This change adds abstractions for opening and managing TCP connections
primarily for use with the STOMP broker support. As one immediate
benefit the change makes the StompBrokerRelayMessageHandler more
easy to test. | spring-messaging/src/main/java/org/springframework/messaging/support/tcp/ReactorNettyTcpClient.java | @@ -0,0 +1,127 @@
+/*
+ * Copyright 2002-2013 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.messaging.support.tcp;
+
+import java.net.InetSocketAddress;
+
+import org.springframework.messaging.Message;
+import org.springframework.util.concurrent.ListenableFuture;
+
+import reactor.core.Environment;
+import reactor.core.composable.Composable;
+import reactor.core.composable.Promise;
+import reactor.function.Consumer;
+import reactor.io.Buffer;
+import reactor.tcp.Reconnect;
+import reactor.tcp.TcpClient;
+import reactor.tcp.TcpConnection;
+import reactor.tcp.encoding.Codec;
+import reactor.tcp.netty.NettyTcpClient;
+import reactor.tcp.spec.TcpClientSpec;
+import reactor.tuple.Tuple;
+import reactor.tuple.Tuple2;
+
+/**
+ * A Reactor/Netty implementation of {@link TcpOperations}.
+ *
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public class ReactorNettyTcpClient<P> implements TcpOperations<P> {
+
+ private Environment environment;
+
+ private TcpClient<Message<P>, Message<P>> tcpClient;
+
+
+ public ReactorNettyTcpClient(String host, int port, Codec<Buffer, Message<P>, Message<P>> codec) {
+ this.environment = new Environment();
+ this.tcpClient = new TcpClientSpec<Message<P>, Message<P>>(NettyTcpClient.class)
+ .env(this.environment)
+ .codec(codec)
+ .connect(host, port)
+ .get();
+ }
+
+
+ @Override
+ public void connect(TcpConnectionHandler<P> connectionHandler) {
+ this.connect(connectionHandler, null);
+ }
+
+ @Override
+ public void connect(final TcpConnectionHandler<P> connectionHandler,
+ final ReconnectStrategy reconnectStrategy) {
+
+ Composable<TcpConnection<Message<P>, Message<P>>> composable;
+
+ if (reconnectStrategy != null) {
+ composable = this.tcpClient.open(new Reconnect() {
+ @Override
+ public Tuple2<InetSocketAddress, Long> reconnect(InetSocketAddress address, int attempt) {
+ return Tuple.of(address, reconnectStrategy.getTimeToNextAttempt(attempt));
+ }
+ });
+ }
+ else {
+ composable = this.tcpClient.open();
+ }
+
+ composable.when(Throwable.class, new Consumer<Throwable>() {
+ @Override
+ public void accept(Throwable ex) {
+ connectionHandler.afterConnectFailure(ex);
+ }
+ });
+
+ composable.consume(new Consumer<TcpConnection<Message<P>, Message<P>>>() {
+ @Override
+ public void accept(TcpConnection<Message<P>, Message<P>> connection) {
+ connection.on().close(new Runnable() {
+ @Override
+ public void run() {
+ connectionHandler.afterConnectionClosed();
+ }
+ });
+ connection.in().consume(new Consumer<Message<P>>() {
+ @Override
+ public void accept(Message<P> message) {
+ connectionHandler.handleMessage(message);
+ }
+ });
+ connectionHandler.afterConnected(new ReactorTcpConnection<P>(connection));
+ }
+ });
+ }
+
+ @Override
+ public ListenableFuture<Void> shutdown() {
+ try {
+ Promise<Void> promise = this.tcpClient.close();
+ return new PromiseToListenableFutureAdapter<Void, Void>(promise) {
+ @Override
+ protected Void adapt(Void result) {
+ return result;
+ }
+ };
+ }
+ finally {
+ this.environment.shutdown();
+ }
+ }
+
+} | true |
Other | spring-projects | spring-framework | 29934d7c0249e54897cb06c1d779dcaec4d6f4ee.json | Add TCP abstractions to spring-messaging
This change adds abstractions for opening and managing TCP connections
primarily for use with the STOMP broker support. As one immediate
benefit the change makes the StompBrokerRelayMessageHandler more
easy to test. | spring-messaging/src/main/java/org/springframework/messaging/support/tcp/ReactorTcpConnection.java | @@ -0,0 +1,134 @@
+/*
+ * Copyright 2002-2013 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.messaging.support.tcp;
+
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import org.springframework.messaging.Message;
+import org.springframework.util.concurrent.ListenableFuture;
+import org.springframework.util.concurrent.ListenableFutureCallback;
+import org.springframework.util.concurrent.ListenableFutureCallbackRegistry;
+
+import reactor.core.composable.Deferred;
+import reactor.core.composable.Promise;
+import reactor.core.composable.spec.DeferredPromiseSpec;
+import reactor.function.Consumer;
+
+
+public class ReactorTcpConnection<P> implements TcpConnection<P> {
+
+ private final reactor.tcp.TcpConnection<Message<P>, Message<P>> reactorTcpConnection;
+
+
+ public ReactorTcpConnection(reactor.tcp.TcpConnection<Message<P>, Message<P>> connection) {
+ this.reactorTcpConnection = connection;
+ }
+
+ @Override
+ public ListenableFuture<Boolean> send(Message<P> message) {
+ ConsumerListenableFuture future = new ConsumerListenableFuture();
+ this.reactorTcpConnection.send(message, future);
+ return future;
+ }
+
+ @Override
+ public void onReadInactivity(Runnable runnable, long inactivityDuration) {
+ this.reactorTcpConnection.on().readIdle(inactivityDuration, runnable);
+ }
+
+ @Override
+ public void onWriteInactivity(Runnable runnable, long inactivityDuration) {
+ this.reactorTcpConnection.on().writeIdle(inactivityDuration, runnable);
+ }
+
+ @Override
+ public void close() {
+ this.reactorTcpConnection.close();
+ }
+
+
+ // Use this temporarily until reactor provides a send method returning a Promise
+
+
+ private static class ConsumerListenableFuture implements ListenableFuture<Boolean>, Consumer<Boolean> {
+
+ final Deferred<Boolean, Promise<Boolean>> deferred = new DeferredPromiseSpec<Boolean>().get();
+
+ private final ListenableFutureCallbackRegistry<Boolean> registry =
+ new ListenableFutureCallbackRegistry<Boolean>();
+
+ @Override
+ public void accept(Boolean result) {
+
+ this.deferred.accept(result);
+
+ if (result == null) {
+ this.registry.failure(new TimeoutException());
+ }
+ else if (result) {
+ this.registry.success(result);
+ }
+ else {
+ this.registry.failure(new Exception("Failed send message"));
+ }
+ }
+
+ @Override
+ public Boolean get() {
+ try {
+ return this.deferred.compose().await();
+ }
+ catch (InterruptedException e) {
+ return Boolean.FALSE;
+ }
+ }
+
+ @Override
+ public Boolean get(long timeout, TimeUnit unit)
+ throws InterruptedException, ExecutionException, TimeoutException {
+
+ Boolean result = this.deferred.compose().await(timeout, unit);
+ if (result == null) {
+ throw new TimeoutException();
+ }
+ return result;
+ }
+
+ @Override
+ public boolean cancel(boolean mayInterruptIfRunning) {
+ return false;
+ }
+
+ @Override
+ public boolean isCancelled() {
+ return false;
+ }
+
+ @Override
+ public boolean isDone() {
+ return this.deferred.compose().isComplete();
+ }
+
+ @Override
+ public void addCallback(ListenableFutureCallback<? super Boolean> callback) {
+ this.registry.addCallback(callback);
+ }
+ }
+
+} | true |
Other | spring-projects | spring-framework | 29934d7c0249e54897cb06c1d779dcaec4d6f4ee.json | Add TCP abstractions to spring-messaging
This change adds abstractions for opening and managing TCP connections
primarily for use with the STOMP broker support. As one immediate
benefit the change makes the StompBrokerRelayMessageHandler more
easy to test. | spring-messaging/src/main/java/org/springframework/messaging/support/tcp/ReconnectStrategy.java | @@ -0,0 +1,36 @@
+/*
+ * Copyright 2002-2013 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.messaging.support.tcp;
+
+
+/**
+ * A contract to determine the frequency of reconnect attempts after connection failure.
+ *
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public interface ReconnectStrategy {
+
+ /**
+ * Return the time to the next attempt to reconnect.
+ *
+ * @param attemptCount how many reconnect attempts have been made already
+ * @return the amount of time in milliseconds or {@code null} to stop
+ */
+ Long getTimeToNextAttempt(int attemptCount);
+
+} | true |
Other | spring-projects | spring-framework | 29934d7c0249e54897cb06c1d779dcaec4d6f4ee.json | Add TCP abstractions to spring-messaging
This change adds abstractions for opening and managing TCP connections
primarily for use with the STOMP broker support. As one immediate
benefit the change makes the StompBrokerRelayMessageHandler more
easy to test. | spring-messaging/src/main/java/org/springframework/messaging/support/tcp/TcpConnection.java | @@ -0,0 +1,58 @@
+/*
+ * Copyright 2002-2013 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.messaging.support.tcp;
+
+import org.springframework.messaging.Message;
+import org.springframework.util.concurrent.ListenableFuture;
+
+/**
+ * A contract for sending messages and managing a TCP connection.
+ *
+ * @param <P> the type of payload for outbound {@link Message}s
+ *
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public interface TcpConnection<P> {
+
+ /**
+ * Send the given message.
+ * @param message the message
+ * @return whether the send succeeded or not
+ */
+ ListenableFuture<Boolean> send(Message<P> message);
+
+ /**
+ * Register a task to invoke after a period of of read inactivity.
+ * @param runnable the task to invoke
+ * @param duration the amount of inactive time in milliseconds
+ */
+ void onReadInactivity(Runnable runnable, long duration);
+
+ /**
+ * Register a task to invoke after a period of of write inactivity.
+ * @param runnable the task to invoke
+ * @param duration the amount of inactive time in milliseconds
+ */
+ void onWriteInactivity(Runnable runnable, long duration);
+
+ /**
+ * Close the connection.
+ */
+ void close();
+
+} | true |
Other | spring-projects | spring-framework | 29934d7c0249e54897cb06c1d779dcaec4d6f4ee.json | Add TCP abstractions to spring-messaging
This change adds abstractions for opening and managing TCP connections
primarily for use with the STOMP broker support. As one immediate
benefit the change makes the StompBrokerRelayMessageHandler more
easy to test. | spring-messaging/src/main/java/org/springframework/messaging/support/tcp/TcpConnectionHandler.java | @@ -0,0 +1,55 @@
+/*
+ * Copyright 2002-2013 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.messaging.support.tcp;
+
+import org.springframework.messaging.Message;
+
+/**
+ * A contract for managing lifecycle events for a TCP connection including
+ * the handling of incoming messages.
+ *
+ * @param <P> the type of payload for in and outbound messages
+ *
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public interface TcpConnectionHandler<P> {
+
+ /**
+ * Invoked after a connection is successfully established.
+ * @param connection the connection
+ */
+ void afterConnected(TcpConnection<P> connection);
+
+ /**
+ * Invoked after a connection failure.
+ * @param ex the exception
+ */
+ void afterConnectFailure(Throwable ex);
+
+ /**
+ * Handle a message received from the remote host.
+ * @param message the message
+ */
+ void handleMessage(Message<P> message);
+
+ /**
+ * Invoked after the connection is closed.
+ */
+ void afterConnectionClosed();
+
+} | true |
Other | spring-projects | spring-framework | 29934d7c0249e54897cb06c1d779dcaec4d6f4ee.json | Add TCP abstractions to spring-messaging
This change adds abstractions for opening and managing TCP connections
primarily for use with the STOMP broker support. As one immediate
benefit the change makes the StompBrokerRelayMessageHandler more
easy to test. | spring-messaging/src/main/java/org/springframework/messaging/support/tcp/TcpOperations.java | @@ -0,0 +1,51 @@
+/*
+ * Copyright 2002-2013 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.messaging.support.tcp;
+
+import org.springframework.util.concurrent.ListenableFuture;
+
+/**
+ * A contract for establishing TCP connections.
+ *
+ * @param <P> the type of payload for in and outbound messages
+ *
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public interface TcpOperations<P> {
+
+ /**
+ * Open a new connection.
+ *
+ * @param connectionHandler a handler to manage the connection
+ */
+ void connect(TcpConnectionHandler<P> connectionHandler);
+
+ /**
+ * Open a new connection and a strategy for reconnecting if the connection fails.
+ *
+ * @param connectionHandler a handler to manage the connection
+ * @param reconnectStrategy a strategy for reconnecting
+ */
+ void connect(TcpConnectionHandler<P> connectionHandler, ReconnectStrategy reconnectStrategy);
+
+ /**
+ * Shut down and close any open connections.
+ */
+ ListenableFuture<Void> shutdown();
+
+} | true |
Other | spring-projects | spring-framework | 29934d7c0249e54897cb06c1d779dcaec4d6f4ee.json | Add TCP abstractions to spring-messaging
This change adds abstractions for opening and managing TCP connections
primarily for use with the STOMP broker support. As one immediate
benefit the change makes the StompBrokerRelayMessageHandler more
easy to test. | spring-messaging/src/main/java/org/springframework/messaging/support/tcp/package-info.java | @@ -0,0 +1,9 @@
+/**
+ * Contains abstractions and implementation classes for establishing TCP connections via
+ * {@link org.springframework.messaging.support.tcp.TcpOperations TcpOperations},
+ * handling messages via
+ * {@link org.springframework.messaging.support.tcp.TcpConnectionHandler TcpConnectionHandler},
+ * as well as sending messages via
+ * {@link org.springframework.messaging.support.tcp.TcpConnection TcpConnection}.
+ */
+package org.springframework.messaging.support.tcp; | true |
Other | spring-projects | spring-framework | 29934d7c0249e54897cb06c1d779dcaec4d6f4ee.json | Add TCP abstractions to spring-messaging
This change adds abstractions for opening and managing TCP connections
primarily for use with the STOMP broker support. As one immediate
benefit the change makes the StompBrokerRelayMessageHandler more
easy to test. | spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java | @@ -231,14 +231,13 @@ public void relayReconnectsIfBrokerComesBackUp() throws Exception {
@Test
public void disconnectClosesRelaySessionCleanly() throws Exception {
- String sess1 = "sess1";
- MessageExchange conn1 = MessageExchangeBuilder.connect(sess1).build();
- this.responseHandler.expect(conn1);
- this.relay.handleMessage(conn1.message);
+ MessageExchange connect = MessageExchangeBuilder.connect("sess1").build();
+ this.responseHandler.expect(connect);
+ this.relay.handleMessage(connect.message);
this.responseHandler.awaitAndAssert();
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT);
- headers.setSessionId(sess1);
+ headers.setSessionId("sess1");
this.relay.handleMessage(MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build());
@@ -330,9 +329,9 @@ public String getAsString() {
StringBuilder sb = new StringBuilder("\n");
synchronized (this.monitor) {
- sb.append("INCOMPLETE:\n").append(this.expected).append("\n");
- sb.append("COMPLETE:\n").append(this.actual).append("\n");
- sb.append("UNMATCHED MESSAGES:\n").append(this.unexpected).append("\n");
+ sb.append("UNMATCHED EXPECTATIONS:\n").append(this.expected).append("\n");
+ sb.append("MATCHED EXPECTATIONS:\n").append(this.actual).append("\n");
+ sb.append("UNEXPECTED MESSAGES:\n").append(this.unexpected).append("\n");
}
return sb.toString(); | true |
Other | spring-projects | spring-framework | 3337fd32cba66aee549e4dddae61b86fe80832e3.json | Refine ResolvableType class
- Support for serialization
- Allow programmatic creation of an array from a given component type
- Allow programmatic creation with given generics
- Extract generics from Class types using Class.getTypeParameters()
- Move TypeVariableResolver to an inner class (and make method private)
- Refine 'resolve()' algorithm
Issue: SPR-10973 | spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java | @@ -256,10 +256,22 @@ public static Class[] resolveTypeArguments(Class<?> clazz, Class<?> genericIfc)
* @deprecated as of Spring 4.0 in favor of {@link ResolvableType}
*/
@Deprecated
- public static Class<?> resolveType(Type genericType, Map<TypeVariable, Type> typeVariableMap) {
- TypeVariableResolver variableResolver = new TypeVariableMapResolver(typeVariableMap);
- Class<?> resolved = ResolvableType.forType(genericType, variableResolver).resolve();
- return (resolved == null ? Object.class : resolved);
+ public static Class<?> resolveType(Type genericType, final Map<TypeVariable, Type> typeVariableMap) {
+
+ ResolvableType.VariableResolver variableResolver = new ResolvableType.VariableResolver() {
+ @Override
+ public ResolvableType resolveVariable(TypeVariable<?> variable) {
+ Type type = typeVariableMap.get(variable);
+ return (type == null ? null : ResolvableType.forType(type));
+ }
+
+ @Override
+ public Object getSource() {
+ return typeVariableMap;
+ }
+ };
+
+ return ResolvableType.forType(genericType, variableResolver).resolve(Object.class);
}
/**
@@ -303,40 +315,4 @@ private static void buildTypeVariableMap(ResolvableType type, Map<TypeVariable,
}
}
-
- /**
- * Adapts a {@code typeVariableMap} to a {@link TypeVariableResolver}.
- */
- private static class TypeVariableMapResolver implements TypeVariableResolver {
-
- private final Map<TypeVariable, Type> typeVariableMap;
-
- public TypeVariableMapResolver(Map<TypeVariable, Type> typeVariableMap) {
- Assert.notNull("TypeVariableMap must not be null");
- this.typeVariableMap = typeVariableMap;
- }
-
- @Override
- public Type resolveVariable(TypeVariable typeVariable) {
- return this.typeVariableMap.get(typeVariable);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj instanceof TypeVariableMapResolver) {
- TypeVariableMapResolver other = (TypeVariableMapResolver) obj;
- return this.typeVariableMap.equals(other.typeVariableMap);
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- return this.typeVariableMap.hashCode();
- }
- }
-
} | true |
Other | spring-projects | spring-framework | 3337fd32cba66aee549e4dddae61b86fe80832e3.json | Refine ResolvableType class
- Support for serialization
- Allow programmatic creation of an array from a given component type
- Allow programmatic creation with given generics
- Extract generics from Class types using Class.getTypeParameters()
- Move TypeVariableResolver to an inner class (and make method private)
- Refine 'resolve()' algorithm
Issue: SPR-10973 | spring-core/src/main/java/org/springframework/core/ResolvableType.java | @@ -16,6 +16,8 @@
package org.springframework.core;
+import java.io.ObjectStreamException;
+import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
@@ -41,9 +43,9 @@
*
* <p>{@code ResolvableTypes} may be obtained from {@link #forField(Field) fields},
* {@link #forMethodParameter(Method, int) method parameters},
- * {@link #forMethodReturnType(Method) method returns}, {@link #forClass(Class) classes}, or
- * directly from a {@link #forType(Type) java.lang.reflect.Type}. Most methods on this class
- * will themselves return {@link ResolvableType}s, allowing easy navigation. For example:
+ * {@link #forMethodReturnType(Method) method returns} or
+ * {@link #forClass(Class) classes}. Most methods on this class will themselves return
+ * {@link ResolvableType}s, allowing easy navigation. For example:
* <pre class="code">
* private HashMap<Integer, List<String>> myMap;
*
@@ -61,15 +63,14 @@
* @author Phillip Webb
* @author Juergen Hoeller
* @since 4.0
- * @see TypeVariableResolver
* @see #forField(Field)
* @see #forMethodParameter(Method, int)
* @see #forMethodReturnType(Method)
* @see #forConstructorParameter(Constructor, int)
* @see #forClass(Class)
* @see #forType(Type)
*/
-public final class ResolvableType implements TypeVariableResolver {
+public final class ResolvableType implements Serializable {
private static ConcurrentReferenceHashMap<ResolvableType, ResolvableType> cache =
new ConcurrentReferenceHashMap<ResolvableType, ResolvableType>();
@@ -79,7 +80,7 @@ public final class ResolvableType implements TypeVariableResolver {
* {@code ResolvableType} returned when no value is available. {@code NONE} is used
* in preference to {@code null} so that multiple method calls can be safely chained.
*/
- public static final ResolvableType NONE = new ResolvableType(null, null);
+ public static final ResolvableType NONE = new ResolvableType(null, null, null);
private static final ResolvableType[] EMPTY_TYPES_ARRAY = new ResolvableType[0];
@@ -91,25 +92,33 @@ public final class ResolvableType implements TypeVariableResolver {
private final Type type;
/**
- * The {@link TypeVariableResolver} to use or {@code null} if no resolver is available.
+ * The {@link VariableResolver} to use or {@code null} if no resolver is available.
*/
- private final TypeVariableResolver variableResolver;
+ private final VariableResolver variableResolver;
/**
* Stored copy of the resolved value or {@code null} if the resolve method has not
* yet been called. {@code void.class} is used when the resolve method failed.
*/
private Class<?> resolved;
+ /**
+ * The component type for an array or {@code null} if the type should be deduced.
+ */
+ private final ResolvableType componentType;
+
+
/**
* Private constructor used to create a new {@link ResolvableType}.
* @param type the underlying java type (may only be {@code null} for {@link #NONE})
* @param variableResolver the resolver used for {@link TypeVariable}s (may be {@code null})
+ * @param componentType an option declared component type for arrays (may be {@code null})
*/
- private ResolvableType(Type type, TypeVariableResolver variableResolver) {
+ private ResolvableType(Type type, VariableResolver variableResolver, ResolvableType componentType) {
this.type = type;
this.variableResolver = variableResolver;
+ this.componentType = componentType;
}
@@ -203,10 +212,12 @@ public ResolvableType getComponentType() {
if (this == NONE) {
return NONE;
}
+ if (this.componentType != null) {
+ return this.componentType;
+ }
if (this.type instanceof Class) {
Class<?> componentType = ((Class<?>) this.type).getComponentType();
- return (componentType == null ? NONE : forType(componentType,
- this.variableResolver));
+ return forType(componentType, this.variableResolver);
}
if (this.type instanceof GenericArrayType) {
return forType(((GenericArrayType) this.type).getGenericComponentType(),
@@ -272,11 +283,11 @@ public ResolvableType as(Class<?> type) {
* @see #getInterfaces()
*/
public ResolvableType getSuperType() {
- Class<?> resolved = resolve();
+ final Class<?> resolved = resolve();
if (resolved == null || resolved.getGenericSuperclass() == null) {
return NONE;
}
- return forType(resolved.getGenericSuperclass(), this);
+ return forType(SerializableTypeWrapper.forGenericSuperclass(resolved), asVariableResolver());
}
/**
@@ -286,16 +297,11 @@ public ResolvableType getSuperType() {
* @see #getSuperType()
*/
public ResolvableType[] getInterfaces() {
- Class<?> resolved = resolve();
+ final Class<?> resolved = resolve();
if (resolved == null || ObjectUtils.isEmpty(resolved.getGenericInterfaces())) {
return EMPTY_TYPES_ARRAY;
}
- Type[] interfaceTypes = resolved.getGenericInterfaces();
- ResolvableType[] interfaces = new ResolvableType[interfaceTypes.length];
- for (int i = 0; i < interfaceTypes.length; i++) {
- interfaces[i] = forType(interfaceTypes[i], this);
- }
- return interfaces;
+ return forTypes(SerializableTypeWrapper.forGenericInterfaces(resolved), asVariableResolver());
}
/**
@@ -407,11 +413,15 @@ public ResolvableType[] getGenerics() {
if (this == NONE) {
return EMPTY_TYPES_ARRAY;
}
+ if (this.type instanceof Class<?>) {
+ Class<?> typeClass = (Class<?>) this.type;
+ return forTypes(SerializableTypeWrapper.forTypeParameters(typeClass), this.variableResolver);
+ }
if (this.type instanceof ParameterizedType) {
- Type[] genericTypes = ((ParameterizedType) getType()).getActualTypeArguments();
- ResolvableType[] generics = new ResolvableType[genericTypes.length];
- for (int i = 0; i < genericTypes.length; i++) {
- generics[i] = forType(genericTypes[i], this);
+ Type[] actualTypeArguments = ((ParameterizedType) this.type).getActualTypeArguments();
+ ResolvableType[] generics = new ResolvableType[actualTypeArguments.length];
+ for (int i = 0; i < actualTypeArguments.length; i++) {
+ generics[i] = forType(actualTypeArguments[i], this.variableResolver);
}
return generics;
}
@@ -475,10 +485,8 @@ public Class<?> resolve() {
*/
public Class<?> resolve(Class<?> fallback) {
if (this.resolved == null) {
- synchronized (this) {
- this.resolved = resolveClass();
- this.resolved = (this.resolved == null ? void.class : this.resolved);
- }
+ Class<?> resolvedClass = resolveClass();
+ this.resolved = (resolvedClass == null ? void.class : resolvedClass);
}
return (this.resolved == void.class ? fallback : this.resolved);
}
@@ -495,27 +503,40 @@ private Class<?> resolveClass() {
/**
* Resolve this type by a single level, returning the resolved value or {@link #NONE}.
+ * NOTE: the returned {@link ResolvableType} should only be used as an intermediary as
+ * it cannot be serialized.
*/
ResolvableType resolveType() {
- Type resolved = null;
+
if (this.type instanceof ParameterizedType) {
- resolved = ((ParameterizedType) this.type).getRawType();
+ return forType(((ParameterizedType) this.type).getRawType(),
+ this.variableResolver);
}
- else if (this.type instanceof WildcardType) {
- resolved = resolveBounds(((WildcardType) this.type).getUpperBounds());
+
+ if (this.type instanceof WildcardType) {
+ Type resolved = resolveBounds(((WildcardType) this.type).getUpperBounds());
if (resolved == null) {
resolved = resolveBounds(((WildcardType) this.type).getLowerBounds());
}
+ return forType(resolved, this.variableResolver);
}
- else if (this.type instanceof TypeVariable) {
+
+ if (this.type instanceof TypeVariable) {
+ TypeVariable<?> variable = (TypeVariable<?>) this.type;
+
+ // Try default variable resolution
if (this.variableResolver != null) {
- resolved = this.variableResolver.resolveVariable((TypeVariable<?>) this.type);
- }
- if (resolved == null) {
- resolved = resolveBounds(((TypeVariable<?>) this.type).getBounds());
+ ResolvableType resolved = this.variableResolver.resolveVariable(variable);
+ if(resolved != null) {
+ return resolved;
+ }
}
+
+ // Fallback to bounds
+ return forType(resolveBounds(variable.getBounds()), this.variableResolver);
}
- return (resolved == null ? NONE : forType(resolved, this.variableResolver));
+
+ return NONE;
}
private Type resolveBounds(Type[] bounds) {
@@ -525,31 +546,35 @@ private Type resolveBounds(Type[] bounds) {
return bounds[0];
}
- public Type resolveVariable(TypeVariable<?> variable) {
- Assert.notNull("Variable must not be null");
+ private ResolvableType resolveVariable(TypeVariable<?> variable) {
+
+ if (this.type instanceof TypeVariable) {
+ return resolveType().resolveVariable(variable);
+ }
+
if (this.type instanceof ParameterizedType) {
+
ParameterizedType parameterizedType = (ParameterizedType) this.type;
- Type owner = parameterizedType.getOwnerType();
if (parameterizedType.getRawType().equals(variable.getGenericDeclaration())) {
TypeVariable<?>[] variables = resolve().getTypeParameters();
for (int i = 0; i < variables.length; i++) {
if (ObjectUtils.nullSafeEquals(variables[i].getName(), variable.getName())) {
- return parameterizedType.getActualTypeArguments()[i];
+ Type actualType = parameterizedType.getActualTypeArguments()[i];
+ return forType(actualType, this.variableResolver);
}
}
}
- Type resolved = null;
- if (this.variableResolver != null) {
- resolved = this.variableResolver.resolveVariable(variable);
- }
- if (resolved == null && owner != null) {
- resolved = forType(owner, this.variableResolver).resolveVariable(variable);
+
+ if (parameterizedType.getOwnerType() != null) {
+ return forType(parameterizedType.getOwnerType(),
+ this.variableResolver).resolveVariable(variable);
}
- return resolved;
}
- if (this.type instanceof TypeVariable) {
- return resolveType().resolveVariable(variable);
+
+ if (this.variableResolver != null) {
+ return this.variableResolver.resolveVariable(variable);
}
+
return null;
}
@@ -580,24 +605,71 @@ public boolean equals(Object obj) {
}
if (obj instanceof ResolvableType) {
ResolvableType other = (ResolvableType) obj;
- return ObjectUtils.nullSafeEquals(this.type, other.type) &&
- ObjectUtils.nullSafeEquals(this.variableResolver, other.variableResolver);
+ boolean equals = ObjectUtils.nullSafeEquals(this.type, other.type);
+ equals &= variableResolverSourceEquals(this.variableResolver, other.variableResolver);
+ equals &= ObjectUtils.nullSafeEquals(this.componentType, other.componentType);
+ return equals;
}
return false;
}
@Override
public int hashCode() {
- return ObjectUtils.nullSafeHashCode(this.type);
+ int hashCode = ObjectUtils.nullSafeHashCode(this.type);
+ hashCode = hashCode * 31 + ObjectUtils.nullSafeHashCode(this.variableResolver);
+ hashCode = hashCode * 31 + ObjectUtils.nullSafeHashCode(this.componentType);
+ return hashCode;
}
+ /**
+ * Custom serialization support for {@value #NONE}.
+ */
+ private Object readResolve() throws ObjectStreamException {
+ return (this.type == null ? NONE : this);
+ }
+
+ /**
+ * Adapts this {@link ResolvableType} to a {@link VariableResolver}.
+ */
+ VariableResolver asVariableResolver() {
+ if (this == NONE) {
+ return null;
+ }
+
+ return new VariableResolver() {
+ @Override
+ public ResolvableType resolveVariable(TypeVariable<?> variable) {
+ return ResolvableType.this.resolveVariable(variable);
+ }
+
+ @Override
+ public Object getSource() {
+ return ResolvableType.this;
+ }
+ };
+ }
+
+ private static boolean variableResolverSourceEquals(VariableResolver o1, VariableResolver o2) {
+ Object s1 = (o1 == null ? null : o1.getSource());
+ Object s2 = (o2 == null ? null : o2.getSource());
+ return ObjectUtils.nullSafeEquals(s1,s2);
+ }
+
+ private static ResolvableType[] forTypes(Type[] types, VariableResolver owner) {
+ ResolvableType[] result = new ResolvableType[types.length];
+ for (int i = 0; i < types.length; i++) {
+ result[i] = forType(types[i], owner);
+ }
+ return result;
+ }
/**
* Return a {@link ResolvableType} for the specified {@link Class}. For example
* {@code ResolvableType.forClass(MyArrayList.class)}.
* @param sourceClass the source class (must not be {@code null}
* @return a {@link ResolvableType} for the specified class
* @see #forClass(Class, Class)
+ * @see #forClassWithGenerics(Class, Class...)
*/
public static ResolvableType forClass(Class<?> sourceClass) {
Assert.notNull(sourceClass, "Source class must not be null");
@@ -609,14 +681,15 @@ public static ResolvableType forClass(Class<?> sourceClass) {
* implementation. For example
* {@code ResolvableType.forClass(List.class, MyArrayList.class)}.
* @param sourceClass the source class (must not be {@code null}
- * @param implementationClass the implementation class (must not be {@code null})
+ * @param implementationClass the implementation class
* @return a {@link ResolvableType} for the specified class backed by the given
* implementation class
* @see #forClass(Class)
+ * @see #forClassWithGenerics(Class, Class...)
*/
public static ResolvableType forClass(Class<?> sourceClass, Class<?> implementationClass) {
Assert.notNull(sourceClass, "Source class must not be null");
- ResolvableType asType = (implementationClass != null ? forType(implementationClass).as(sourceClass) : NONE);
+ ResolvableType asType = forType(implementationClass).as(sourceClass);
return (asType == NONE ? forType(sourceClass) : asType);
}
@@ -628,7 +701,7 @@ public static ResolvableType forClass(Class<?> sourceClass, Class<?> implementat
*/
public static ResolvableType forField(Field field) {
Assert.notNull(field, "Field must not be null");
- return forType(field.getGenericType());
+ return forType(SerializableTypeWrapper.forField(field));
}
/**
@@ -637,15 +710,14 @@ public static ResolvableType forField(Field field) {
* <p>Use this variant when the class that declares the field includes generic
* parameter variables that are satisfied by the implementation class.
* @param field the source field
- * @param implementationClass the implementation class (must not be {@code null})
+ * @param implementationClass the implementation class
* @return a {@link ResolvableType} for the specified field
* @see #forField(Field)
*/
public static ResolvableType forField(Field field, Class<?> implementationClass) {
Assert.notNull(field, "Field must not be null");
- TypeVariableResolver variableResolver = (implementationClass != null ?
- forType(implementationClass).as(field.getDeclaringClass()) : null);
- return forType(field.getGenericType(), variableResolver);
+ ResolvableType owner = forType(implementationClass).as(field.getDeclaringClass());
+ return forType(SerializableTypeWrapper.forField(field), owner.asVariableResolver());
}
/**
@@ -658,7 +730,7 @@ public static ResolvableType forField(Field field, Class<?> implementationClass)
*/
public static ResolvableType forField(Field field, int nestingLevel) {
Assert.notNull(field, "Field must not be null");
- return forType(field.getGenericType()).getNested(nestingLevel);
+ return forType(SerializableTypeWrapper.forField(field)).getNested(nestingLevel);
}
/**
@@ -669,15 +741,14 @@ public static ResolvableType forField(Field field, int nestingLevel) {
* @param field the source field
* @param nestingLevel the nesting level (1 for the outer level; 2 for a nested
* generic type; etc)
- * @param implementationClass the implementation class (must not be {@code null})
+ * @param implementationClass the implementation class
* @return a {@link ResolvableType} for the specified field
* @see #forField(Field)
*/
public static ResolvableType forField(Field field, int nestingLevel, Class<?> implementationClass) {
Assert.notNull(field, "Field must not be null");
- TypeVariableResolver variableResolver = (implementationClass != null ?
- forType(implementationClass).as(field.getDeclaringClass()) : null);
- return forType(field.getGenericType(), variableResolver).getNested(nestingLevel);
+ ResolvableType owner = forType(implementationClass).as(field.getDeclaringClass());
+ return forType(SerializableTypeWrapper.forField(field), owner.asVariableResolver()).getNested(nestingLevel);
}
/**
@@ -699,19 +770,45 @@ public static ResolvableType forConstructorParameter(Constructor<?> constructor,
* implementation class.
* @param constructor the source constructor (must not be {@code null})
* @param parameterIndex the parameter index
- * @param implementationClass the implementation class (must not be {@code null})
+ * @param implementationClass the implementation class
* @return a {@link ResolvableType} for the specified constructor parameter
* @see #forConstructorParameter(Constructor, int)
*/
public static ResolvableType forConstructorParameter(Constructor<?> constructor, int parameterIndex,
Class<?> implementationClass) {
-
Assert.notNull(constructor, "Constructor must not be null");
MethodParameter methodParameter = new MethodParameter(constructor, parameterIndex);
methodParameter.setContainingClass(implementationClass);
return forMethodParameter(methodParameter);
}
+ /**
+ * Return a {@link ResolvableType} for the specified {@link Method} return type.
+ * @param method the source for the method return type
+ * @return a {@link ResolvableType} for the specified method return
+ * @see #forMethodReturnType(Method, Class)
+ */
+ public static ResolvableType forMethodReturnType(Method method) {
+ Assert.notNull(method, "Method must not be null");
+ return forMethodParameter(MethodParameter.forMethodOrConstructor(method, -1));
+ }
+
+ /**
+ * Return a {@link ResolvableType} for the specified {@link Method} return type.
+ * Use this variant when the class that declares the method includes generic
+ * parameter variables that are satisfied by the implementation class.
+ * @param method the source for the method return type
+ * @param implementationClass the implementation class
+ * @return a {@link ResolvableType} for the specified method return
+ * @see #forMethodReturnType(Method)
+ */
+ public static ResolvableType forMethodReturnType(Method method, Class<?> implementationClass) {
+ Assert.notNull(method, "Method must not be null");
+ MethodParameter methodParameter = MethodParameter.forMethodOrConstructor(method, -1);
+ methodParameter.setContainingClass(implementationClass);
+ return forMethodParameter(methodParameter);
+ }
+
/**
* Return a {@link ResolvableType} for the specified {@link Method} parameter.
* @param method the source method (must not be {@code null})
@@ -731,12 +828,13 @@ public static ResolvableType forMethodParameter(Method method, int parameterInde
* includes generic parameter variables that are satisfied by the implementation class.
* @param method the source method (must not be {@code null})
* @param parameterIndex the parameter index
- * @param implementationClass the implementation class (must not be {@code null})
+ * @param implementationClass the implementation class
* @return a {@link ResolvableType} for the specified method parameter
* @see #forMethodParameter(Method, int, Class)
* @see #forMethodParameter(MethodParameter)
*/
- public static ResolvableType forMethodParameter(Method method, int parameterIndex, Class<?> implementationClass) {
+ public static ResolvableType forMethodParameter(Method method, int parameterIndex,
+ Class<?> implementationClass) {
Assert.notNull(method, "Method must not be null");
MethodParameter methodParameter = new MethodParameter(method, parameterIndex);
methodParameter.setContainingClass(implementationClass);
@@ -751,59 +849,119 @@ public static ResolvableType forMethodParameter(Method method, int parameterInde
*/
public static ResolvableType forMethodParameter(MethodParameter methodParameter) {
Assert.notNull(methodParameter, "MethodParameter must not be null");
- TypeVariableResolver variableResolver = (methodParameter.getContainingClass() != null ?
- forType(methodParameter.getContainingClass()).as(methodParameter.getDeclaringClass()) : null);
- return forType(methodParameter.getGenericParameterType(), variableResolver).getNested(
- methodParameter.getNestingLevel(), methodParameter.typeIndexesPerLevel);
+ ResolvableType owner = forType(methodParameter.getContainingClass()).as(
+ methodParameter.getDeclaringClass());
+ return forType(SerializableTypeWrapper.forMethodParameter(methodParameter),
+ owner.asVariableResolver()).getNested(methodParameter.getNestingLevel(),
+ methodParameter.typeIndexesPerLevel);
}
/**
- * Return a {@link ResolvableType} for the specified {@link Method} return type.
- * @param method the source for the method return type
- * @return a {@link ResolvableType} for the specified method return
- * @see #forMethodReturnType(Method, Class)
+ * Return a {@link ResolvableType} as a array of the specified {@code componentType}.
+ * @param componentType the component type
+ * @return a {@link ResolvableType} as an array of the specified component type
*/
- public static ResolvableType forMethodReturnType(Method method) {
- Assert.notNull(method, "Method must not be null");
- return forType(method.getGenericReturnType());
+ public static ResolvableType forArrayComponent(final ResolvableType componentType) {
+ Assert.notNull(componentType, "ComponentType must not be null");
+ Class<?> arrayClass = Array.newInstance(componentType.resolve(), 0).getClass();
+ return new ResolvableType(arrayClass, null, componentType);
}
/**
- * Return a {@link ResolvableType} for the specified {@link Method} return type.
- * Use this variant when the class that declares the method includes generic
- * parameter variables that are satisfied by the implementation class.
- * @param method the source for the method return type
- * @param implementationClass the implementation class (must not be {@code null})
- * @return a {@link ResolvableType} for the specified method return
- * @see #forMethodReturnType(Method)
+ * Return a {@link ResolvableType} for the specified {@link Class} with pre-declared
+ * generics.
+ * @param sourceClass the source class
+ * @param generics the generics of the class
+ * @return a {@link ResolvableType} for the specific class and generics
+ * @see #forClassWithGenerics(Class, ResolvableType...)
*/
- public static ResolvableType forMethodReturnType(Method method, Class<?> implementationClass) {
- Assert.notNull(method, "Method must not be null");
- TypeVariableResolver variableResolver = (implementationClass != null ?
- forType(implementationClass).as(method.getDeclaringClass()) : null);
- return forType(method.getGenericReturnType(), variableResolver);
+ public static ResolvableType forClassWithGenerics(Class<?> sourceClass,
+ Class<?>... generics) {
+ Assert.notNull(sourceClass, "Source class must not be null");
+ Assert.notNull(generics, "Generics must not be null");
+ ResolvableType[] resolvableGenerics = new ResolvableType[generics.length];
+ for (int i = 0; i < generics.length; i++) {
+ resolvableGenerics[i] = forClass(generics[i]);
+ }
+ return forClassWithGenerics(sourceClass, resolvableGenerics);
+ }
+
+ /**
+ * Return a {@link ResolvableType} for the specified {@link Class} with pre-declared
+ * generics.
+ * @param sourceClass the source class
+ * @param generics the generics of the class
+ * @return a {@link ResolvableType} for the specific class and generics
+ * @see #forClassWithGenerics(Class, Class...)
+ */
+ public static ResolvableType forClassWithGenerics(Class<?> sourceClass,
+ final ResolvableType... generics) {
+ Assert.notNull(sourceClass, "Source class must not be null");
+ Assert.notNull(generics, "Generics must not be null");
+ final TypeVariable<?>[] typeVariables = sourceClass.getTypeParameters();
+ Assert.isTrue(typeVariables.length == generics.length,
+ "Missmatched number of generics specified");
+ VariableResolver variableResolver = new VariableResolver() {
+ @Override
+ public ResolvableType resolveVariable(TypeVariable<?> variable) {
+ for (int i = 0; i < typeVariables.length; i++) {
+ if(typeVariables[i].equals(variable)) {
+ return generics[i];
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public Object getSource() {
+ return generics;
+ }
+ };
+
+ return forType(sourceClass, variableResolver);
}
/**
- * Return a {@link ResolvableType} for the specified {@link java.lang.reflect.Type}.
- * @param type the source type (must not be {@code null})
- * @return a {@link ResolvableType} for the specified {@link java.lang.reflect.Type}
+ * Return a {@link ResolvableType} for the specified {@link Type}. NOTE: The resulting
+ * {@link ResolvableType} may not be {@link Serializable}.
+ * @param type the source type or {@code null}
+ * @return a {@link ResolvableType} for the specified {@link Type}
+ * @see #forType(Type, ResolvableType)
*/
public static ResolvableType forType(Type type) {
- return forType(type, null);
+ return forType(type, (VariableResolver) null);
}
/**
- * Return a {@link ResolvableType} for the specified {@link java.lang.reflect.Type}
- * backed by a given {@link TypeVariableResolver}.
- * @param type the source type (must not be {@code null})
- * @param variableResolver the variable resolver
- * @return a {@link ResolvableType} for the specified {@link java.lang.reflect.Type}
- * and {@link TypeVariableResolver}
+ * Return a {@link ResolvableType} for the specified {@link Type} backed by the
+ * given owner type. NOTE: The resulting {@link ResolvableType} may not be
+ * {@link Serializable}.
+ * @param type the source type or {@code null}
+ * @param owner the owner type used to resolve variables
+ * @return a {@link ResolvableType} for the specified {@link Type} and owner
+ * @see #forType(Type)
*/
- public static ResolvableType forType(Type type, TypeVariableResolver variableResolver) {
- ResolvableType key = new ResolvableType(type, variableResolver);
+ public static ResolvableType forType(Type type, ResolvableType owner) {
+ VariableResolver variableResolver = null;
+ if (owner != null) {
+ variableResolver = owner.asVariableResolver();
+ }
+ return forType(type, variableResolver);
+ }
+
+ /**
+ * Return a {@link ResolvableType} for the specified {@link Type} backed by a given
+ * {@link VariableResolver}.
+ * @param type the source type or {@code null}
+ * @param variableResolver the variable resolver or {@code null}
+ * @return a {@link ResolvableType} for the specified {@link Type} and {@link VariableResolver}
+ */
+ static ResolvableType forType(Type type, VariableResolver variableResolver) {
+ if(type == null) {
+ return NONE;
+ }
// Check the cache, we may have a ResolvableType that may have already been resolved
+ ResolvableType key = new ResolvableType(type, variableResolver, null);
ResolvableType resolvableType = cache.get(key);
if (resolvableType == null) {
resolvableType = key;
@@ -813,6 +971,26 @@ public static ResolvableType forType(Type type, TypeVariableResolver variableRes
}
+ /**
+ * Strategy interface used to resolve {@link TypeVariable}s.
+ */
+ static interface VariableResolver extends Serializable {
+
+ /**
+ * Return the source of the resolver (used for hashCode and equals).
+ */
+ Object getSource();
+
+ /**
+ * Resolve the specified varaible.
+ * @param variable the variable to resolve
+ * @return the resolved variable or {@code null}
+ */
+ ResolvableType resolveVariable(TypeVariable<?> variable);
+
+ }
+
+
/**
* Internal helper to handle bounds from {@link WildcardType}s.
*/
@@ -886,7 +1064,8 @@ public static WildcardBounds get(ResolvableType type) {
Type[] bounds = boundsType == Kind.UPPER ? wildcardType.getUpperBounds() : wildcardType.getLowerBounds();
ResolvableType[] resolvableBounds = new ResolvableType[bounds.length];
for (int i = 0; i < bounds.length; i++) {
- resolvableBounds[i] = forType(bounds[i], type.variableResolver);
+ resolvableBounds[i] = ResolvableType.forType(bounds[i],
+ type.variableResolver);
}
return new WildcardBounds(boundsType, resolvableBounds);
} | true |
Other | spring-projects | spring-framework | 3337fd32cba66aee549e4dddae61b86fe80832e3.json | Refine ResolvableType class
- Support for serialization
- Allow programmatic creation of an array from a given component type
- Allow programmatic creation with given generics
- Extract generics from Class types using Class.getTypeParameters()
- Move TypeVariableResolver to an inner class (and make method private)
- Refine 'resolve()' algorithm
Issue: SPR-10973 | spring-core/src/main/java/org/springframework/core/SerializableTypeWrapper.java | @@ -0,0 +1,330 @@
+/*
+ * Copyright 2002-2013 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;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.Serializable;
+import java.lang.reflect.Field;
+import java.lang.reflect.GenericArrayType;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Proxy;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+import java.lang.reflect.WildcardType;
+
+import org.springframework.util.Assert;
+import org.springframework.util.ReflectionUtils;
+
+/**
+ * Internal utility class that can be used to obtain wrapped {@link Serializable} variants
+ * of {@link java.lang.reflect.Type}s.
+ *
+ * <p>{@link #forField(Field) Fields} or {@link #forMethodParameter(MethodParameter)
+ * MethodParameters} can be used as the root source for a serializable type. Alternatively
+ * the {@link #forGenericSuperclass(Class) superclass},
+ * {@link #forGenericInterfaces(Class) interfaces} or {@link #forTypeParameters(Class)
+ * type parameters} or a regular {@link Class} can also be used as source.
+ *
+ * <p>The returned type will either be a {@link Class} or a serializable proxy of
+ * {@link GenericArrayType}, {@link ParameterizedType}, {@link TypeVariable} or
+ * {@link WildcardType}. With the exception of {@link Class} (which is final) calls to
+ * methods that return further {@link Type}s (for example
+ * {@link GenericArrayType#getGenericComponentType()}) will be automatically wrapped.
+ *
+ * @author Phillip Webb
+ * @since 4.0
+ */
+abstract class SerializableTypeWrapper {
+
+ private static final Class<?>[] SUPPORTED_SERIALAZABLE_TYPES = { GenericArrayType.class,
+ ParameterizedType.class, TypeVariable.class, WildcardType.class };
+
+
+ /**
+ * Return a {@link Serializable} variant of {@link Field#getGenericType()}.
+ */
+ public static Type forField(Field field) {
+ Assert.notNull(field, "Field must not be null");
+ return forTypeProvider(new FieldTypeProvider(field));
+ }
+
+ /**
+ * Return a {@link Serializable} variant of
+ * {@link MethodParameter#getGenericParameterType()}.
+ */
+ public static Type forMethodParameter(MethodParameter methodParameter) {
+ return forTypeProvider(new MethodParameterTypeProvider(methodParameter));
+ }
+
+ /**
+ * Return a {@link Serializable} variant of {@link Class#getGenericSuperclass()}.
+ */
+ public static Type forGenericSuperclass(final Class<?> type) {
+ return forTypeProvider(new TypeProvider() {
+ @Override
+ public Type getType() {
+ return type.getGenericSuperclass();
+ }
+ });
+ }
+
+ /**
+ * Return a {@link Serializable} variant of {@link Class#getGenericInterfaces()}.
+ */
+ public static Type[] forGenericInterfaces(final Class<?> type) {
+ Type[] result = new Type[type.getGenericInterfaces().length];
+ for (int i = 0; i < result.length; i++) {
+ final int index = i;
+ result[i] = forTypeProvider(new TypeProvider() {
+ @Override
+ public Type getType() {
+ return type.getGenericInterfaces()[index];
+ }
+ });
+ }
+ return result;
+ }
+
+ /**
+ * Return a {@link Serializable} variant of {@link Class#getTypeParameters()}.
+ */
+ public static Type[] forTypeParameters(final Class<?> type) {
+ Type[] result = new Type[type.getTypeParameters().length];
+ for (int i = 0; i < result.length; i++) {
+ final int index = i;
+ result[i] = forTypeProvider(new TypeProvider() {
+ @Override
+ public Type getType() {
+ return type.getTypeParameters()[index];
+ }
+ });
+ }
+ return result;
+ }
+
+
+ /**
+ * Return a {@link Serializable} {@link Type} backed by a {@link TypeProvider} .
+ */
+ private static Type forTypeProvider(final TypeProvider provider) {
+ Assert.notNull(provider, "Provider must not be null");
+ if (provider.getType() instanceof Serializable || provider.getType() == null) {
+ return provider.getType();
+ }
+ for (Class<?> type : SUPPORTED_SERIALAZABLE_TYPES) {
+ if (type.isAssignableFrom(provider.getType().getClass())) {
+ ClassLoader classLoader = provider.getClass().getClassLoader();
+ Class<?>[] interfaces = new Class<?>[] { type, Serializable.class };
+ InvocationHandler handler = new TypeProxyInvocationHandler(provider);
+ return (Type) Proxy.newProxyInstance(classLoader, interfaces, handler);
+ }
+ }
+ throw new IllegalArgumentException("Unsupported Type class "
+ + provider.getType().getClass().getName());
+ }
+
+
+ /**
+ * A {@link Serializable} interface providing access to a {@link Type}.
+ */
+ private static interface TypeProvider extends Serializable {
+
+ /**
+ * Return the (possibly non {@link Serializable}) {@link Type}.
+ */
+ Type getType();
+
+ }
+
+
+ /**
+ * {@link Serializable} {@link InvocationHandler} used by the Proxied {@link Type}.
+ * Provides serialization support and enhances any methods that return {@code Type}
+ * or {@code Type[]}.
+ */
+ private static class TypeProxyInvocationHandler implements InvocationHandler,
+ Serializable {
+
+ private final TypeProvider provider;
+
+
+ public TypeProxyInvocationHandler(TypeProvider provider) {
+ this.provider = provider;
+ }
+
+
+ @Override
+ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
+ if (Type.class.equals(method.getReturnType()) && args == null) {
+ return forTypeProvider(new MethodInvokeTypeProvider(this.provider, method, -1));
+ }
+ if (Type[].class.equals(method.getReturnType()) && args == null) {
+ Type[] result = new Type[((Type[]) method.invoke(this.provider.getType(), args)).length];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = forTypeProvider(new MethodInvokeTypeProvider(this.provider, method, i));
+ }
+ return result;
+ }
+ return method.invoke(this.provider.getType(), args);
+ }
+
+ }
+
+
+
+ /**
+ * {@link TypeProvider} for {@link Type}s obtained from a {@link Field}.
+ */
+ private static class FieldTypeProvider implements TypeProvider {
+
+ private final String fieldName;
+
+ private final Class<?> declaringClass;
+
+ private transient Field field;
+
+
+ public FieldTypeProvider(Field field) {
+ this.fieldName = field.getName();
+ this.declaringClass = field.getDeclaringClass();
+ this.field = field;
+ }
+
+
+ @Override
+ public Type getType() {
+ return this.field.getGenericType();
+ }
+
+ private void readObject(ObjectInputStream inputStream) throws IOException,
+ ClassNotFoundException {
+ inputStream.defaultReadObject();
+ try {
+ this.field = this.declaringClass.getDeclaredField(this.fieldName);
+ }
+ catch (Throwable ex) {
+ throw new IllegalStateException(
+ "Could not find original class structure", ex);
+ }
+ }
+
+ }
+
+
+ /**
+ * {@link TypeProvider} for {@link Type}s obtained from a {@link MethodParameter}.
+ */
+ private static class MethodParameterTypeProvider implements TypeProvider {
+
+ private final String methodName;
+
+ private final Class<?>[] parameterTypes;
+
+ private final Class<?> declaringClass;
+
+ private final int parameterIndex;
+
+ private transient MethodParameter methodParameter;
+
+
+ public MethodParameterTypeProvider(MethodParameter methodParameter) {
+ if (methodParameter.getMethod() != null) {
+ this.methodName = methodParameter.getMethod().getName();
+ this.parameterTypes = methodParameter.getMethod().getParameterTypes();
+ }
+ else {
+ this.methodName = null;
+ this.parameterTypes = methodParameter.getConstructor().getParameterTypes();
+ }
+ this.declaringClass = methodParameter.getDeclaringClass();
+ this.parameterIndex = methodParameter.getParameterIndex();
+ this.methodParameter = methodParameter;
+ }
+
+
+ @Override
+ public Type getType() {
+ return this.methodParameter.getGenericParameterType();
+ }
+
+ private void readObject(ObjectInputStream inputStream) throws IOException,
+ ClassNotFoundException {
+ inputStream.defaultReadObject();
+ try {
+ if (this.methodName != null) {
+ this.methodParameter = new MethodParameter(
+ this.declaringClass.getDeclaredMethod(this.methodName,
+ this.parameterTypes), this.parameterIndex);
+ }
+ else {
+ this.methodParameter = new MethodParameter(
+ this.declaringClass.getDeclaredConstructor(this.parameterTypes),
+ this.parameterIndex);
+ }
+ }
+ catch (Throwable ex) {
+ throw new IllegalStateException(
+ "Could not find original class structure", ex);
+ }
+ }
+
+ }
+
+
+ /**
+ * {@link TypeProvider} for {@link Type}s obtained by invoking a no-arg method.
+ */
+ private static class MethodInvokeTypeProvider implements TypeProvider {
+
+ private final TypeProvider provider;
+
+ private final String methodName;
+
+ private final int index;
+
+ private transient Object result;
+
+
+ public MethodInvokeTypeProvider(TypeProvider provider, Method method, int index) {
+ this.provider = provider;
+ this.methodName = method.getName();
+ this.index = index;
+ this.result = ReflectionUtils.invokeMethod(method, provider.getType());
+ }
+
+
+ @Override
+ public Type getType() {
+ if (this.result instanceof Type || this.result == null) {
+ return (Type) this.result;
+ }
+ return ((Type[])this.result)[this.index];
+ }
+
+ private void readObject(ObjectInputStream inputStream) throws IOException,
+ ClassNotFoundException {
+ inputStream.defaultReadObject();
+ Method method = ReflectionUtils.findMethod(
+ this.provider.getType().getClass(), this.methodName);
+ this.result = ReflectionUtils.invokeMethod(method, this.provider.getType());
+ }
+
+ }
+} | true |
Other | spring-projects | spring-framework | 3337fd32cba66aee549e4dddae61b86fe80832e3.json | Refine ResolvableType class
- Support for serialization
- Allow programmatic creation of an array from a given component type
- Allow programmatic creation with given generics
- Extract generics from Class types using Class.getTypeParameters()
- Move TypeVariableResolver to an inner class (and make method private)
- Refine 'resolve()' algorithm
Issue: SPR-10973 | spring-core/src/main/java/org/springframework/core/TypeVariableResolver.java | @@ -1,40 +0,0 @@
-/*
- * Copyright 2002-2013 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;
-
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-
-/**
- * Strategy interface that can be used to resolve {@link java.lang.reflect.TypeVariable}s.
- *
- * @author Phillip Webb
- * @since 4.0
- * @see ResolvableType
- * @see GenericTypeResolver
- */
-interface TypeVariableResolver {
-
- /**
- * Resolve the specified type variable.
- * @param typeVariable the type variable to resolve (must not be {@code null})
- * @return the resolved {@link java.lang.reflect.Type} for the variable or
- * {@code null} if the variable cannot be resolved.
- */
- Type resolveVariable(TypeVariable<?> typeVariable);
-
-} | true |
Other | spring-projects | spring-framework | 3337fd32cba66aee549e4dddae61b86fe80832e3.json | Refine ResolvableType class
- Support for serialization
- Allow programmatic creation of an array from a given component type
- Allow programmatic creation with given generics
- Extract generics from Class types using Class.getTypeParameters()
- Move TypeVariableResolver to an inner class (and make method private)
- Refine 'resolve()' algorithm
Issue: SPR-10973 | spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java | @@ -16,6 +16,10 @@
package org.springframework.core;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
@@ -44,12 +48,14 @@
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.runners.MockitoJUnitRunner;
-
+import org.springframework.core.ResolvableType.VariableResolver;
import org.springframework.util.MultiValueMap;
+import static org.mockito.BDDMockito.*;
+
+import static org.mockito.Mockito.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
-import static org.mockito.BDDMockito.*;
/**
* Tests for {@link ResolvableType}.
@@ -86,7 +92,6 @@ public void noneReturnValues() throws Exception {
assertThat(none.resolve(String.class), equalTo((Class) String.class));
assertThat(none.resolveGeneric(0), nullValue());
assertThat(none.resolveGenerics().length, equalTo(0));
- assertThat(none.resolveVariable(mock(TypeVariable.class)), nullValue());
assertThat(none.toString(), equalTo("?"));
assertThat(none.isAssignableFrom(ResolvableType.forClass(Object.class)), equalTo(false));
}
@@ -415,6 +420,13 @@ public void getGenericOfGeneric() throws Exception {
assertThat(type.getGeneric().getGeneric().getType(), equalTo((Type) String.class));
}
+ @Test
+ public void genericOfGenericWithAs() throws Exception {
+ ResolvableType type = ResolvableType.forField(Fields.class.getField("stringListList")).asCollection();
+ assertThat(type.toString(), equalTo("java.util.Collection<java.util.List<java.lang.String>>"));
+ assertThat(type.getGeneric().asCollection().toString(), equalTo("java.util.Collection<java.lang.String>"));
+ }
+
@Test
public void getGenericOfGenericByIndexes() throws Exception {
ResolvableType type = ResolvableType.forField(Fields.class.getField("stringListList"));
@@ -437,13 +449,21 @@ public void hasGenerics() throws Exception {
}
@Test
- public void getGenerics() throws Exception {
+ public void getGenericsFromParameterizedType() throws Exception {
ResolvableType type = ResolvableType.forClass(List.class, ExtendsList.class);
ResolvableType[] generics = type.getGenerics();
assertThat(generics.length, equalTo(1));
assertThat(generics[0].resolve(), equalTo((Class) CharSequence.class));
}
+ @Test
+ public void getGenericsFromClass() throws Exception {
+ ResolvableType type = ResolvableType.forClass(List.class);
+ ResolvableType[] generics = type.getGenerics();
+ assertThat(generics.length, equalTo(1));
+ assertThat(generics[0].getType().toString(), equalTo("E"));
+ }
+
@Test
public void noGetGenerics() throws Exception {
ResolvableType type = ResolvableType.forClass(ExtendsList.class);
@@ -549,9 +569,8 @@ public void resolveVariableFromInheritedFieldSwitched() throws Exception {
public void doesResolveFromOuterOwner() throws Exception {
ResolvableType type = ResolvableType.forField(
Fields.class.getField("listOfListOfUnknown")).as(Collection.class);
- ResolvableType generic = type.getGeneric(0);
- assertThat(generic.resolve(), equalTo((Class) List.class));
- assertThat(generic.as(Collection.class).getGeneric(0).as(Collection.class).resolve(), nullValue());
+ assertThat(type.getGeneric(0).resolve(), equalTo((Class) List.class));
+ assertThat(type.getGeneric(0).as(Collection.class).getGeneric(0).as(Collection.class).resolve(), nullValue());
}
@Test
@@ -721,15 +740,16 @@ public void resolveTypeVariableFromType() throws Exception {
public void resolveTypeVariableFromTypeWithVariableResolver() throws Exception {
Type sourceType = Methods.class.getMethod("typedReturn").getGenericReturnType();
ResolvableType type = ResolvableType.forType(
- sourceType, ResolvableType.forClass(TypedMethods.class).as(Methods.class));
+ sourceType, ResolvableType.forClass(TypedMethods.class).as(Methods.class).asVariableResolver());
assertThat(type.resolve(), equalTo((Class) String.class));
assertThat(type.getType().toString(), equalTo("T"));
}
@Test
public void resolveTypeWithCustomVariableResolver() throws Exception {
- TypeVariableResolver variableResolver = mock(TypeVariableResolver.class);
- given(variableResolver.resolveVariable((TypeVariable<?>) anyObject())).willReturn(Long.class);
+ VariableResolver variableResolver = mock(VariableResolver.class);
+ ResolvableType longType = ResolvableType.forClass(Long.class);
+ given(variableResolver.resolveVariable((TypeVariable<?>) anyObject())).willReturn(longType);
ResolvableType variable = ResolvableType.forType(
Fields.class.getField("typeVariableType").getGenericType(), variableResolver);
@@ -747,10 +767,10 @@ public void resolveTypeWithCustomVariableResolver() throws Exception {
public void toStrings() throws Exception {
assertThat(ResolvableType.NONE.toString(), equalTo("?"));
- assertFieldToStringValue("classType", "java.util.List");
+ assertFieldToStringValue("classType", "java.util.List<?>");
assertFieldToStringValue("typeVariableType", "?");
assertFieldToStringValue("parameterizedType", "java.util.List<?>");
- assertFieldToStringValue("arrayClassType", "java.util.List[]");
+ assertFieldToStringValue("arrayClassType", "java.util.List<?>[]");
assertFieldToStringValue("genericArrayType", "java.util.List<java.lang.String>[]");
assertFieldToStringValue("genericMultiArrayType", "java.util.List<java.lang.String>[][][]");
assertFieldToStringValue("wildcardType", "java.util.List<java.lang.Number>");
@@ -761,7 +781,7 @@ public void toStrings() throws Exception {
assertFieldToStringValue("stringArrayList", "java.util.List<java.lang.String[]>");
assertFieldToStringValue("stringIntegerMultiValueMap", "org.springframework.util.MultiValueMap<java.lang.String, java.lang.Integer>");
assertFieldToStringValue("stringIntegerMultiValueMapSwitched", VariableNameSwitch.class.getName() + "<java.lang.Integer, java.lang.String>");
- assertFieldToStringValue("listOfListOfUnknown", "java.util.List<java.util.List>");
+ assertFieldToStringValue("listOfListOfUnknown", "java.util.List<java.util.List<?>>");
assertTypedFieldToStringValue("typeVariableType", "java.lang.String");
assertTypedFieldToStringValue("parameterizedType", "java.util.List<java.lang.String>");
@@ -789,6 +809,17 @@ public void resolveFromOuterClass() throws Exception {
assertThat(type.resolve(), equalTo((Type) Integer.class));
}
+ @Test
+ public void resolveFromClassWithGenerics() throws Exception {
+ ResolvableType type = ResolvableType.forClassWithGenerics(List.class, ResolvableType.forClassWithGenerics(List.class, String.class));
+ assertThat(type.asCollection().toString(), equalTo("java.util.Collection<java.util.List<java.lang.String>>"));
+ assertThat(type.asCollection().getGeneric().toString(), equalTo("java.util.List<java.lang.String>"));
+ assertThat(type.asCollection().getGeneric().asCollection().toString(), equalTo("java.util.Collection<java.lang.String>"));
+ assertThat(type.toString(), equalTo("java.util.List<java.util.List<java.lang.String>>"));
+ assertThat(type.asCollection().getGeneric().getGeneric().resolve(), equalTo((Type) String.class));
+ }
+
+
@Test
public void isAssignableFromMustNotBeNull() throws Exception {
this.thrown.expect(IllegalArgumentException.class);
@@ -997,7 +1028,7 @@ public void isAssignableFromForComplexWildcards() throws Exception {
public void hashCodeAndEquals() throws Exception {
ResolvableType forClass = ResolvableType.forClass(List.class);
ResolvableType forFieldDirect = ResolvableType.forField(Fields.class.getDeclaredField("stringList"));
- ResolvableType forFieldViaType = ResolvableType.forType(Fields.class.getDeclaredField("stringList").getGenericType());
+ ResolvableType forFieldViaType = ResolvableType.forType(Fields.class.getDeclaredField("stringList").getGenericType(), (VariableResolver) null);
ResolvableType forFieldWithImplementation = ResolvableType.forField(Fields.class.getDeclaredField("stringList"), TypedFields.class);
assertThat(forClass, equalTo(forClass));
@@ -1024,6 +1055,60 @@ public void javaDocSample() throws Exception {
assertThat(t.resolveGeneric(1, 0), equalTo((Class) String.class));
}
+ @Test
+ public void forClassWithGenerics() throws Exception {
+ ResolvableType elementType = ResolvableType.forClassWithGenerics(Map.class, Integer.class, String.class);
+ ResolvableType listType = ResolvableType.forClassWithGenerics(List.class, elementType);
+ assertThat(listType.toString(), equalTo("java.util.List<java.util.Map<java.lang.Integer, java.lang.String>>"));
+ }
+
+ @Test
+ public void classWithGenericsAs() throws Exception {
+ ResolvableType type = ResolvableType.forClassWithGenerics(MultiValueMap.class, Integer.class, String.class);
+ assertThat(type.asMap().toString(), equalTo("java.util.Map<java.lang.Integer, java.util.List<java.lang.String>>"));
+ }
+
+ @Test
+ public void forClassWithMismatchedGenerics() throws Exception {
+ thrown.expect(IllegalArgumentException.class);
+ thrown.expectMessage("Missmatched number of generics specified");
+ ResolvableType.forClassWithGenerics(Map.class, Integer.class);
+ }
+
+ @Test
+ public void forArrayComponent() throws Exception {
+ ResolvableType elementType = ResolvableType.forField(Fields.class.getField("stringList"));
+ ResolvableType type = ResolvableType.forArrayComponent(elementType);
+ assertThat(type.toString(), equalTo("java.util.List<java.lang.String>[]"));
+ assertThat(type.resolve(), equalTo((Class) List[].class));
+ }
+
+ @Test
+ public void serialize() throws Exception {
+ testSerialization(ResolvableType.forClass(List.class));
+ testSerialization(ResolvableType.forField(Fields.class.getField("charSequenceList")));
+ testSerialization(ResolvableType.forMethodParameter(Methods.class.getMethod("charSequenceParameter", List.class), 0));
+ testSerialization(ResolvableType.forMethodReturnType(Methods.class.getMethod("charSequenceReturn")));
+ testSerialization(ResolvableType.forConstructorParameter(Constructors.class.getConstructor(List.class), 0));
+ testSerialization(ResolvableType.forField(Fields.class.getField("charSequenceList")).getGeneric());
+ testSerialization(ResolvableType.forField(Fields.class.getField("charSequenceList")).asCollection());
+ testSerialization(ResolvableType.forClass(ExtendsMap.class).getSuperType());
+ ResolvableType deserializedNone = testSerialization(ResolvableType.NONE);
+ assertThat(deserializedNone, sameInstance(ResolvableType.NONE));
+ }
+
+ private ResolvableType testSerialization(ResolvableType type) throws Exception {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(bos);
+ oos.writeObject(type);
+ oos.close();
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
+ ResolvableType read = (ResolvableType) ois.readObject();
+ assertThat(read, equalTo(type));
+ assertThat(read.getType(), equalTo(type.getType()));
+ assertThat(read.resolve(), equalTo((Class) type.resolve()));
+ return read;
+ }
private static AssertAssignbleMatcher assertAssignable(final ResolvableType type,
final ResolvableType... fromTypes) { | true |
Other | spring-projects | spring-framework | 3337fd32cba66aee549e4dddae61b86fe80832e3.json | Refine ResolvableType class
- Support for serialization
- Allow programmatic creation of an array from a given component type
- Allow programmatic creation with given generics
- Extract generics from Class types using Class.getTypeParameters()
- Move TypeVariableResolver to an inner class (and make method private)
- Refine 'resolve()' algorithm
Issue: SPR-10973 | spring-core/src/test/java/org/springframework/core/SerializableTypeWrapperTests.java | @@ -0,0 +1,171 @@
+/*
+ * Copyright 2002-2013 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;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.lang.reflect.Constructor;
+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.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+import static org.hamcrest.Matchers.*;
+import static org.junit.Assert.*;
+
+
+/**
+ * Tests for {@link SerializableTypeWrapper}.
+ *
+ * @author Phillip Webb
+ */
+public class SerializableTypeWrapperTests {
+
+ @Test
+ public void forField() throws Exception {
+ Type type = SerializableTypeWrapper.forField(Fields.class.getField("parameterizedType"));
+ assertThat(type.toString(), equalTo("java.util.List<java.lang.String>"));
+ assertSerialzable(type);
+ }
+
+ @Test
+ public void forMethodParameter() throws Exception {
+ Method method = Methods.class.getDeclaredMethod("method", Class.class, Object.class);
+ Type type = SerializableTypeWrapper.forMethodParameter(MethodParameter.forMethodOrConstructor(method, 0));
+ assertThat(type.toString(), equalTo("java.lang.Class<T>"));
+ assertSerialzable(type);
+ }
+
+ @Test
+ public void forConstructor() throws Exception {
+ Constructor<?> constructor = Constructors.class.getDeclaredConstructor(List.class);
+ Type type = SerializableTypeWrapper.forMethodParameter(MethodParameter.forMethodOrConstructor(constructor, 0));
+ assertThat(type.toString(), equalTo("java.util.List<java.lang.String>"));
+ assertSerialzable(type);
+ }
+
+ @Test
+ public void forGenericSuperClass() throws Exception {
+ Type type = SerializableTypeWrapper.forGenericSuperclass(ArrayList.class);
+ assertThat(type.toString(), equalTo("java.util.AbstractList<E>"));
+ assertSerialzable(type);
+ }
+
+ @Test
+ public void forGenericInterfaces() throws Exception {
+ Type type = SerializableTypeWrapper.forGenericInterfaces(List.class)[0];
+ assertThat(type.toString(), equalTo("java.util.Collection<E>"));
+ assertSerialzable(type);
+ }
+
+ @Test
+ public void forTypeParamters() throws Exception {
+ Type type = SerializableTypeWrapper.forTypeParameters(List.class)[0];
+ assertThat(type.toString(), equalTo("E"));
+ assertSerialzable(type);
+ }
+
+ @Test
+ public void classType() throws Exception {
+ Type type = SerializableTypeWrapper.forField(Fields.class.getField("classType"));
+ assertThat(type.toString(), equalTo("class java.lang.String"));
+ assertSerialzable(type);
+ }
+
+ @Test
+ public void genericArrayType() throws Exception {
+ GenericArrayType type = (GenericArrayType) SerializableTypeWrapper.forField(Fields.class.getField("genericArrayType"));
+ assertThat(type.toString(), equalTo("java.util.List<java.lang.String>[]"));
+ assertSerialzable(type);
+ assertSerialzable(type.getGenericComponentType());
+ }
+
+ @Test
+ public void parameterizedType() throws Exception {
+ ParameterizedType type = (ParameterizedType) SerializableTypeWrapper.forField(Fields.class.getField("parameterizedType"));
+ assertThat(type.toString(), equalTo("java.util.List<java.lang.String>"));
+ assertSerialzable(type);
+ assertSerialzable(type.getOwnerType());
+ assertSerialzable(type.getRawType());
+ assertSerialzable(type.getActualTypeArguments());
+ assertSerialzable(type.getActualTypeArguments()[0]);
+ }
+
+ @Test
+ public void typeVariableType() throws Exception {
+ TypeVariable<?> type = (TypeVariable<?>) SerializableTypeWrapper.forField(Fields.class.getField("typeVariableType"));
+ assertThat(type.toString(), equalTo("T"));
+ assertSerialzable(type);
+ assertSerialzable(type.getBounds());
+ }
+
+ @Test
+ public void wildcardType() throws Exception {
+ ParameterizedType typeSource = (ParameterizedType) SerializableTypeWrapper.forField(Fields.class.getField("wildcardType"));
+ WildcardType type = (WildcardType) typeSource.getActualTypeArguments()[0];
+ assertThat(type.toString(), equalTo("? extends java.lang.CharSequence"));
+ assertSerialzable(type);
+ assertSerialzable(type.getLowerBounds());
+ assertSerialzable(type.getUpperBounds());
+ }
+
+
+ private void assertSerialzable(Object source) throws Exception {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(bos);
+ oos.writeObject(source);
+ oos.close();
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
+ assertThat(ois.readObject(), equalTo(source));
+ }
+
+
+ static class Fields<T> {
+
+ public String classType;
+
+ public List<String>[] genericArrayType;
+
+ public List<String> parameterizedType;
+
+ public T typeVariableType;
+
+ public List<? extends CharSequence> wildcardType;
+
+ }
+
+ static interface Methods {
+
+ <T> List<T> method(Class<T> p1, T p2);
+
+ }
+
+ static class Constructors {
+
+ public Constructors(List<String> p) {
+ }
+
+ }
+} | true |
Other | spring-projects | spring-framework | 190bf247a30a2f13ead89383e5e0476584652dd1.json | Add helper method to ResourceHandlerRegistry | spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistry.java | @@ -17,6 +17,7 @@
package org.springframework.web.servlet.config.annotation;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -64,6 +65,7 @@ public ResourceHandlerRegistry(ApplicationContext applicationContext, ServletCon
this.servletContext = servletContext;
}
+
/**
* Add a resource handler for serving static resources based on the specified URL path patterns.
* The handler will be invoked for every incoming request that matches to one of the specified path patterns.
@@ -75,6 +77,18 @@ public ResourceHandlerRegistration addResourceHandler(String... pathPatterns) {
return registration;
}
+ /**
+ * Whether a resource handler has already been registered for the given pathPattern.
+ */
+ public boolean hasMappingForPattern(String pathPattern) {
+ for (ResourceHandlerRegistration registration : registrations) {
+ if (Arrays.asList(registration.getPathPatterns()).contains(pathPattern)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
/**
* Specify the order to use for resource handling relative to other {@link HandlerMapping}s configured in
* the Spring MVC application context. The default value used is {@code Integer.MAX_VALUE-1}. | true |
Other | spring-projects | spring-framework | 190bf247a30a2f13ead89383e5e0476584652dd1.json | Add helper method to ResourceHandlerRegistry | spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java | @@ -16,9 +16,6 @@
package org.springframework.web.servlet.config.annotation;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.test.MockHttpServletRequest;
@@ -29,6 +26,8 @@
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
+import static org.junit.Assert.*;
+
/**
* Test fixture with a {@link ResourceHandlerRegistry}.
*
@@ -84,6 +83,13 @@ public void order() {
assertEquals(0, registry.getHandlerMapping().getOrder());
}
+ @Test
+ public void hasMappingForPattern() {
+ assertTrue(registry.hasMappingForPattern("/resources/**"));
+ assertFalse(registry.hasMappingForPattern("/whatever"));
+ }
+
+
private ResourceHttpRequestHandler getHandler(String pathPattern) {
SimpleUrlHandlerMapping handlerMapping = (SimpleUrlHandlerMapping) registry.getHandlerMapping();
return (ResourceHttpRequestHandler) handlerMapping.getUrlMap().get(pathPattern); | true |
Other | spring-projects | spring-framework | 079bebcfb519dabcd975ccc91a7bba6812ca5257.json | Delete unused import in StdReflParamNameDscoverer | spring-core/src/main/java/org/springframework/core/StandardReflectionParameterNameDiscoverer.java | @@ -20,8 +20,6 @@
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
-import org.springframework.util.ClassUtils;
-
/**
* {@link ParameterNameDiscoverer} implementation which uses JDK 8's
* reflection facilities for introspecting parameter names. | false |
Other | spring-projects | spring-framework | bcfbd862c73db17d7bd8dfe5b669d1a8fc17bcbf.json | Add value() attribute to @Payload | spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/Payload.java | @@ -38,6 +38,16 @@
@Documented
public @interface Payload {
+ /**
+ * A SpEL expression to be evaluated against the payload object as the root context.
+ * This attribute may or may not be supported depending on whether the message being
+ * handled contains a non-primitive Object as its payload or is in serialized form
+ * and requires message conversion.
+ * <p>
+ * When processing STOMP over WebSocket messages this attribute is not supported.
+ */
+ String value() default "";
+
/**
* Whether payload content is required.
* <p> | true |
Other | spring-projects | spring-framework | bcfbd862c73db17d7bd8dfe5b669d1a8fc17bcbf.json | Add value() attribute to @Payload | spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/PayloadArgumentResolver.java | @@ -23,6 +23,7 @@
import org.springframework.messaging.support.converter.MessageConverter;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
+import org.springframework.util.StringUtils;
/**
@@ -69,6 +70,10 @@ public Object resolveArgument(MethodParameter parameter, Message<?> message) thr
}
}
+ if ((annot != null) && StringUtils.hasText(annot.value())) {
+ throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver.");
+ }
+
return this.converter.fromMessage(message, targetClass);
}
| true |
Other | spring-projects | spring-framework | bcfbd862c73db17d7bd8dfe5b669d1a8fc17bcbf.json | Add value() attribute to @Payload | spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/PayloadArgumentResolverTests.java | @@ -41,6 +41,7 @@ public class PayloadArgumentResolverTests {
private MethodParameter param;
private MethodParameter paramNotRequired;
+ private MethodParameter paramWithSpelExpression;
@Before
@@ -50,10 +51,11 @@ public void setup() throws Exception {
this.resolver = new PayloadArgumentResolver(messageConverter );
Method method = PayloadArgumentResolverTests.class.getDeclaredMethod("handleMessage",
- String.class, String.class);
+ String.class, String.class, String.class);
this.param = new MethodParameter(method , 0);
this.paramNotRequired = new MethodParameter(method , 1);
+ this.paramWithSpelExpression = new MethodParameter(method , 2);
}
@@ -75,11 +77,18 @@ public void resolveNotRequired() throws Exception {
assertEquals("ABC", this.resolver.resolveArgument(this.paramNotRequired, notEmptyMessage));
}
+ @Test(expected=IllegalStateException.class)
+ public void resolveSpelExpressionNotSupported() throws Exception {
+ Message<?> message = MessageBuilder.withPayload("ABC".getBytes()).build();
+ this.resolver.resolveArgument(this.paramWithSpelExpression, message);
+ }
+
@SuppressWarnings("unused")
private void handleMessage(
@Payload String param,
- @Payload(required=false) String paramNotRequired) {
+ @Payload(required=false) String paramNotRequired,
+ @Payload("foo.bar") String paramWithSpelExpression) {
}
} | true |
Other | spring-projects | spring-framework | 70dfec269b2ea249b2abf3cf252774a6fd578b39.json | Use alternative UUID strategy in MessageHeaders
This change adds an alternative UUID generation strategy to use by
default in MessageHeaders. Instead of using SecureRandom for each
new UUID, SecureRandom is used only for the initial seed to be
provided java.util.Random. Thereafter the same Random instance is
used instead. This provides improved performance while id's are
still random but less securely so. | spring-messaging/src/main/java/org/springframework/messaging/MessageHeaders.java | @@ -20,6 +20,8 @@
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
+import java.math.BigInteger;
+import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -28,6 +30,7 @@
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.Random;
import java.util.Set;
import java.util.UUID;
@@ -56,6 +59,7 @@
* @author Arjen Poutsma
* @author Mark Fisher
* @author Gary Russell
+ * @author Rossen Stoyanchev
* @since 4.0
* @see org.springframework.messaging.support.MessageBuilder
*/
@@ -65,9 +69,10 @@ public final class MessageHeaders implements Map<String, Object>, Serializable {
private static final Log logger = LogFactory.getLog(MessageHeaders.class);
-
private static volatile IdGenerator idGenerator = null;
+ private static volatile IdGenerator defaultIdGenerator = new AlternativeJdkIdGenerator();
+
/**
* The key for the Message ID. This is an automatically generated UUID and
* should never be explicitly set in the header map <b>except</b> in the
@@ -92,13 +97,8 @@ public final class MessageHeaders implements Map<String, Object>, Serializable {
public MessageHeaders(Map<String, Object> headers) {
this.headers = (headers != null) ? new HashMap<String, Object>(headers) : new HashMap<String, Object>();
- if (MessageHeaders.idGenerator == null){
- this.headers.put(ID, UUID.randomUUID());
- }
- else {
- this.headers.put(ID, MessageHeaders.idGenerator.generateId());
- }
-
+ IdGenerator generatorToUse = (idGenerator != null) ? idGenerator : defaultIdGenerator;
+ this.headers.put(ID, generatorToUse.generateId());
this.headers.put(TIMESTAMP, new Long(System.currentTimeMillis()));
}
@@ -247,4 +247,37 @@ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundE
public static interface IdGenerator {
UUID generateId();
}
+
+ /**
+ * A variation of {@link UUID#randomUUID()} that uses {@link SecureRandom} only for
+ * the initial seed and {@link Random} thereafter, which provides better performance
+ * in exchange for less securely random id's.
+ */
+ public static class AlternativeJdkIdGenerator implements IdGenerator {
+
+ private final Random random;
+
+ public AlternativeJdkIdGenerator() {
+ byte[] seed = new SecureRandom().generateSeed(8);
+ this.random = new Random(new BigInteger(seed).longValue());
+ }
+
+ public UUID generateId() {
+
+ byte[] randomBytes = new byte[16];
+ this.random.nextBytes(randomBytes);
+
+ long mostSigBits = 0;
+ for (int i = 0; i < 8; i++) {
+ mostSigBits = (mostSigBits << 8) | (randomBytes[i] & 0xff);
+ }
+ long leastSigBits = 0;
+ for (int i = 8; i < 16; i++) {
+ leastSigBits = (leastSigBits << 8) | (randomBytes[i] & 0xff);
+ }
+
+ return new UUID(mostSigBits, leastSigBits);
+ }
+ }
+
} | true |
Other | spring-projects | spring-framework | 70dfec269b2ea249b2abf3cf252774a6fd578b39.json | Use alternative UUID strategy in MessageHeaders
This change adds an alternative UUID generation strategy to use by
default in MessageHeaders. Instead of using SecureRandom for each
new UUID, SecureRandom is used only for the initial seed to be
provided java.util.Random. Thereafter the same Random instance is
used instead. This provides improved performance while id's are
still random but less securely so. | spring-messaging/src/test/java/org/springframework/messaging/MessageHeadersTests.java | @@ -0,0 +1,154 @@
+/*
+ * Copyright 2002-2013 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.messaging;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * Test fixture for {@link MessageHeaders}.
+ *
+ * @author Rossen Stoyanchev
+ */
+public class MessageHeadersTests {
+
+
+ @Test
+ public void testTimestamp() {
+ MessageHeaders headers = new MessageHeaders(null);
+ assertNotNull(headers.getTimestamp());
+ }
+
+ @Test
+ public void testTimestampOverwritten() throws Exception {
+ MessageHeaders headers1 = new MessageHeaders(null);
+ Thread.sleep(50L);
+ MessageHeaders headers2 = new MessageHeaders(headers1);
+ assertNotSame(headers1.getTimestamp(), headers2.getTimestamp());
+ }
+
+ @Test
+ public void testIdOverwritten() throws Exception {
+ MessageHeaders headers1 = new MessageHeaders(null);
+ MessageHeaders headers2 = new MessageHeaders(headers1);
+ assertNotSame(headers1.getId(), headers2.getId());
+ }
+
+ @Test
+ public void testId() {
+ MessageHeaders headers = new MessageHeaders(null);
+ assertNotNull(headers.getId());
+ }
+
+ @Test
+ public void testNonTypedAccessOfHeaderValue() {
+ Integer value = new Integer(123);
+ Map<String, Object> map = new HashMap<String, Object>();
+ map.put("test", value);
+ MessageHeaders headers = new MessageHeaders(map);
+ assertEquals(value, headers.get("test"));
+ }
+
+ @Test
+ public void testTypedAccessOfHeaderValue() {
+ Integer value = new Integer(123);
+ Map<String, Object> map = new HashMap<String, Object>();
+ map.put("test", value);
+ MessageHeaders headers = new MessageHeaders(map);
+ assertEquals(value, headers.get("test", Integer.class));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testHeaderValueAccessWithIncorrectType() {
+ Integer value = new Integer(123);
+ Map<String, Object> map = new HashMap<String, Object>();
+ map.put("test", value);
+ MessageHeaders headers = new MessageHeaders(map);
+ assertEquals(value, headers.get("test", String.class));
+ }
+
+ @Test
+ public void testNullHeaderValue() {
+ Map<String, Object> map = new HashMap<String, Object>();
+ MessageHeaders headers = new MessageHeaders(map);
+ assertNull(headers.get("nosuchattribute"));
+ }
+
+ @Test
+ public void testNullHeaderValueWithTypedAccess() {
+ Map<String, Object> map = new HashMap<String, Object>();
+ MessageHeaders headers = new MessageHeaders(map);
+ assertNull(headers.get("nosuchattribute", String.class));
+ }
+
+ @Test
+ public void testHeaderKeys() {
+ Map<String, Object> map = new HashMap<String, Object>();
+ map.put("key1", "val1");
+ map.put("key2", new Integer(123));
+ MessageHeaders headers = new MessageHeaders(map);
+ Set<String> keys = headers.keySet();
+ assertTrue(keys.contains("key1"));
+ assertTrue(keys.contains("key2"));
+ }
+
+ @Test
+ public void serializeWithAllSerializableHeaders() throws Exception {
+ Map<String, Object> map = new HashMap<String, Object>();
+ map.put("name", "joe");
+ map.put("age", 42);
+ MessageHeaders input = new MessageHeaders(map);
+ MessageHeaders output = (MessageHeaders) serializeAndDeserialize(input);
+ assertEquals("joe", output.get("name"));
+ assertEquals(42, output.get("age"));
+ }
+
+ @Test
+ public void serializeWithNonSerializableHeader() throws Exception {
+ Object address = new Object();
+ Map<String, Object> map = new HashMap<String, Object>();
+ map.put("name", "joe");
+ map.put("address", address);
+ MessageHeaders input = new MessageHeaders(map);
+ MessageHeaders output = (MessageHeaders) serializeAndDeserialize(input);
+ assertEquals("joe", output.get("name"));
+ assertNull(output.get("address"));
+ }
+
+
+ private static Object serializeAndDeserialize(Object object) throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream out = new ObjectOutputStream(baos);
+ out.writeObject(object);
+ out.close();
+ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
+ ObjectInputStream in = new ObjectInputStream(bais);
+ Object result = in.readObject();
+ in.close();
+ return result;
+ }
+
+} | true |
Other | spring-projects | spring-framework | 7c3749769a8d136eee5e3b01e156b9a5eac3ec49.json | Add STOMP broker relay to configure "host" header
Issue: SPR-10955 | spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java | @@ -47,9 +47,24 @@
/**
- * A {@link MessageHandler} that handles messages by forwarding them to a STOMP broker and
- * reversely sends any returned messages from the broker to the provided
- * {@link MessageChannel}.
+ * A {@link MessageHandler} that handles messages by forwarding them to a STOMP broker.
+ * For each new {@link SimpMessageType#CONNECT CONNECT} message, an independent TCP
+ * connection to the broker is opened and used exclusively for all messages from the
+ * client that originated the CONNECT message. Messages from the same client are
+ * identified through the session id message header. Reversely, when the STOMP broker
+ * sends messages back on the TCP connection, those messages are enriched with the session
+ * id of the client and sent back downstream through the {@link MessageChannel} provided
+ * to the constructor.
+ * <p>
+ * This class also automatically opens a default "system" TCP connection to the message
+ * broker that is used for sending messages that originate from the server application (as
+ * opposed to from a client). Such messages are recognized because they are not associated
+ * with any client and therefore do not have a session id header. The "system" connection
+ * is effectively shared and cannot be used to receive messages. Several properties are
+ * provided to configure the "system" session including the the
+ * {@link #setSystemLogin(String) login} {@link #setSystemPasscode(String) passcode},
+ * heartbeat {@link #setSystemHeartbeatSendInterval(long) send} and
+ * {@link #setSystemHeartbeatReceiveInterval(long) receive} intervals.
*
* @author Rossen Stoyanchev
* @author Andy Wilkinson
@@ -71,6 +86,8 @@ public class StompBrokerRelayMessageHandler extends AbstractBrokerMessageHandler
private long systemHeartbeatReceiveInterval = 10000;
+ private String virtualHost;
+
private Environment environment;
private TcpClient<Message<byte[]>, Message<byte[]>> tcpClient;
@@ -120,11 +137,13 @@ public int getRelayPort() {
}
/**
- * Set the interval, in milliseconds, at which the "system" relay session will,
- * in the absence of any other data being sent, send a heartbeat to the STOMP broker.
- * A value of zero will prevent heartbeats from being sent to the broker.
+ * Set the interval, in milliseconds, at which the "system" relay session will, in the
+ * absence of any other data being sent, send a heartbeat to the STOMP broker. A value
+ * of zero will prevent heartbeats from being sent to the broker.
* <p>
* The default value is 10000.
+ * <p>
+ * See class-level documentation for more information on the "system" session.
*/
public void setSystemHeartbeatSendInterval(long systemHeartbeatSendInterval) {
this.systemHeartbeatSendInterval = systemHeartbeatSendInterval;
@@ -145,6 +164,8 @@ public long getSystemHeartbeatSendInterval() {
* heartbeats from the broker.
* <p>
* The default value is 10000.
+ * <p>
+ * See class-level documentation for more information on the "system" session.
*/
public void setSystemHeartbeatReceiveInterval(long heartbeatReceiveInterval) {
this.systemHeartbeatReceiveInterval = heartbeatReceiveInterval;
@@ -161,6 +182,8 @@ public long getSystemHeartbeatReceiveInterval() {
/**
* Set the login for the "system" relay session used to send messages to the STOMP
* broker without having a client session (e.g. REST/HTTP request handling method).
+ * <p>
+ * See class-level documentation for more information on the "system" session.
*/
public void setSystemLogin(String systemLogin) {
Assert.hasText(systemLogin, "systemLogin must not be empty");
@@ -177,6 +200,8 @@ public String getSystemLogin() {
/**
* Set the passcode for the "system" relay session used to send messages to the STOMP
* broker without having a client session (e.g. REST/HTTP request handling method).
+ * <p>
+ * See class-level documentation for more information on the "system" session.
*/
public void setSystemPasscode(String systemPasscode) {
this.systemPasscode = systemPasscode;
@@ -189,6 +214,26 @@ public String getSystemPasscode() {
return this.systemPasscode;
}
+ /**
+ * Set the value of the "host" header to use in STOMP CONNECT frames. When this
+ * property is configured, a "host" header will be added to every STOMP frame sent to
+ * the STOMP broker. This may be useful for example in a cloud environment where the
+ * actual host to which the TCP connection is established is different from the host
+ * providing the cloud-based STOMP service.
+ * <p>
+ * By default this property is not set.
+ */
+ public void setVirtualHost(String virtualHost) {
+ this.virtualHost = virtualHost;
+ }
+
+ /**
+ * @return the configured virtual host value.
+ */
+ public String getVirtualHost() {
+ return this.virtualHost;
+ }
+
@Override
protected void startInternal() {
@@ -252,7 +297,10 @@ protected void handleMessageInternal(Message<?> message) {
}
if (SimpMessageType.CONNECT.equals(messageType)) {
- message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
+ if (getVirtualHost() != null) {
+ headers.setHost(getVirtualHost());
+ message = MessageBuilder.withPayload(message.getPayload()).setHeaders(headers).build();
+ }
StompRelaySession session = new StompRelaySession(sessionId);
this.relaySessions.put(sessionId, session);
session.connect(message);
@@ -516,6 +564,9 @@ public void connect() {
headers.setLogin(systemLogin);
headers.setPasscode(systemPasscode);
headers.setHeartbeat(systemHeartbeatSendInterval, systemHeartbeatReceiveInterval);
+ if (getVirtualHost() != null) {
+ headers.setHost(getVirtualHost());
+ }
Message<?> connectMessage = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
super.connect(connectMessage);
} | true |
Other | spring-projects | spring-framework | 7c3749769a8d136eee5e3b01e156b9a5eac3ec49.json | Add STOMP broker relay to configure "host" header
Issue: SPR-10955 | spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java | @@ -113,6 +113,8 @@ public void tearDown() throws Exception {
}
}
+ // test "host" header (virtualHost property) when TCP client is behind interface and configurable
+
@Test
public void publishSubscribe() throws Exception {
| true |
Other | spring-projects | spring-framework | cf7889e226519bec62345affa7c401b0abbebecc.json | Fix issue with DeferredResult on @RestController
Before this change, async result handling on controller methods failed
to observe type-level annotations annotations. The issue was never
noticed until we started supporting type-level @ResponseBody and the
@RestController meta annotation.
Issue: SPR-10905 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethod.java | @@ -174,9 +174,10 @@ private String getReturnValueHandlingErrorMessage(String message, Object returnV
}
/**
- * Return a ServletInvocableHandlerMethod that will process the value returned
- * from an async operation essentially either applying return value handling or
- * raising an exception if the end result is an Exception.
+ * Create a ServletInvocableHandlerMethod that will return the given value from an
+ * async operation instead of invoking the controller method again. The async result
+ * value is then either processed as if the controller method returned it or an
+ * exception is raised if the async result value itself is an Exception.
*/
ServletInvocableHandlerMethod wrapConcurrentResult(final Object result) {
@@ -197,9 +198,12 @@ else if (result instanceof Throwable) {
/**
- * A ServletInvocableHandlerMethod sub-class that invokes a given
- * {@link Callable} and "inherits" the annotations of the containing class
- * instance, useful for invoking a Callable returned from a HandlerMethod.
+ * A sub-class of {@link HandlerMethod} that invokes the given {@link Callable}
+ * instead of the target controller method. This is useful for resuming processing
+ * with the result of an async operation. The goal is to process the value returned
+ * from the Callable as if it was returned by the target controller method, i.e.
+ * taking into consideration both method and type-level controller annotations (e.g.
+ * {@code @ResponseBody}, {@code @ResponseStatus}, etc).
*/
private class CallableHandlerMethod extends ServletInvocableHandlerMethod {
@@ -208,6 +212,17 @@ public CallableHandlerMethod(Callable<?> callable) {
this.setHandlerMethodReturnValueHandlers(ServletInvocableHandlerMethod.this.returnValueHandlers);
}
+ /**
+ * Bridge to type-level annotations of the target controller method.
+ */
+ @Override
+ public Class<?> getBeanType() {
+ return ServletInvocableHandlerMethod.this.getBeanType();
+ }
+
+ /**
+ * Bridge to method-level annotations of the target controller method.
+ */
@Override
public <A extends Annotation> A getMethodAnnotation(Class<A> annotationType) {
return ServletInvocableHandlerMethod.this.getMethodAnnotation(annotationType); | true |
Other | spring-projects | spring-framework | cf7889e226519bec62345affa7c401b0abbebecc.json | Fix issue with DeferredResult on @RestController
Before this change, async result handling on controller methods failed
to observe type-level annotations annotations. The issue was never
noticed until we started supporting type-level @ResponseBody and the
@RestController meta annotation.
Issue: SPR-10905 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletInvocableHandlerMethodTests.java | @@ -15,33 +15,37 @@
*/
package org.springframework.web.servlet.mvc.method.annotation;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
+import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockHttpServletResponse;
import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
+import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.method.annotation.RequestParamMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.view.RedirectView;
+import static org.junit.Assert.*;
+
/**
* Test fixture with {@link ServletInvocableHandlerMethod}.
*
@@ -73,7 +77,7 @@ public void setUp() throws Exception {
@Test
public void invokeAndHandle_VoidWithResponseStatus() throws Exception {
- ServletInvocableHandlerMethod handlerMethod = getHandlerMethod("responseStatus");
+ ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "responseStatus");
handlerMethod.invokeAndHandle(webRequest, mavContainer);
assertTrue("Null return value + @ResponseStatus should result in 'request handled'",
@@ -85,7 +89,7 @@ public void invokeAndHandle_VoidWithResponseStatus() throws Exception {
public void invokeAndHandle_VoidWithHttpServletResponseArgument() throws Exception {
argumentResolvers.addResolver(new ServletResponseMethodArgumentResolver());
- ServletInvocableHandlerMethod handlerMethod = getHandlerMethod("httpServletResponse", HttpServletResponse.class);
+ ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "httpServletResponse", HttpServletResponse.class);
handlerMethod.invokeAndHandle(webRequest, mavContainer);
assertTrue("Null return value + HttpServletResponse arg should result in 'request handled'",
@@ -98,7 +102,7 @@ public void invokeAndHandle_VoidRequestNotModified() throws Exception {
int lastModifiedTimestamp = 1000 * 1000;
webRequest.checkNotModified(lastModifiedTimestamp);
- ServletInvocableHandlerMethod handlerMethod = getHandlerMethod("notModified");
+ ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "notModified");
handlerMethod.invokeAndHandle(webRequest, mavContainer);
assertTrue("Null return value + 'not modified' request should result in 'request handled'",
@@ -109,7 +113,7 @@ public void invokeAndHandle_VoidRequestNotModified() throws Exception {
@Test
public void invokeAndHandle_NotVoidWithResponseStatusAndReason() throws Exception {
- ServletInvocableHandlerMethod handlerMethod = getHandlerMethod("responseStatusWithReason");
+ ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "responseStatusWithReason");
handlerMethod.invokeAndHandle(webRequest, mavContainer);
assertTrue("When a phrase is used, the response should not be used any more", mavContainer.isRequestHandled());
@@ -121,7 +125,7 @@ public void invokeAndHandle_NotVoidWithResponseStatusAndReason() throws Exceptio
public void invokeAndHandle_Exception() throws Exception {
returnValueHandlers.addHandler(new ExceptionRaisingReturnValueHandler());
- ServletInvocableHandlerMethod handlerMethod = getHandlerMethod("handle");
+ ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "handle");
handlerMethod.invokeAndHandle(webRequest, mavContainer);
fail("Expected exception");
}
@@ -133,7 +137,7 @@ public void invokeAndHandle_DynamicReturnValue() throws Exception {
returnValueHandlers.addHandler(new ViewNameMethodReturnValueHandler());
// Invoke without a request parameter (String return value)
- ServletInvocableHandlerMethod handlerMethod = getHandlerMethod("dynamicReturnValue", String.class);
+ ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new Handler(), "dynamicReturnValue", String.class);
handlerMethod.invokeAndHandle(webRequest, mavContainer);
assertNotNull(mavContainer.getView());
@@ -146,11 +150,45 @@ public void invokeAndHandle_DynamicReturnValue() throws Exception {
assertEquals("view", mavContainer.getViewName());
}
+ @Test
+ public void wrapConcurrentResult_MethodLevelResponseBody() throws Exception {
+ wrapConcurrentResult_ResponseBody(new MethodLevelResponseBodyHandler());
+ }
+
+ @Test
+ public void wrapConcurrentResult_TypeLevelResponseBody() throws Exception {
+ wrapConcurrentResult_ResponseBody(new TypeLevelResponseBodyHandler());
+ }
+
+ private void wrapConcurrentResult_ResponseBody(Object handler) throws Exception {
+ List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
+ converters.add(new StringHttpMessageConverter());
+ returnValueHandlers.addHandler(new RequestResponseBodyMethodProcessor(converters));
+ ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(handler, "handle");
+ handlerMethod = handlerMethod.wrapConcurrentResult("bar");
+ handlerMethod.invokeAndHandle(webRequest, mavContainer);
+
+ assertEquals("bar", response.getContentAsString());
+ }
+
+ @Test
+ public void wrapConcurrentResult_ResponseEntity() throws Exception {
+ List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
+ converters.add(new StringHttpMessageConverter());
+ returnValueHandlers.addHandler(new HttpEntityMethodProcessor(converters));
+ ServletInvocableHandlerMethod handlerMethod = getHandlerMethod(new ResponseEntityHandler(), "handle");
+ handlerMethod = handlerMethod.wrapConcurrentResult(new ResponseEntity<>("bar", HttpStatus.OK));
+ handlerMethod.invokeAndHandle(webRequest, mavContainer);
+
+ assertEquals("bar", response.getContentAsString());
+ }
- private ServletInvocableHandlerMethod getHandlerMethod(String methodName, Class<?>... argTypes)
- throws NoSuchMethodException {
- Method method = Handler.class.getDeclaredMethod(methodName, argTypes);
- ServletInvocableHandlerMethod handlerMethod = new ServletInvocableHandlerMethod(new Handler(), method);
+
+ private ServletInvocableHandlerMethod getHandlerMethod(Object controller,
+ String methodName, Class<?>... argTypes) throws NoSuchMethodException {
+
+ Method method = controller.getClass().getDeclaredMethod(methodName, argTypes);
+ ServletInvocableHandlerMethod handlerMethod = new ServletInvocableHandlerMethod(controller, method);
handlerMethod.setHandlerMethodArgumentResolvers(argumentResolvers);
handlerMethod.setHandlerMethodReturnValueHandlers(returnValueHandlers);
return handlerMethod;
@@ -183,6 +221,31 @@ public Object dynamicReturnValue(@RequestParam(required=false) String param) {
}
}
+ private static class MethodLevelResponseBodyHandler {
+
+ @ResponseBody
+ public DeferredResult<String> handle() {
+ return new DeferredResult<>();
+ }
+ }
+
+ @ResponseBody
+ private static class TypeLevelResponseBodyHandler {
+
+ @SuppressWarnings("unused")
+ public DeferredResult<String> handle() {
+ return new DeferredResult<String>();
+ }
+ }
+
+ private static class ResponseEntityHandler {
+
+ public DeferredResult<ResponseEntity<String>> handle() {
+ return new DeferredResult<>();
+ }
+ }
+
+
private static class ExceptionRaisingReturnValueHandler implements HandlerMethodReturnValueHandler {
@Override | true |
Other | spring-projects | spring-framework | 74794190a53a096cc1eca99202e5e9f9a70f0503.json | Implement java.io.Flushable wherever applicable | spring-tx/src/main/java/org/springframework/transaction/TransactionStatus.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2013 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.
@@ -16,6 +16,8 @@
package org.springframework.transaction;
+import java.io.Flushable;
+
/**
* Representation of the status of a transaction.
*
@@ -34,7 +36,7 @@
* @see org.springframework.transaction.support.TransactionCallback#doInTransaction
* @see org.springframework.transaction.interceptor.TransactionInterceptor#currentTransactionStatus()
*/
-public interface TransactionStatus extends SavepointManager {
+public interface TransactionStatus extends SavepointManager, Flushable {
/**
* Return whether the present transaction is new (else participating
@@ -79,6 +81,7 @@ public interface TransactionStatus extends SavepointManager {
* Flush the underlying session to the datastore, if applicable:
* for example, all affected Hibernate/JPA sessions.
*/
+ @Override
void flush();
/** | true |
Other | spring-projects | spring-framework | 74794190a53a096cc1eca99202e5e9f9a70f0503.json | Implement java.io.Flushable wherever applicable | spring-tx/src/main/java/org/springframework/transaction/support/SmartTransactionObject.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2013 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.
@@ -16,6 +16,8 @@
package org.springframework.transaction.support;
+import java.io.Flushable;
+
/**
* Interface to be implemented by transaction objects that are able to
* return an internal rollback-only marker, typically from a another
@@ -29,7 +31,7 @@
* @since 1.1
* @see DefaultTransactionStatus#isRollbackOnly
*/
-public interface SmartTransactionObject {
+public interface SmartTransactionObject extends Flushable {
/**
* Return whether the transaction is internally marked as rollback-only.
@@ -43,6 +45,7 @@ public interface SmartTransactionObject {
* Flush the underlying sessions to the datastore, if applicable:
* for example, all affected Hibernate/JPA sessions.
*/
+ @Override
void flush();
} | true |
Other | spring-projects | spring-framework | 74794190a53a096cc1eca99202e5e9f9a70f0503.json | Implement java.io.Flushable wherever applicable | spring-tx/src/main/java/org/springframework/transaction/support/TransactionSynchronization.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 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.
@@ -16,6 +16,8 @@
package org.springframework.transaction.support;
+import java.io.Flushable;
+
/**
* Interface for transaction synchronization callbacks.
* Supported by AbstractPlatformTransactionManager.
@@ -34,7 +36,7 @@
* @see org.springframework.jdbc.datasource.DataSourceUtils#CONNECTION_SYNCHRONIZATION_ORDER
* @see org.springframework.orm.hibernate3.SessionFactoryUtils#SESSION_SYNCHRONIZATION_ORDER
*/
-public interface TransactionSynchronization {
+public interface TransactionSynchronization extends Flushable {
/** Completion status in case of proper commit */
int STATUS_COMMITTED = 0;
@@ -65,6 +67,7 @@ public interface TransactionSynchronization {
* for example, a Hibernate/JPA session.
* @see org.springframework.transaction.TransactionStatus#flush()
*/
+ @Override
void flush();
/** | true |
Other | spring-projects | spring-framework | 74794190a53a096cc1eca99202e5e9f9a70f0503.json | Implement java.io.Flushable wherever applicable | spring-web/src/main/java/org/springframework/http/server/ServerHttpResponse.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 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,6 +17,7 @@
package org.springframework.http.server;
import java.io.Closeable;
+import java.io.Flushable;
import java.io.IOException;
import org.springframework.http.HttpOutputMessage;
@@ -28,7 +29,7 @@
* @author Arjen Poutsma
* @since 3.0
*/
-public interface ServerHttpResponse extends HttpOutputMessage, Closeable {
+public interface ServerHttpResponse extends HttpOutputMessage, Flushable, Closeable {
/**
* Set the HTTP status code of the response.
@@ -37,10 +38,11 @@ public interface ServerHttpResponse extends HttpOutputMessage, Closeable {
void setStatusCode(HttpStatus status);
/**
- * Ensure the headers and the content of the response are written out. After the first
- * flush, headers can no longer be changed, only further content writing and flushing
- * is possible.
+ * Ensure that the headers and the content of the response are written out.
+ * <p>After the first flush, headers can no longer be changed.
+ * Only further content writing and content flushing is possible.
*/
+ @Override
void flush() throws IOException;
/** | true |
Other | spring-projects | spring-framework | 7823c5d6ea6d0074f27f765066ba51daf990074d.json | Upgrade reactor to M1 | build.gradle | @@ -322,15 +322,15 @@ project("spring-messaging") {
compile(project(":spring-context"))
optional(project(":spring-websocket"))
optional("com.fasterxml.jackson.core:jackson-databind:2.2.0")
- optional("org.projectreactor:reactor-core:1.0.0.BUILD-SNAPSHOT")
- optional("org.projectreactor:reactor-tcp:1.0.0.BUILD-SNAPSHOT")
+ optional("org.projectreactor:reactor-core:1.0.0.M1")
+ optional("org.projectreactor:reactor-tcp:1.0.0.M1")
optional("com.lmax:disruptor:3.1.1")
testCompile("commons-dbcp:commons-dbcp:1.2.2")
testCompile("javax.inject:javax.inject-tck:1")
}
repositories {
- maven { url 'http://repo.springsource.org/snapshot' } // reactor
+ maven { url 'http://repo.springsource.org/libs-milestone' } // reactor
}
}
| false |
Other | spring-projects | spring-framework | 55dae74f156c1c8326e182e5f1eb7a162cba56a8.json | Add ReplyTo annotation | spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/ReplyTo.java | @@ -14,34 +14,28 @@
* limitations under the License.
*/
-package org.springframework.messaging.simp;
+package org.springframework.messaging.handler.annotation;
-import org.springframework.core.NamedThreadLocal;
-import org.springframework.messaging.Message;
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
-// TODO: remove?
-
/**
* @author Rossen Stoyanchev
* @since 4.0
*/
-public class MessageHolder {
-
- private static final NamedThreadLocal<Message<?>> messageHolder =
- new NamedThreadLocal<Message<?>>("Current message");
-
-
- public static void setMessage(Message<?> message) {
- messageHolder.set(message);
- }
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.RUNTIME)
+@Documented
+public @interface ReplyTo {
- public static Message<?> getMessage() {
- return messageHolder.get();
- }
- public static void reset() {
- messageHolder.remove();
- }
+ /**
+ * The destination value for the reply.
+ */
+ String value();
} | true |
Other | spring-projects | spring-framework | 55dae74f156c1c8326e182e5f1eb7a162cba56a8.json | Add ReplyTo annotation | spring-messaging/src/main/java/org/springframework/messaging/handler/method/MissingSessionUserException.java | @@ -16,7 +16,6 @@
package org.springframework.messaging.handler.method;
-import org.springframework.core.MethodParameter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
@@ -26,29 +25,13 @@
* @author Rossen Stoyanchev
* @since 4.0
*/
-public class InvalidMessageMethodParameterException extends MessagingException {
+public class MissingSessionUserException extends MessagingException {
private static final long serialVersionUID = -6905878930083523161L;
- private final MethodParameter parameter;
-
- public InvalidMessageMethodParameterException(Message<?> message, String description,
- MethodParameter parameter, Throwable cause) {
- super(message, description, cause);
- this.parameter = parameter;
- }
-
- public InvalidMessageMethodParameterException(Message<?> message, String description,
- MethodParameter parameter) {
-
- super(message, description);
- this.parameter = parameter;
- }
-
-
- public MethodParameter getParameter() {
- return this.parameter;
+ public MissingSessionUserException(Message<?> message) {
+ super(message, "No \"user\" header in message");
}
} | true |
Other | spring-projects | spring-framework | 55dae74f156c1c8326e182e5f1eb7a162cba56a8.json | Add ReplyTo annotation | spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/DefaultMessageReturnValueHandler.java | @@ -16,30 +16,47 @@
package org.springframework.messaging.simp.annotation.support;
+import java.security.Principal;
+
import org.springframework.core.MethodParameter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
+import org.springframework.messaging.handler.annotation.ReplyTo;
import org.springframework.messaging.handler.method.MessageReturnValueHandler;
+import org.springframework.messaging.handler.method.MissingSessionUserException;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.messaging.support.converter.MessageConverter;
import org.springframework.util.Assert;
/**
+ * Expects return values to be either a {@link Message} or the payload of a message to be
+ * converted and sent on a {@link MessageChannel}.
+ *
+ * <p>This {@link MessageReturnValueHandler} should be ordered last as it supports all
+ * return value types.
+ *
* @author Rossen Stoyanchev
* @since 4.0
*/
-public class MessageSendingReturnValueHandler implements MessageReturnValueHandler {
+public class DefaultMessageReturnValueHandler implements MessageReturnValueHandler {
+
+ private MessageChannel inboundChannel;
private MessageChannel outboundChannel;
private final MessageConverter converter;
- public MessageSendingReturnValueHandler(MessageChannel outboundChannel, MessageConverter<?> converter) {
+ public DefaultMessageReturnValueHandler(MessageChannel inboundChannel, MessageChannel outboundChannel,
+ MessageConverter<?> converter) {
+
+ Assert.notNull(inboundChannel, "inboundChannel is required");
Assert.notNull(outboundChannel, "outboundChannel is required");
Assert.notNull(converter, "converter is required");
+
+ this.inboundChannel = inboundChannel;
this.outboundChannel = outboundChannel;
this.converter = converter;
}
@@ -60,6 +77,7 @@ public void handleReturnValue(Object returnValue, MethodParameter returnType, Me
}
SimpMessageHeaderAccessor inputHeaders = SimpMessageHeaderAccessor.wrap(message);
+
Message<?> returnMessage = (returnValue instanceof Message) ? (Message<?>) returnValue : null;
Object returnPayload = (returnMessage != null) ? returnMessage.getPayload() : returnValue;
@@ -68,14 +86,43 @@ public void handleReturnValue(Object returnValue, MethodParameter returnType, Me
returnHeaders.setSessionId(inputHeaders.getSessionId());
returnHeaders.setSubscriptionId(inputHeaders.getSubscriptionId());
- if (returnHeaders.getDestination() == null) {
- returnHeaders.setDestination(inputHeaders.getDestination());
- }
+
+ String destination = getDestination(message, returnType, inputHeaders, returnHeaders);
+ returnHeaders.setDestination(destination);
returnMessage = this.converter.toMessage(returnPayload);
returnMessage = MessageBuilder.fromMessage(returnMessage).copyHeaders(returnHeaders.toMap()).build();
- this.outboundChannel.send(returnMessage);
+ if (destination.startsWith("/user/")) {
+ this.inboundChannel.send(returnMessage);
+ }
+ else {
+ this.outboundChannel.send(returnMessage);
+ }
}
+ protected String getDestination(Message<?> inputMessage, MethodParameter returnType,
+ SimpMessageHeaderAccessor inputHeaders, SimpMessageHeaderAccessor returnHeaders) {
+
+ ReplyTo annot = returnType.getMethodAnnotation(ReplyTo.class);
+
+ if (returnHeaders.getDestination() != null) {
+ return returnHeaders.getDestination();
+ }
+ else if (annot != null) {
+ Principal user = inputHeaders.getUser();
+ if (user == null) {
+ throw new MissingSessionUserException(inputMessage);
+ }
+ return "/user/" + user.getName() + annot.value();
+ }
+ else if (inputHeaders.getDestination() != null) {
+ return inputHeaders.getDestination();
+ }
+ else {
+ return null;
+ }
+
+ }
+
} | true |
Other | spring-projects | spring-framework | 55dae74f156c1c8326e182e5f1eb7a162cba56a8.json | Add ReplyTo annotation | spring-messaging/src/main/java/org/springframework/messaging/simp/annotation/support/PrincipalMessageArgumentResolver.java | @@ -20,8 +20,8 @@
import org.springframework.core.MethodParameter;
import org.springframework.messaging.Message;
-import org.springframework.messaging.handler.method.InvalidMessageMethodParameterException;
import org.springframework.messaging.handler.method.MessageArgumentResolver;
+import org.springframework.messaging.handler.method.MissingSessionUserException;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
@@ -43,7 +43,7 @@ public Object resolveArgument(MethodParameter parameter, Message<?> message) thr
SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
Principal user = headers.getUser();
if (user == null) {
- throw new InvalidMessageMethodParameterException(message, "User not available", parameter);
+ throw new MissingSessionUserException(message);
}
return user;
} | true |
Other | spring-projects | spring-framework | 55dae74f156c1c8326e182e5f1eb7a162cba56a8.json | Add ReplyTo annotation | spring-messaging/src/main/java/org/springframework/messaging/simp/handler/AnnotationMethodMessageHandler.java | @@ -43,12 +43,11 @@
import org.springframework.messaging.handler.method.InvocableMessageHandlerMethod;
import org.springframework.messaging.handler.method.MessageArgumentResolverComposite;
import org.springframework.messaging.handler.method.MessageReturnValueHandlerComposite;
-import org.springframework.messaging.simp.MessageHolder;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.annotation.SubscribeEvent;
import org.springframework.messaging.simp.annotation.UnsubscribeEvent;
-import org.springframework.messaging.simp.annotation.support.MessageSendingReturnValueHandler;
+import org.springframework.messaging.simp.annotation.support.DefaultMessageReturnValueHandler;
import org.springframework.messaging.simp.annotation.support.PrincipalMessageArgumentResolver;
import org.springframework.messaging.support.converter.MessageConverter;
import org.springframework.stereotype.Controller;
@@ -67,6 +66,8 @@ public class AnnotationMethodMessageHandler implements MessageHandler, Applicati
private static final Log logger = LogFactory.getLog(AnnotationMethodMessageHandler.class);
+ private final MessageChannel inboundChannel;
+
private final MessageChannel outboundChannel;
private MessageConverter<?> messageConverter;
@@ -91,8 +92,10 @@ public class AnnotationMethodMessageHandler implements MessageHandler, Applicati
* @param inboundChannel a channel for processing incoming messages from clients
* @param outboundChannel a channel for messages going out to clients
*/
- public AnnotationMethodMessageHandler(MessageChannel outboundChannel) {
+ public AnnotationMethodMessageHandler(MessageChannel inboundChannel, MessageChannel outboundChannel) {
+ Assert.notNull(inboundChannel, "inboundChannel is required");
Assert.notNull(outboundChannel, "outboundChannel is required");
+ this.inboundChannel = inboundChannel;
this.outboundChannel = outboundChannel;
}
@@ -116,8 +119,8 @@ public void afterPropertiesSet() {
this.argumentResolvers.addResolver(new PrincipalMessageArgumentResolver());
this.argumentResolvers.addResolver(new MessageBodyArgumentResolver(this.messageConverter));
- this.returnValueHandlers.addHandler(
- new MessageSendingReturnValueHandler(this.outboundChannel, this.messageConverter));
+ this.returnValueHandlers.addHandler(new DefaultMessageReturnValueHandler(
+ this.inboundChannel, this.outboundChannel, this.messageConverter));
}
protected void initHandlerMethods() {
@@ -215,16 +218,13 @@ private void handleMessageInternal(final Message<?> message, Map<MappingInfo, Ha
invocableHandlerMethod.setMessageMethodArgumentResolvers(this.argumentResolvers);
try {
- MessageHolder.setMessage(message);
-
- Object value = invocableHandlerMethod.invoke(message);
+ Object returnValue = invocableHandlerMethod.invoke(message);
MethodParameter returnType = handlerMethod.getReturnType();
if (void.class.equals(returnType.getParameterType())) {
return;
}
-
- this.returnValueHandlers.handleReturnValue(value, returnType, message);
+ this.returnValueHandlers.handleReturnValue(returnValue, returnType, message);
}
catch (Exception ex) {
invokeExceptionHandler(message, handlerMethod, ex);
@@ -233,14 +233,11 @@ private void handleMessageInternal(final Message<?> message, Map<MappingInfo, Ha
// TODO
ex.printStackTrace();
}
- finally {
- MessageHolder.reset();
- }
}
private void invokeExceptionHandler(Message<?> message, HandlerMethod handlerMethod, Exception ex) {
- InvocableMessageHandlerMethod invocableHandlerMethod;
+ InvocableMessageHandlerMethod exceptionHandlerMethod;
Class<?> beanType = handlerMethod.getBeanType();
MessageExceptionHandlerMethodResolver resolver = this.exceptionHandlerCache.get(beanType);
if (resolver == null) {
@@ -254,11 +251,17 @@ private void invokeExceptionHandler(Message<?> message, HandlerMethod handlerMet
return;
}
- invocableHandlerMethod = new InvocableMessageHandlerMethod(handlerMethod.getBean(), method);
- invocableHandlerMethod.setMessageMethodArgumentResolvers(this.argumentResolvers);
+ exceptionHandlerMethod = new InvocableMessageHandlerMethod(handlerMethod.getBean(), method);
+ exceptionHandlerMethod.setMessageMethodArgumentResolvers(this.argumentResolvers);
try {
- invocableHandlerMethod.invoke(message, ex);
+ Object returnValue = exceptionHandlerMethod.invoke(message, ex);
+
+ MethodParameter returnType = exceptionHandlerMethod.getReturnType();
+ if (void.class.equals(returnType.getParameterType())) {
+ return;
+ }
+ this.returnValueHandlers.handleReturnValue(returnValue, returnType, message);
}
catch (Throwable t) {
logger.error("Error while handling exception", t); | true |
Other | spring-projects | spring-framework | 55dae74f156c1c8326e182e5f1eb7a162cba56a8.json | Add ReplyTo annotation | spring-messaging/src/main/java/org/springframework/messaging/simp/handler/SimpleUserSessionResolver.java | @@ -27,7 +27,7 @@
* @author Rossen Stoyanchev
* @since 4.0
*/
-public class InMemoryUserSessionResolver implements UserSessionResolver, UserSessionStore {
+public class SimpleUserSessionResolver implements UserSessionResolver, UserSessionStore {
// userId -> sessionId's
private final Map<String, Set<String>> userSessionIds = new ConcurrentHashMap<String, Set<String>>(); | true |
Other | spring-projects | spring-framework | 55dae74f156c1c8326e182e5f1eb7a162cba56a8.json | Add ReplyTo annotation | spring-messaging/src/main/java/org/springframework/messaging/simp/handler/UserDestinationMessageHandler.java | @@ -47,7 +47,7 @@ public class UserDestinationMessageHandler implements MessageHandler {
private String prefix = "/user/";
- private UserSessionResolver userSessionResolver = new InMemoryUserSessionResolver();
+ private UserSessionResolver userSessionResolver = new SimpleUserSessionResolver();
public UserDestinationMessageHandler(MessageSendingOperations<String> messagingTemplate) { | true |
Other | spring-projects | spring-framework | 5d20b75dc215aa4d732d97f53266810c7d936be0.json | Add support for sending private messages
The new UserDestinationMessageHandler resolves messages with
destinations prefixed with "/user/{username}" and resolves them into a
destination to which the user is currently subscribed by appending the
user session id.
For example a destination such as "/user/john/queue/trade-confirmation"
would resolve "/trade-confirmation/i9oqdfzo" assuming "i9oqdfzo" is the
user's session id. | spring-messaging/src/main/java/org/springframework/messaging/simp/handler/AnnotationMethodMessageHandler.java | @@ -63,9 +63,9 @@
* @author Rossen Stoyanchev
* @since 4.0
*/
-public class AnnotationSimpMessageHandler implements MessageHandler, ApplicationContextAware, InitializingBean {
+public class AnnotationMethodMessageHandler implements MessageHandler, ApplicationContextAware, InitializingBean {
- private static final Log logger = LogFactory.getLog(AnnotationSimpMessageHandler.class);
+ private static final Log logger = LogFactory.getLog(AnnotationMethodMessageHandler.class);
private final MessageChannel outboundChannel;
@@ -91,7 +91,7 @@ public class AnnotationSimpMessageHandler implements MessageHandler, Application
* @param inboundChannel a channel for processing incoming messages from clients
* @param outboundChannel a channel for messages going out to clients
*/
- public AnnotationSimpMessageHandler(MessageChannel outboundChannel) {
+ public AnnotationMethodMessageHandler(MessageChannel outboundChannel) {
Assert.notNull(outboundChannel, "outboundChannel is required");
this.outboundChannel = outboundChannel;
} | true |
Other | spring-projects | spring-framework | 5d20b75dc215aa4d732d97f53266810c7d936be0.json | Add support for sending private messages
The new UserDestinationMessageHandler resolves messages with
destinations prefixed with "/user/{username}" and resolves them into a
destination to which the user is currently subscribed by appending the
user session id.
For example a destination such as "/user/john/queue/trade-confirmation"
would resolve "/trade-confirmation/i9oqdfzo" assuming "i9oqdfzo" is the
user's session id. | spring-messaging/src/main/java/org/springframework/messaging/simp/handler/InMemoryUserSessionResolver.java | @@ -0,0 +1,62 @@
+/*
+ * Copyright 2002-2013 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.messaging.simp.handler;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArraySet;
+
+
+/**
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public class InMemoryUserSessionResolver implements UserSessionResolver, UserSessionStore {
+
+ // userId -> sessionId's
+ private final Map<String, Set<String>> userSessionIds = new ConcurrentHashMap<String, Set<String>>();
+
+
+ @Override
+ public void storeUserSessionId(String user, String sessionId) {
+ Set<String> sessionIds = this.userSessionIds.get(user);
+ if (sessionIds == null) {
+ sessionIds = new CopyOnWriteArraySet<String>();
+ this.userSessionIds.put(user, sessionIds);
+ }
+ sessionIds.add(sessionId);
+ }
+
+ @Override
+ public void deleteUserSessionId(String user, String sessionId) {
+ Set<String> sessionIds = this.userSessionIds.get(user);
+ if (sessionIds != null) {
+ if (sessionIds.remove(sessionId) && sessionIds.isEmpty()) {
+ this.userSessionIds.remove(user);
+ }
+ }
+ }
+
+ @Override
+ public Set<String> resolveUserSessionIds(String user) {
+ Set<String> sessionIds = this.userSessionIds.get(user);
+ return (sessionIds != null) ? sessionIds : Collections.<String>emptySet();
+ }
+
+} | true |
Other | spring-projects | spring-framework | 5d20b75dc215aa4d732d97f53266810c7d936be0.json | Add support for sending private messages
The new UserDestinationMessageHandler resolves messages with
destinations prefixed with "/user/{username}" and resolves them into a
destination to which the user is currently subscribed by appending the
user session id.
For example a destination such as "/user/john/queue/trade-confirmation"
would resolve "/trade-confirmation/i9oqdfzo" assuming "i9oqdfzo" is the
user's session id. | spring-messaging/src/main/java/org/springframework/messaging/simp/handler/UserDestinationMessageHandler.java | @@ -0,0 +1,187 @@
+/*
+ * Copyright 2002-2013 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.messaging.simp.handler;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.springframework.messaging.Message;
+import org.springframework.messaging.MessageHandler;
+import org.springframework.messaging.MessagingException;
+import org.springframework.messaging.core.MessageSendingOperations;
+import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
+import org.springframework.messaging.simp.SimpMessageType;
+import org.springframework.messaging.support.MessageBuilder;
+import org.springframework.util.Assert;
+import org.springframework.util.StringUtils;
+
+
+/**
+ *
+ * Supports destinations prefixed with "/user/{username}" and resolves them into a
+ * destination to which the user is currently subscribed by appending the user session id.
+ * For example a destination such as "/user/john/queue/trade-confirmation" would resolve
+ * to "/trade-confirmation/i9oqdfzo" if "i9oqdfzo" is the user's session id.
+ *
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public class UserDestinationMessageHandler implements MessageHandler {
+
+ private static final Log logger = LogFactory.getLog(UserDestinationMessageHandler.class);
+
+ private final MessageSendingOperations<String> messagingTemplate;
+
+ private String prefix = "/user/";
+
+ private UserSessionResolver userSessionResolver = new InMemoryUserSessionResolver();
+
+
+ public UserDestinationMessageHandler(MessageSendingOperations<String> messagingTemplate) {
+ this.messagingTemplate = messagingTemplate;
+ }
+
+ /**
+ * <p>The default prefix is "/user".
+ * @param prefix the prefix to set
+ */
+ public void setPrefix(String prefix) {
+ Assert.hasText(prefix, "prefix is required");
+ this.prefix = prefix.endsWith("/") ? prefix : prefix + "/";
+ }
+
+ /**
+ * @return the prefix
+ */
+ public String getPrefix() {
+ return this.prefix;
+ }
+
+ /**
+ * @param userSessionResolver the userSessionResolver to set
+ */
+ public void setUserSessionResolver(UserSessionResolver userSessionResolver) {
+ this.userSessionResolver = userSessionResolver;
+ }
+
+ /**
+ * @return the userSessionResolver
+ */
+ public UserSessionResolver getUserSessionResolver() {
+ return this.userSessionResolver;
+ }
+
+ /**
+ * @return the messagingTemplate
+ */
+ public MessageSendingOperations<String> getMessagingTemplate() {
+ return this.messagingTemplate;
+ }
+
+ @Override
+ public void handleMessage(Message<?> message) throws MessagingException {
+
+ if (!shouldHandle(message)) {
+ return;
+ }
+
+ SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
+ String destination = headers.getDestination();
+
+ if (logger.isTraceEnabled()) {
+ logger.trace("Processing message to destination " + destination);
+ }
+
+ UserDestinationParser destinationParser = new UserDestinationParser(destination);
+ String user = destinationParser.getUser();
+
+ if (user == null) {
+ if (logger.isErrorEnabled()) {
+ logger.error("Ignoring message, expected destination \"" + this.prefix
+ + "{userId}/**\": " + destination);
+ }
+ return;
+ }
+
+ for (String sessionId : this.userSessionResolver.resolveUserSessionIds(user)) {
+
+ String targetDestination = destinationParser.getTargetDestination(sessionId);
+ headers.setDestination(targetDestination);
+ message = MessageBuilder.fromMessage(message).copyHeaders(headers.toMap()).build();
+
+ if (logger.isTraceEnabled()) {
+ logger.trace("Sending message to resolved target destination " + targetDestination);
+ }
+ this.messagingTemplate.send(targetDestination, message);
+ }
+ }
+
+ protected boolean shouldHandle(Message<?> message) {
+
+ SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
+ SimpMessageType messageType = headers.getMessageType();
+ String destination = headers.getDestination();
+
+ if (!SimpMessageType.MESSAGE.equals(messageType)) {
+ return false;
+ }
+
+ if (!StringUtils.hasText(destination)) {
+ if (logger.isErrorEnabled()) {
+ logger.error("Ignoring message, no destination: " + headers);
+ }
+ return false;
+ }
+ else if (!destination.startsWith(this.prefix)) {
+ return false;
+ }
+
+ return true;
+ }
+
+
+ private class UserDestinationParser {
+
+ private final String user;
+
+ private final String targetDestination;
+
+
+ public UserDestinationParser(String destination) {
+
+ int userStartIndex = prefix.length();
+ int userEndIndex = destination.indexOf('/', userStartIndex);
+
+ if (userEndIndex > 0) {
+ this.user = destination.substring(userStartIndex, userEndIndex);
+ this.targetDestination = destination.substring(userEndIndex);
+ }
+ else {
+ this.user = null;
+ this.targetDestination = null;
+ }
+ }
+
+ public String getUser() {
+ return this.user;
+ }
+
+ public String getTargetDestination(String sessionId) {
+ return (this.targetDestination != null) ? this.targetDestination + "/" + sessionId : null;
+ }
+ }
+
+} | true |
Other | spring-projects | spring-framework | 5d20b75dc215aa4d732d97f53266810c7d936be0.json | Add support for sending private messages
The new UserDestinationMessageHandler resolves messages with
destinations prefixed with "/user/{username}" and resolves them into a
destination to which the user is currently subscribed by appending the
user session id.
For example a destination such as "/user/john/queue/trade-confirmation"
would resolve "/trade-confirmation/i9oqdfzo" assuming "i9oqdfzo" is the
user's session id. | spring-messaging/src/main/java/org/springframework/messaging/simp/handler/UserSessionResolver.java | @@ -0,0 +1,38 @@
+/*
+ * Copyright 2002-2013 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.messaging.simp.handler;
+
+import java.util.Set;
+
+
+/**
+ * A strategy for resolving a user name to one or more session id's.
+ *
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public interface UserSessionResolver {
+
+ /**
+ * Retrieve the sessionId(s) associated with the given user.
+ *
+ * @param user the user name
+ * @return a Set with zero, one, or more, current session id's.
+ */
+ Set<String> resolveUserSessionIds(String user);
+
+} | true |
Other | spring-projects | spring-framework | 5d20b75dc215aa4d732d97f53266810c7d936be0.json | Add support for sending private messages
The new UserDestinationMessageHandler resolves messages with
destinations prefixed with "/user/{username}" and resolves them into a
destination to which the user is currently subscribed by appending the
user session id.
For example a destination such as "/user/john/queue/trade-confirmation"
would resolve "/trade-confirmation/i9oqdfzo" assuming "i9oqdfzo" is the
user's session id. | spring-messaging/src/main/java/org/springframework/messaging/simp/handler/UserSessionStore.java | @@ -0,0 +1,30 @@
+/*
+ * Copyright 2002-2013 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.messaging.simp.handler;
+
+
+/**
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public interface UserSessionStore {
+
+ void storeUserSessionId(String user, String sessionId);
+
+ void deleteUserSessionId(String user, String sessionId);
+
+} | true |
Other | spring-projects | spring-framework | 5d20b75dc215aa4d732d97f53266810c7d936be0.json | Add support for sending private messages
The new UserDestinationMessageHandler resolves messages with
destinations prefixed with "/user/{username}" and resolves them into a
destination to which the user is currently subscribed by appending the
user session id.
For example a destination such as "/user/john/queue/trade-confirmation"
would resolve "/trade-confirmation/i9oqdfzo" assuming "i9oqdfzo" is the
user's session id. | spring-messaging/src/main/java/org/springframework/messaging/simp/handler/package-info.java | @@ -0,0 +1,4 @@
+/**
+ * MessageHandler implementation and supporting classes for message processing.
+ */
+package org.springframework.messaging.simp.handler; | true |
Other | spring-projects | spring-framework | 5d20b75dc215aa4d732d97f53266810c7d936be0.json | Add support for sending private messages
The new UserDestinationMessageHandler resolves messages with
destinations prefixed with "/user/{username}" and resolves them into a
destination to which the user is currently subscribed by appending the
user session id.
For example a destination such as "/user/john/queue/trade-confirmation"
would resolve "/trade-confirmation/i9oqdfzo" assuming "i9oqdfzo" is the
user's session id. | spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompWebSocketHandler.java | @@ -27,6 +27,8 @@
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.simp.SimpMessageType;
+import org.springframework.messaging.simp.handler.UserDestinationMessageHandler;
+import org.springframework.messaging.simp.handler.UserSessionStore;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
@@ -48,13 +50,21 @@ public class StompWebSocketHandler extends TextWebSocketHandlerAdapter implement
*/
public static final String CONNECTED_USER_HEADER = "user-name";
+ /**
+ * A suffix unique to the current session that a client can append to a destination.
+ * @see UserDestinationMessageHandler
+ */
+ public static final String QUEUE_SUFFIX_HEADER = "queue-suffix";
+
private static final byte[] EMPTY_PAYLOAD = new byte[0];
private static Log logger = LogFactory.getLog(StompWebSocketHandler.class);
private MessageChannel clientInputChannel;
+ private UserSessionStore userSessionStore;
+
private final StompMessageConverter stompMessageConverter = new StompMessageConverter();
private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<String, WebSocketSession>();
@@ -70,14 +80,35 @@ public StompWebSocketHandler(MessageChannel clientInputChannel) {
}
+ /**
+ * Configure a store for saving user session information.
+ * @param userSessionStore the userSessionStore to use to store user session id's
+ * @see UserDestinationMessageHandler
+ */
+ public void setUserSessionResolver(UserSessionStore userSessionStore) {
+ this.userSessionStore = userSessionStore;
+ }
+
+ /**
+ * @return the userSessionResolver
+ */
+ public UserSessionStore getUserSessionResolver() {
+ return this.userSessionStore;
+ }
+
public StompMessageConverter getStompMessageConverter() {
return this.stompMessageConverter;
}
+
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
Assert.notNull(this.clientInputChannel, "No output channel for STOMP messages.");
this.sessions.put(session.getId(), session);
+
+ if ((this.userSessionStore != null) && (session.getPrincipal() != null)) {
+ this.userSessionStore.storeUserSessionId(session.getPrincipal().getName(), session.getId());
+ }
}
/**
@@ -146,6 +177,7 @@ else if (acceptVersions.isEmpty()) {
if (session.getPrincipal() != null) {
connectedHeaders.setNativeHeader(CONNECTED_USER_HEADER, session.getPrincipal().getName());
+ connectedHeaders.setNativeHeader(QUEUE_SUFFIX_HEADER, session.getId());
}
// TODO: security
@@ -178,6 +210,10 @@ public void afterConnectionClosed(WebSocketSession session, CloseStatus status)
String sessionId = session.getId();
this.sessions.remove(sessionId);
+ if ((this.userSessionStore != null) && (session.getPrincipal() != null)) {
+ this.userSessionStore.deleteUserSessionId(session.getPrincipal().getName(), sessionId);
+ }
+
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.DISCONNECT);
headers.setSessionId(sessionId);
Message<?> message = MessageBuilder.withPayload(new byte[0]).copyHeaders(headers.toMap()).build(); | true |
Other | spring-projects | spring-framework | 14ab2c88cc512a92d82db1f8fbb22d53445c6aa2.json | Request streaming for Apache HttpClient
- Added org.springframework.http.StreamingHttpOutputMessage, which
allows for a settable request body (as opposed to an output stream).
- Added http.client.HttpComponentsStreamingClientHttpRequest, which
implements the above mentioned interface, mapping setBody() to a
setEntity() call on the Apache HttpClient HttpEntityEnclosingRequest.
- Added a 'bufferRequestBody' property to the
HttpComponentsClientHttpRequestFactory. When this property is set to
false (default is true), we return a
HttpComponentsStreamingClientHttpRequest instead of a (request
buffering) HttpComponentsClientHttpRequest.
Issue: SPR-10728 | spring-web/src/main/java/org/springframework/http/StreamingHttpOutputMessage.java | @@ -0,0 +1,54 @@
+/*
+ * Copyright 2002-2013 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.http;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * Represents a HTTP output message that allows for setting a streaming body.
+ *
+ * @author Arjen Poutsma
+ * @since 4.0
+ */
+public interface StreamingHttpOutputMessage extends HttpOutputMessage {
+
+ /**
+ * Sets the streaming body for this message.
+ *
+ * @param body the streaming body
+ */
+ void setBody(Body body);
+
+ /**
+ * Defines the contract for bodies that can be written directly to a
+ * {@link OuputStream}. It is useful with HTTP client libraries that provide indirect
+ * access to an {@link OutputStream} via a callback mechanism.
+ */
+ public interface Body {
+
+ /**
+ * Writes this body to the given {@link OuputStream}.
+ *
+ * @param outputStream the output stream to write to
+ * @throws IOException in case of errors
+ */
+ void writeTo(OutputStream outputStream) throws IOException;
+
+ }
+
+} | true |
Other | spring-projects | spring-framework | 14ab2c88cc512a92d82db1f8fbb22d53445c6aa2.json | Request streaming for Apache HttpClient
- Added org.springframework.http.StreamingHttpOutputMessage, which
allows for a settable request body (as opposed to an output stream).
- Added http.client.HttpComponentsStreamingClientHttpRequest, which
implements the above mentioned interface, mapping setBody() to a
setEntity() call on the Apache HttpClient HttpEntityEnclosingRequest.
- Added a 'bufferRequestBody' property to the
HttpComponentsClientHttpRequestFactory. When this property is set to
false (default is true), we return a
HttpComponentsStreamingClientHttpRequest instead of a (request
buffering) HttpComponentsClientHttpRequest.
Issue: SPR-10728 | spring-web/src/main/java/org/springframework/http/client/AbstractClientHttpRequest.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 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.
@@ -43,7 +43,7 @@ public final HttpHeaders getHeaders() {
@Override
public final OutputStream getBody() throws IOException {
- checkExecuted();
+ assertNotExecuted();
return getBodyInternal(this.headers);
}
@@ -55,13 +55,18 @@ public Cookies getCookies() {
@Override
public final ClientHttpResponse execute() throws IOException {
- checkExecuted();
+ assertNotExecuted();
ClientHttpResponse result = executeInternal(this.headers);
this.executed = true;
return result;
}
- private void checkExecuted() {
+ /**
+ * Asserts that this request has not been {@linkplain #execute() executed} yet.
+ *
+ * @throws IllegalStateException if this request has been executed
+ */
+ protected void assertNotExecuted() {
Assert.state(!this.executed, "ClientHttpRequest already executed");
}
| true |
Other | spring-projects | spring-framework | 14ab2c88cc512a92d82db1f8fbb22d53445c6aa2.json | Request streaming for Apache HttpClient
- Added org.springframework.http.StreamingHttpOutputMessage, which
allows for a settable request body (as opposed to an output stream).
- Added http.client.HttpComponentsStreamingClientHttpRequest, which
implements the above mentioned interface, mapping setBody() to a
setEntity() call on the Apache HttpClient HttpEntityEnclosingRequest.
- Added a 'bufferRequestBody' property to the
HttpComponentsClientHttpRequestFactory. When this property is set to
false (default is true), we return a
HttpComponentsStreamingClientHttpRequest instead of a (request
buffering) HttpComponentsClientHttpRequest.
Issue: SPR-10728 | spring-web/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequest.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 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.
@@ -73,22 +73,35 @@ public URI getURI() {
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
+ addHeaders(this.httpRequest, headers);
+
+ if (this.httpRequest instanceof HttpEntityEnclosingRequest) {
+ HttpEntityEnclosingRequest entityEnclosingRequest =
+ (HttpEntityEnclosingRequest) this.httpRequest;
+ HttpEntity requestEntity = new ByteArrayEntity(bufferedOutput);
+ entityEnclosingRequest.setEntity(requestEntity);
+ }
+ HttpResponse httpResponse =
+ this.httpClient.execute(this.httpRequest, this.httpContext);
+ return new HttpComponentsClientHttpResponse(httpResponse);
+ }
+
+ /**
+ * Adds the given headers to the given HTTP request.
+ *
+ * @param httpRequest the request to add the headers to
+ * @param headers the headers to add
+ */
+ static void addHeaders(HttpUriRequest httpRequest, HttpHeaders headers) {
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String headerName = entry.getKey();
if (!headerName.equalsIgnoreCase(HTTP.CONTENT_LEN) &&
!headerName.equalsIgnoreCase(HTTP.TRANSFER_ENCODING)) {
for (String headerValue : entry.getValue()) {
- this.httpRequest.addHeader(headerName, headerValue);
+ httpRequest.addHeader(headerName, headerValue);
}
}
}
- if (this.httpRequest instanceof HttpEntityEnclosingRequest) {
- HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) this.httpRequest;
- HttpEntity requestEntity = new ByteArrayEntity(bufferedOutput);
- entityEnclosingRequest.setEntity(requestEntity);
- }
- HttpResponse httpResponse = this.httpClient.execute(this.httpRequest, this.httpContext);
- return new HttpComponentsClientHttpResponse(httpResponse);
}
} | true |
Other | spring-projects | spring-framework | 14ab2c88cc512a92d82db1f8fbb22d53445c6aa2.json | Request streaming for Apache HttpClient
- Added org.springframework.http.StreamingHttpOutputMessage, which
allows for a settable request body (as opposed to an output stream).
- Added http.client.HttpComponentsStreamingClientHttpRequest, which
implements the above mentioned interface, mapping setBody() to a
setEntity() call on the Apache HttpClient HttpEntityEnclosingRequest.
- Added a 'bufferRequestBody' property to the
HttpComponentsClientHttpRequestFactory. When this property is set to
false (default is true), we return a
HttpComponentsStreamingClientHttpRequest instead of a (request
buffering) HttpComponentsClientHttpRequest.
Issue: SPR-10728 | spring-web/src/main/java/org/springframework/http/client/HttpComponentsClientHttpRequestFactory.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 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.
@@ -64,6 +64,7 @@ public class HttpComponentsClientHttpRequestFactory implements ClientHttpRequest
private HttpClient httpClient;
+ private boolean bufferRequestBody = true;
/**
* Create a new instance of the HttpComponentsClientHttpRequestFactory with a default
@@ -128,11 +129,28 @@ public void setReadTimeout(int timeout) {
getHttpClient().getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
}
+ /**
+ * Indicates whether this request factory should buffer the request body internally.
+ *
+ * <p>Default is {@code true}. When sending large amounts of data via POST or PUT, it is
+ * recommended to change this property to {@code false}, so as not to run out of memory.
+ */
+ public void setBufferRequestBody(boolean bufferRequestBody) {
+ this.bufferRequestBody = bufferRequestBody;
+ }
+
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
HttpUriRequest httpRequest = createHttpUriRequest(httpMethod, uri);
postProcessHttpRequest(httpRequest);
- return new HttpComponentsClientHttpRequest(getHttpClient(), httpRequest, createHttpContext(httpMethod, uri));
+ if (bufferRequestBody) {
+ return new HttpComponentsClientHttpRequest(getHttpClient(), httpRequest,
+ createHttpContext(httpMethod, uri));
+ }
+ else {
+ return new HttpComponentsStreamingClientHttpRequest(getHttpClient(),
+ httpRequest, createHttpContext(httpMethod, uri));
+ }
}
/** | true |
Other | spring-projects | spring-framework | 14ab2c88cc512a92d82db1f8fbb22d53445c6aa2.json | Request streaming for Apache HttpClient
- Added org.springframework.http.StreamingHttpOutputMessage, which
allows for a settable request body (as opposed to an output stream).
- Added http.client.HttpComponentsStreamingClientHttpRequest, which
implements the above mentioned interface, mapping setBody() to a
setEntity() call on the Apache HttpClient HttpEntityEnclosingRequest.
- Added a 'bufferRequestBody' property to the
HttpComponentsClientHttpRequestFactory. When this property is set to
false (default is true), we return a
HttpComponentsStreamingClientHttpRequest instead of a (request
buffering) HttpComponentsClientHttpRequest.
Issue: SPR-10728 | spring-web/src/main/java/org/springframework/http/client/HttpComponentsStreamingClientHttpRequest.java | @@ -0,0 +1,168 @@
+/*
+ * Copyright 2002-2013 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.http.client;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URI;
+
+import org.apache.http.Header;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpEntityEnclosingRequest;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.message.BasicHeader;
+import org.apache.http.protocol.HttpContext;
+
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.MediaType;
+import org.springframework.http.StreamingHttpOutputMessage;
+
+/**
+ * {@link ClientHttpRequest} implementation that uses Apache HttpComponents HttpClient to
+ * execute requests.
+ *
+ * <p>Created via the {@link org.springframework.http.client.HttpComponentsClientHttpRequestFactory}.
+ *
+ * @author Arjen Poutsma
+ * @see org.springframework.http.client.HttpComponentsClientHttpRequestFactory#createRequest(java.net.URI,
+ * org.springframework.http.HttpMethod)
+ * @since 4.0
+ */
+final class HttpComponentsStreamingClientHttpRequest extends AbstractClientHttpRequest
+ implements StreamingHttpOutputMessage {
+
+ private final HttpClient httpClient;
+
+ private final HttpUriRequest httpRequest;
+
+ private final HttpContext httpContext;
+
+ private Body body;
+
+ public HttpComponentsStreamingClientHttpRequest(HttpClient httpClient,
+ HttpUriRequest httpRequest, HttpContext httpContext) {
+ this.httpClient = httpClient;
+ this.httpRequest = httpRequest;
+ this.httpContext = httpContext;
+ }
+
+ @Override
+ public HttpMethod getMethod() {
+ return HttpMethod.valueOf(this.httpRequest.getMethod());
+ }
+
+ @Override
+ public URI getURI() {
+ return this.httpRequest.getURI();
+ }
+
+ @Override
+ public void setBody(Body body) {
+ assertNotExecuted();
+ this.body = body;
+ }
+
+ @Override
+ protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
+ throw new UnsupportedOperationException(
+ "getBody not supported when bufferRequestBody is false");
+ }
+
+ @Override
+ protected ClientHttpResponse executeInternal(HttpHeaders headers) throws IOException {
+ HttpComponentsClientHttpRequest.addHeaders(this.httpRequest, headers);
+
+ if (this.httpRequest instanceof HttpEntityEnclosingRequest && body != null) {
+ HttpEntityEnclosingRequest entityEnclosingRequest =
+ (HttpEntityEnclosingRequest) this.httpRequest;
+
+ HttpEntity requestEntity = new StreamingHttpEntity(getHeaders(), body);
+ entityEnclosingRequest.setEntity(requestEntity);
+ }
+ HttpResponse httpResponse =
+ this.httpClient.execute(this.httpRequest, this.httpContext);
+ return new HttpComponentsClientHttpResponse(httpResponse);
+ }
+
+ private static class StreamingHttpEntity implements HttpEntity {
+
+ private final HttpHeaders headers;
+
+ private final StreamingHttpOutputMessage.Body body;
+
+ private StreamingHttpEntity(HttpHeaders headers,
+ StreamingHttpOutputMessage.Body body) {
+ this.headers = headers;
+ this.body = body;
+ }
+
+ @Override
+ public boolean isRepeatable() {
+ return false;
+ }
+
+ @Override
+ public boolean isChunked() {
+ return false;
+ }
+
+ @Override
+ public long getContentLength() {
+ return headers.getContentLength();
+ }
+
+ @Override
+ public Header getContentType() {
+ MediaType contentType = headers.getContentType();
+ return contentType != null ?
+ new BasicHeader("Content-Type", contentType.toString()) : null;
+ }
+
+ @Override
+ public Header getContentEncoding() {
+ String contentEncoding = headers.getFirst("Content-Encoding");
+ return contentEncoding != null ?
+ new BasicHeader("Content-Encoding", contentEncoding) : null;
+
+ }
+
+ @Override
+ public InputStream getContent() throws IOException, IllegalStateException {
+ throw new IllegalStateException();
+ }
+
+ @Override
+ public void writeTo(OutputStream outputStream) throws IOException {
+ body.writeTo(outputStream);
+ }
+
+ @Override
+ public boolean isStreaming() {
+ return true;
+ }
+
+ @Override
+ public void consumeContent() throws IOException {
+ throw new UnsupportedOperationException();
+ }
+ }
+
+} | true |
Other | spring-projects | spring-framework | 14ab2c88cc512a92d82db1f8fbb22d53445c6aa2.json | Request streaming for Apache HttpClient
- Added org.springframework.http.StreamingHttpOutputMessage, which
allows for a settable request body (as opposed to an output stream).
- Added http.client.HttpComponentsStreamingClientHttpRequest, which
implements the above mentioned interface, mapping setBody() to a
setEntity() call on the Apache HttpClient HttpEntityEnclosingRequest.
- Added a 'bufferRequestBody' property to the
HttpComponentsClientHttpRequestFactory. When this property is set to
false (default is true), we return a
HttpComponentsStreamingClientHttpRequest instead of a (request
buffering) HttpComponentsClientHttpRequest.
Issue: SPR-10728 | spring-web/src/main/java/org/springframework/http/converter/AbstractHttpMessageConverter.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 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,6 +17,7 @@
package org.springframework.http.converter;
import java.io.IOException;
+import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -25,10 +26,12 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.springframework.http.Cookies;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
+import org.springframework.http.StreamingHttpOutputMessage;
import org.springframework.util.Assert;
/**
@@ -163,10 +166,10 @@ public final T read(Class<? extends T> clazz, HttpInputMessage inputMessage) thr
* on the output message. It then calls {@link #writeInternal}.
*/
@Override
- public final void write(T t, MediaType contentType, HttpOutputMessage outputMessage)
+ public final void write(final T t, MediaType contentType, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
- HttpHeaders headers = outputMessage.getHeaders();
+ final HttpHeaders headers = outputMessage.getHeaders();
if (headers.getContentType() == null) {
if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
contentType = getDefaultContentType(t);
@@ -181,8 +184,36 @@ public final void write(T t, MediaType contentType, HttpOutputMessage outputMess
headers.setContentLength(contentLength);
}
}
- writeInternal(t, outputMessage);
- outputMessage.getBody().flush();
+ if (outputMessage instanceof StreamingHttpOutputMessage) {
+ StreamingHttpOutputMessage streamingOutputMessage =
+ (StreamingHttpOutputMessage) outputMessage;
+
+ streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() {
+ @Override
+ public void writeTo(final OutputStream outputStream) throws IOException {
+ writeInternal(t, new HttpOutputMessage() {
+ @Override
+ public OutputStream getBody() throws IOException {
+ return outputStream;
+ }
+
+ @Override
+ public HttpHeaders getHeaders() {
+ return headers;
+ }
+
+ @Override
+ public Cookies getCookies() {
+ return null;
+ }
+ });
+ }
+ });
+ }
+ else {
+ writeInternal(t, outputMessage);
+ outputMessage.getBody().flush();
+ }
}
/** | true |
Other | spring-projects | spring-framework | 14ab2c88cc512a92d82db1f8fbb22d53445c6aa2.json | Request streaming for Apache HttpClient
- Added org.springframework.http.StreamingHttpOutputMessage, which
allows for a settable request body (as opposed to an output stream).
- Added http.client.HttpComponentsStreamingClientHttpRequest, which
implements the above mentioned interface, mapping setBody() to a
setEntity() call on the Apache HttpClient HttpEntityEnclosingRequest.
- Added a 'bufferRequestBody' property to the
HttpComponentsClientHttpRequestFactory. When this property is set to
false (default is true), we return a
HttpComponentsStreamingClientHttpRequest instead of a (request
buffering) HttpComponentsClientHttpRequest.
Issue: SPR-10728 | spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java | @@ -18,6 +18,7 @@
import java.io.IOException;
import java.io.InputStream;
+import java.io.OutputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.Enumeration;
@@ -40,8 +41,10 @@
import org.junit.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
+import org.springframework.http.StreamingHttpOutputMessage;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.SocketUtils;
+import org.springframework.util.StreamUtils;
import static org.junit.Assert.*;
@@ -111,9 +114,21 @@ public void echo() throws Exception {
request.getHeaders().add(headerName, headerValue1);
String headerValue2 = "value2";
request.getHeaders().add(headerName, headerValue2);
- byte[] body = "Hello World".getBytes("UTF-8");
+ final byte[] body = "Hello World".getBytes("UTF-8");
request.getHeaders().setContentLength(body.length);
- FileCopyUtils.copy(body, request.getBody());
+ if (request instanceof StreamingHttpOutputMessage) {
+ StreamingHttpOutputMessage streamingRequest =
+ (StreamingHttpOutputMessage) request;
+ streamingRequest.setBody(new StreamingHttpOutputMessage.Body() {
+ @Override
+ public void writeTo(OutputStream outputStream) throws IOException {
+ StreamUtils.copy(body, outputStream);
+ }
+ });
+ }
+ else {
+ StreamUtils.copy(body, request.getBody());
+ }
ClientHttpResponse response = request.execute();
try {
assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode());
@@ -131,8 +146,21 @@ public void echo() throws Exception {
@Test(expected = IllegalStateException.class)
public void multipleWrites() throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST);
- byte[] body = "Hello World".getBytes("UTF-8");
- FileCopyUtils.copy(body, request.getBody());
+ final byte[] body = "Hello World".getBytes("UTF-8");
+ if (request instanceof StreamingHttpOutputMessage) {
+ StreamingHttpOutputMessage streamingRequest =
+ (StreamingHttpOutputMessage) request;
+ streamingRequest.setBody(new StreamingHttpOutputMessage.Body() {
+ @Override
+ public void writeTo(OutputStream outputStream) throws IOException {
+ StreamUtils.copy(body, outputStream);
+ }
+ });
+ }
+ else {
+ StreamUtils.copy(body, request.getBody());
+ }
+
ClientHttpResponse response = request.execute();
try {
FileCopyUtils.copy(body, request.getBody()); | true |
Other | spring-projects | spring-framework | 14ab2c88cc512a92d82db1f8fbb22d53445c6aa2.json | Request streaming for Apache HttpClient
- Added org.springframework.http.StreamingHttpOutputMessage, which
allows for a settable request body (as opposed to an output stream).
- Added http.client.HttpComponentsStreamingClientHttpRequest, which
implements the above mentioned interface, mapping setBody() to a
setEntity() call on the Apache HttpClient HttpEntityEnclosingRequest.
- Added a 'bufferRequestBody' property to the
HttpComponentsClientHttpRequestFactory. When this property is set to
false (default is true), we return a
HttpComponentsStreamingClientHttpRequest instead of a (request
buffering) HttpComponentsClientHttpRequest.
Issue: SPR-10728 | spring-web/src/test/java/org/springframework/http/client/StreamingHttpComponentsClientHttpRequestFactoryTests.java | @@ -0,0 +1,40 @@
+/*
+ * Copyright 2002-2013 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.http.client;
+
+import org.junit.Test;
+
+import org.springframework.http.HttpMethod;
+
+public class StreamingHttpComponentsClientHttpRequestFactoryTests
+ extends AbstractHttpRequestFactoryTestCase {
+
+ @Override
+ protected ClientHttpRequestFactory createRequestFactory() {
+ HttpComponentsClientHttpRequestFactory requestFactory =
+ new HttpComponentsClientHttpRequestFactory();
+ requestFactory.setBufferRequestBody(false);
+ return requestFactory;
+ }
+
+ @Override
+ @Test
+ public void httpMethods() throws Exception {
+ assertHttpMethod("patch", HttpMethod.PATCH);
+ }
+
+} | true |
Other | spring-projects | spring-framework | 83ea0fb9e043670f8153147c1a79026acfa98f54.json | Fix typo in ModelAndViewMethodReturnValueHandler
This commit fixes a typo in the class-level Javadoc for
ModelAndViewMethodReturnValueHandler.
Issue: SPR-10650 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewMethodReturnValueHandler.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 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.
@@ -30,7 +30,7 @@
*
* <p>If the return value is {@code null}, the
* {@link ModelAndViewContainer#setRequestHandled(boolean)} flag is set to
- * {@code false} to indicate the request was handled directly.
+ * {@code true} to indicate the request was handled directly.
*
* <p>A {@link ModelAndView} return type has a set purpose. Therefore this
* handler should be configured ahead of handlers that support any return | false |
Other | spring-projects | spring-framework | dbc904b647a265fb2d267d3957f34e9606886a2a.json | Remove mavenLocal (was temporarily added) | build.gradle | @@ -313,7 +313,6 @@ project("spring-context") {
jvmArgs = ["-disableassertions:org.aspectj.weaver.UnresolvedType"] // SPR-7989
}
repositories {
- mavenLocal() // temporary workaround for locally installed (latest) reactor
maven { url 'http://repo.springsource.org/snapshot' } // reactor
}
}
@@ -498,7 +497,6 @@ project("spring-websocket") {
repositories {
maven { url "https://repository.apache.org/content/repositories/snapshots" } // tomcat-websocket-* snapshots
maven { url "https://maven.java.net/content/repositories/releases" } // javax.websocket, tyrus
- mavenLocal() // temporary workaround for locally installed (latest) reactor
maven { url 'http://repo.springsource.org/snapshot' } // reactor
}
} | false |
Other | spring-projects | spring-framework | 907e286e7703cf3e8c8e954774891b75d661e17d.json | Fix typos in HandlerAdapter | spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerAdapter.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 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.
@@ -20,24 +20,24 @@
import javax.servlet.http.HttpServletResponse;
/**
- * MVC framework SPI interface, allowing parameterization of core MVC workflow.
+ * MVC framework SPI, allowing parameterization of the core MVC workflow.
*
* <p>Interface that must be implemented for each handler type to handle a request.
* This interface is used to allow the {@link DispatcherServlet} to be indefinitely
- * extensible. The DispatcherServlet accesses all installed handlers through this
- * interface, meaning that it does not contain code specific to any handler type.
+ * extensible. The {@code DispatcherServlet} accesses all installed handlers through
+ * this interface, meaning that it does not contain code specific to any handler type.
*
* <p>Note that a handler can be of type {@code Object}. This is to enable
* handlers from other frameworks to be integrated with this framework without
- * custom coding, as well as to allow for annotation handler objects that do
- * not obey any specific Java interface.
+ * custom coding, as well as to allow for annotation-driven handler objects that
+ * do not obey any specific Java interface.
*
* <p>This interface is not intended for application developers. It is available
* to handlers who want to develop their own web workflow.
*
- * <p>Note: HandlerAdaptger implementators may implement the
- * {@link org.springframework.core.Ordered} interface to be able to specify a
- * sorting order (and thus a priority) for getting applied by DispatcherServlet.
+ * <p>Note: {@code HandlerAdapter} implementors may implement the {@link
+ * org.springframework.core.Ordered} interface to be able to specify a sorting
+ * order (and thus a priority) for getting applied by the {@code DispatcherServlet}.
* Non-Ordered instances get treated as lowest priority.
*
* @author Rod Johnson
@@ -48,8 +48,8 @@
public interface HandlerAdapter {
/**
- * Given a handler instance, return whether or not this HandlerAdapter can
- * support it. Typical HandlerAdapters will base the decision on the handler
+ * Given a handler instance, return whether or not this {@code HandlerAdapter}
+ * can support it. Typical HandlerAdapters will base the decision on the handler
* type. HandlerAdapters will usually only support one handler type each.
* <p>A typical implementation:
* <p>{@code | false |
Other | spring-projects | spring-framework | 2a559028ad91cfad0202d728726bffaef9eaa96f.json | Upgrade spring-websocket to Jetty 9.0.4 | build.gradle | @@ -480,11 +480,11 @@ project("spring-websocket") {
}
optional("org.glassfish.tyrus:tyrus-websocket-core:1.0")
optional("org.glassfish.tyrus:tyrus-container-servlet:1.0")
- optional("org.eclipse.jetty:jetty-webapp:9.0.3.v20130506") {
+ optional("org.eclipse.jetty:jetty-webapp:9.0.4.v20130625") {
exclude group: "org.eclipse.jetty.orbit", module: "javax.servlet"
}
- optional("org.eclipse.jetty.websocket:websocket-server:9.0.3.v20130506")
- optional("org.eclipse.jetty.websocket:websocket-client:9.0.3.v20130506")
+ optional("org.eclipse.jetty.websocket:websocket-server:9.0.4.v20130625")
+ optional("org.eclipse.jetty.websocket:websocket-client:9.0.4.v20130625")
optional("com.fasterxml.jackson.core:jackson-databind:2.2.0") // required for SockJS support currently
}
| true |
Other | spring-projects | spring-framework | 2a559028ad91cfad0202d728726bffaef9eaa96f.json | Upgrade spring-websocket to Jetty 9.0.4 | spring-websocket/src/main/java/org/springframework/web/socket/server/support/JettyRequestUpgradeStrategy.java | @@ -24,8 +24,8 @@
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.eclipse.jetty.websocket.api.UpgradeResponse;
import org.eclipse.jetty.websocket.server.HandshakeRFC6455;
-import org.eclipse.jetty.websocket.server.ServletWebSocketRequest;
import org.eclipse.jetty.websocket.server.WebSocketServerFactory;
+import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
@@ -67,8 +67,8 @@ public JettyRequestUpgradeStrategy() {
this.factory.setCreator(new WebSocketCreator() {
@Override
public Object createWebSocket(UpgradeRequest request, UpgradeResponse response) {
- Assert.isInstanceOf(ServletWebSocketRequest.class, request);
- return ((ServletWebSocketRequest) request).getServletAttributes().get(WEBSOCKET_LISTENER_ATTR_NAME);
+ Assert.isInstanceOf(ServletUpgradeRequest.class, request);
+ return ((ServletUpgradeRequest) request).getServletAttributes().get(WEBSOCKET_LISTENER_ATTR_NAME);
}
});
try { | true |
Other | spring-projects | spring-framework | 8560582c405e03c6fd7206b7c1f177218f7b6aa9.json | Add messaging.channel package | build.gradle | @@ -301,6 +301,7 @@ project("spring-context") {
optional("org.hibernate:hibernate-validator:4.3.0.Final")
optional("org.aspectj:aspectjweaver:${aspectjVersion}")
optional("org.apache.geronimo.specs:geronimo-jta_1.1_spec:1.1")
+ optional("reactor:reactor-core:1.0.0.BUILD-SNAPSHOT")
testCompile("commons-dbcp:commons-dbcp:1.2.2")
testCompile("javax.inject:javax.inject-tck:1")
}
@@ -311,6 +312,10 @@ project("spring-context") {
test {
jvmArgs = ["-disableassertions:org.aspectj.weaver.UnresolvedType"] // SPR-7989
}
+ repositories {
+ mavenLocal() // temporary workaround for locally installed (latest) reactor
+ maven { url 'http://repo.springsource.org/snapshot' } // reactor
+ }
}
project("spring-tx") { | true |
Other | spring-projects | spring-framework | 8560582c405e03c6fd7206b7c1f177218f7b6aa9.json | Add messaging.channel package | spring-context/src/main/java/org/springframework/messaging/channel/PublishSubscribeChannel.java | @@ -0,0 +1,101 @@
+/*
+ * Copyright 2002-2013 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.messaging.channel;
+
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArraySet;
+import java.util.concurrent.Executor;
+
+import org.springframework.messaging.Message;
+import org.springframework.messaging.MessageHandler;
+import org.springframework.messaging.SubscribableChannel;
+import org.springframework.util.Assert;
+
+/**
+ * A {@link SubscribableChannel} that sends messages to each of its subscribers. For a
+ * more feature complete implementation consider
+ * {@code org.springframework.integration.channel.PublishSubscribeChannel} from the
+ * Spring Integration project.
+ *
+ * @author Phillip Webb
+ * @since 4.0
+ */
+public class PublishSubscribeChannel implements SubscribableChannel {
+
+ private Executor executor;
+
+ private Set<MessageHandler> handlers = new CopyOnWriteArraySet<MessageHandler>();
+
+
+ /**
+ * Create a new {@link PublishSubscribeChannel} instance where messages will be sent
+ * in the callers thread.
+ */
+ public PublishSubscribeChannel() {
+ this(null);
+ }
+
+ /**
+ * Create a new {@link PublishSubscribeChannel} instance where messages will be sent
+ * via the specified executor.
+ * @param executor the executor used to send the message or {@code null} to execute in
+ * the callers thread.
+ */
+ public PublishSubscribeChannel(Executor executor) {
+ this.executor = executor;
+ }
+
+ @Override
+ public boolean send(Message<?> message) {
+ return send(message, INDEFINITE_TIMEOUT);
+ }
+
+ @Override
+ public boolean send(Message<?> message, long timeout) {
+ Assert.notNull(message, "Message must not be null");
+ Assert.notNull(message.getPayload(), "Message payload must not be null");
+ for (final MessageHandler handler : this.handlers) {
+ dispatchToHandler(message, handler);
+ }
+ return true;
+ }
+
+ private void dispatchToHandler(final Message<?> message, final MessageHandler handler) {
+ if (this.executor == null) {
+ handler.handleMessage(message);
+ }
+ else {
+ this.executor.execute(new Runnable() {
+ @Override
+ public void run() {
+ handler.handleMessage(message);
+ }
+ });
+ }
+ }
+
+ @Override
+ public boolean subscribe(MessageHandler handler) {
+ return this.handlers.add(handler);
+ }
+
+ @Override
+ public boolean unsubscribe(MessageHandler handler) {
+ return this.handlers.remove(handler);
+ }
+
+} | true |
Other | spring-projects | spring-framework | 8560582c405e03c6fd7206b7c1f177218f7b6aa9.json | Add messaging.channel package | spring-context/src/main/java/org/springframework/messaging/channel/ReactorMessageChannel.java | @@ -14,7 +14,7 @@
* limitations under the License.
*/
-package org.springframework.web.messaging.support;
+package org.springframework.messaging.channel;
import java.util.HashMap;
import java.util.Map; | true |
Other | spring-projects | spring-framework | 8560582c405e03c6fd7206b7c1f177218f7b6aa9.json | Add messaging.channel package | spring-context/src/test/java/org/springframework/messaging/channel/PublishSubscibeChannelTests.java | @@ -0,0 +1,148 @@
+/*
+ * Copyright 2002-2013 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.messaging.channel;
+
+import java.util.concurrent.Executor;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.springframework.messaging.Message;
+import org.springframework.messaging.MessageHandler;
+import org.springframework.messaging.MessagingException;
+import org.springframework.messaging.channel.PublishSubscribeChannel;
+import org.springframework.messaging.support.MessageBuilder;
+
+import static org.hamcrest.Matchers.*;
+import static org.junit.Assert.*;
+import static org.mockito.BDDMockito.*;
+
+/**
+ * Tests for {@link PublishSubscribeChannel}.
+ *
+ * @author Phillip Webb
+ */
+public class PublishSubscibeChannelTests {
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+
+ private PublishSubscribeChannel channel = new PublishSubscribeChannel();
+
+ @Mock
+ private MessageHandler handler;
+
+ private final Object payload = new Object();
+
+ private final Message<Object> message = MessageBuilder.withPayload(this.payload).build();
+
+ @Captor
+ private ArgumentCaptor<Runnable> runnableCaptor;
+
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void messageMustNotBeNull() throws Exception {
+ thrown.expect(IllegalArgumentException.class);
+ thrown.expectMessage("Message must not be null");
+ this.channel.send(null);
+ }
+
+ @Test
+ public void payloadMustNotBeNull() throws Exception {
+ Message<?> message = mock(Message.class);
+ thrown.expect(IllegalArgumentException.class);
+ thrown.expectMessage("Message payload must not be null");
+ this.channel.send(message);
+ }
+
+ @Test
+ public void sendWithoutExecutor() {
+ this.channel.subscribe(this.handler);
+ this.channel.send(this.message);
+ verify(this.handler).handleMessage(this.message);
+ }
+
+ @Test
+ public void sendWithExecutor() throws Exception {
+ Executor executor = mock(Executor.class);
+ this.channel = new PublishSubscribeChannel(executor);
+ this.channel.subscribe(this.handler);
+ this.channel.send(this.message);
+ verify(executor).execute(this.runnableCaptor.capture());
+ verify(this.handler, never()).handleMessage(this.message);
+ this.runnableCaptor.getValue().run();
+ verify(this.handler).handleMessage(this.message);
+ }
+
+ @Test
+ public void subscribeTwice() throws Exception {
+ assertThat(this.channel.subscribe(this.handler), equalTo(true));
+ assertThat(this.channel.subscribe(this.handler), equalTo(false));
+ this.channel.send(this.message);
+ verify(this.handler, times(1)).handleMessage(this.message);
+ }
+
+ @Test
+ public void unsubscribeTwice() throws Exception {
+ this.channel.subscribe(this.handler);
+ assertThat(this.channel.unsubscribe(this.handler), equalTo(true));
+ assertThat(this.channel.unsubscribe(this.handler), equalTo(false));
+ this.channel.send(this.message);
+ verify(this.handler, never()).handleMessage(this.message);
+ }
+
+ @Test
+ public void failurePropagates() throws Exception {
+ RuntimeException ex = new RuntimeException();
+ willThrow(ex).given(this.handler).handleMessage(this.message);
+ MessageHandler secondHandler = mock(MessageHandler.class);
+ this.channel.subscribe(this.handler);
+ this.channel.subscribe(secondHandler);
+ try {
+ this.channel.send(message);
+ }
+ catch(RuntimeException actualException) {
+ assertThat(actualException, equalTo(ex));
+ }
+ verifyZeroInteractions(secondHandler);
+ }
+
+ @Test
+ public void concurrentModification() throws Exception {
+ this.channel.subscribe(new MessageHandler() {
+ @Override
+ public void handleMessage(Message<?> message) throws MessagingException {
+ channel.unsubscribe(handler);
+ }
+ });
+ this.channel.subscribe(this.handler);
+ this.channel.send(this.message);
+ verify(this.handler).handleMessage(this.message);
+ }
+
+} | true |
Other | spring-projects | spring-framework | 9dba73dfc90978a98e6d8d214fec107ff71018f4.json | Add ConversionService support for ByteBuffers
Add ByteBufferConverter that is registered by default with the
DefaultConversionService. Allows conversion from/to a ByteBuffer and
byte[] or to any type that can be converted via a byte[].
Issue: SPR-10712 | spring-core/src/main/java/org/springframework/core/convert/support/ByteBufferConverter.java | @@ -0,0 +1,114 @@
+/*
+ * Copyright 2002-2013 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.convert.support;
+
+import java.nio.ByteBuffer;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.springframework.core.convert.ConversionService;
+import org.springframework.core.convert.TypeDescriptor;
+import org.springframework.core.convert.converter.ConditionalGenericConverter;
+
+/**
+ * Converts a {@link ByteBuffer} directly to and from {@code byte[]}s and indirectly to
+ * any type that the {@link ConversionService} support via {@code byte[]}.
+ *
+ * @author Phillip Webb
+ */
+public class ByteBufferConverter implements ConditionalGenericConverter {
+
+ private static final TypeDescriptor BYTE_BUFFER_TYPE = TypeDescriptor.valueOf(ByteBuffer.class);
+
+ private static final TypeDescriptor BYTE_ARRAY_TYPE = TypeDescriptor.valueOf(byte[].class);
+
+ private static final Set<ConvertiblePair> CONVERTIBLE_PAIRS;
+ static {
+ Set<ConvertiblePair> convertiblePairs = new HashSet<ConvertiblePair>();
+ convertiblePairs.add(new ConvertiblePair(ByteBuffer.class, Object.class));
+ convertiblePairs.add(new ConvertiblePair(Object.class, ByteBuffer.class));
+ CONVERTIBLE_PAIRS = Collections.unmodifiableSet(convertiblePairs);
+ }
+
+
+ private ConversionService conversionService;
+
+
+ public ByteBufferConverter(ConversionService conversionService) {
+ this.conversionService = conversionService;
+ }
+
+
+ @Override
+ public Set<ConvertiblePair> getConvertibleTypes() {
+ return CONVERTIBLE_PAIRS;
+ }
+
+ @Override
+ public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
+ if (sourceType.isAssignableTo(BYTE_BUFFER_TYPE)) {
+ return matchesFromByteBuffer(targetType);
+ }
+ if (targetType.isAssignableTo(BYTE_BUFFER_TYPE)) {
+ return matchesToByteBuffer(sourceType);
+ }
+ return false;
+ }
+
+ private boolean matchesFromByteBuffer(TypeDescriptor targetType) {
+ return (targetType.isAssignableTo(BYTE_ARRAY_TYPE) || this.conversionService.canConvert(
+ BYTE_ARRAY_TYPE, targetType));
+ }
+
+ private boolean matchesToByteBuffer(TypeDescriptor sourceType) {
+ return (sourceType.isAssignableTo(BYTE_ARRAY_TYPE) || this.conversionService.canConvert(
+ sourceType, BYTE_ARRAY_TYPE));
+ }
+
+ @Override
+ public Object convert(Object source, TypeDescriptor sourceType,
+ TypeDescriptor targetType) {
+ if (sourceType.isAssignableTo(BYTE_BUFFER_TYPE)) {
+ return convertFromByteBuffer((ByteBuffer) source, targetType);
+ }
+ if (targetType.isAssignableTo(BYTE_BUFFER_TYPE)) {
+ return convertToByteBuffer(source, sourceType);
+ }
+ // Should not happen
+ throw new IllegalStateException("Unexpected source/target types");
+ }
+
+ private Object convertFromByteBuffer(ByteBuffer source, TypeDescriptor targetType) {
+ byte[] bytes = new byte[source.remaining()];
+ source.get(bytes);
+ if (targetType.isAssignableTo(BYTE_ARRAY_TYPE)) {
+ return bytes;
+ }
+ return this.conversionService.convert(bytes, BYTE_ARRAY_TYPE, targetType);
+ }
+
+ private Object convertToByteBuffer(Object source, TypeDescriptor sourceType) {
+ byte[] bytes = (byte[]) (source instanceof byte[] ? source
+ : this.conversionService.convert(source, sourceType, BYTE_ARRAY_TYPE));
+ ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
+ byteBuffer.put(bytes);
+ byteBuffer.rewind();
+ return byteBuffer;
+ }
+
+} | true |
Other | spring-projects | spring-framework | 9dba73dfc90978a98e6d8d214fec107ff71018f4.json | Add ConversionService support for ByteBuffers
Add ByteBufferConverter that is registered by default with the
DefaultConversionService. Allows conversion from/to a ByteBuffer and
byte[] or to any type that can be converted via a byte[].
Issue: SPR-10712 | spring-core/src/main/java/org/springframework/core/convert/support/DefaultConversionService.java | @@ -53,6 +53,7 @@ public DefaultConversionService() {
public static void addDefaultConverters(ConverterRegistry converterRegistry) {
addScalarConverters(converterRegistry);
addCollectionConverters(converterRegistry);
+ addBinaryConverters(converterRegistry);
addFallbackConverters(converterRegistry);
}
@@ -109,6 +110,11 @@ private static void addCollectionConverters(ConverterRegistry converterRegistry)
converterRegistry.addConverter(new ObjectToCollectionConverter(conversionService));
}
+ private static void addBinaryConverters(ConverterRegistry converterRegistry) {
+ ConversionService conversionService = (ConversionService) converterRegistry;
+ converterRegistry.addConverter(new ByteBufferConverter(conversionService));
+ }
+
private static void addFallbackConverters(ConverterRegistry converterRegistry) {
ConversionService conversionService = (ConversionService) converterRegistry;
converterRegistry.addConverter(new ObjectToObjectConverter()); | true |
Other | spring-projects | spring-framework | 9dba73dfc90978a98e6d8d214fec107ff71018f4.json | Add ConversionService support for ByteBuffers
Add ByteBufferConverter that is registered by default with the
DefaultConversionService. Allows conversion from/to a ByteBuffer and
byte[] or to any type that can be converted via a byte[].
Issue: SPR-10712 | spring-core/src/test/java/org/springframework/core/convert/support/ByteBufferConverterTests.java | @@ -0,0 +1,109 @@
+/*
+ * Copyright 2002-2013 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.convert.support;
+
+import java.nio.ByteBuffer;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.springframework.core.convert.converter.Converter;
+
+import static org.hamcrest.Matchers.*;
+import static org.junit.Assert.*;
+
+/**
+ * Tests for {@link ByteBufferConverter}.
+ *
+ * @author Phillip Webb
+ */
+public class ByteBufferConverterTests {
+
+ private GenericConversionService conversionService;
+
+ @Before
+ public void setup() {
+ this.conversionService = new GenericConversionService();
+ this.conversionService.addConverter(new ByteBufferConverter(conversionService));
+ this.conversionService.addConverter(new ByteArrayToOtherTypeConverter());
+ this.conversionService.addConverter(new OtherTypeToByteArrayConverter());
+ }
+
+ @Test
+ public void byteArrayToByteBuffer() throws Exception {
+ byte[] bytes = new byte[] { 1, 2, 3 };
+ ByteBuffer convert = this.conversionService.convert(bytes, ByteBuffer.class);
+ assertThat(bytes, not(sameInstance(convert.array())));
+ assertThat(bytes, equalTo(convert.array()));
+ }
+
+ @Test
+ public void byteBufferToByteArray() throws Exception {
+ byte[] bytes = new byte[] { 1, 2, 3 };
+ ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
+ byte[] convert = this.conversionService.convert(byteBuffer, byte[].class);
+ assertThat(bytes, not(sameInstance(convert)));
+ assertThat(bytes, equalTo(convert));
+ }
+
+ @Test
+ public void byteBufferToOtherType() throws Exception {
+ byte[] bytes = new byte[] { 1, 2, 3 };
+ ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
+ OtherType convert = this.conversionService.convert(byteBuffer, OtherType.class);
+ assertThat(bytes, not(sameInstance(convert.bytes)));
+ assertThat(bytes, equalTo(convert.bytes));
+ }
+
+ @Test
+ public void otherTypeToByteBuffer() throws Exception {
+ byte[] bytes = new byte[] { 1, 2, 3 };
+ OtherType otherType = new OtherType(bytes);
+ ByteBuffer convert = this.conversionService.convert(otherType, ByteBuffer.class);
+ assertThat(bytes, not(sameInstance(convert.array())));
+ assertThat(bytes, equalTo(convert.array()));
+ }
+
+ private static class OtherType {
+
+ private byte[] bytes;
+
+ public OtherType(byte[] bytes) {
+ this.bytes = bytes;
+ }
+
+ }
+
+ private static class ByteArrayToOtherTypeConverter implements
+ Converter<byte[], OtherType> {
+
+ @Override
+ public OtherType convert(byte[] source) {
+ return new OtherType(source);
+ }
+ }
+
+ private static class OtherTypeToByteArrayConverter implements
+ Converter<OtherType, byte[]> {
+
+ @Override
+ public byte[] convert(OtherType source) {
+ return source.bytes;
+ }
+
+ }
+
+} | true |
Other | spring-projects | spring-framework | e694cc16c72a5304e031ff144de340ebb72b93df.json | Consider original headers in pattern-based removal
When headers are being removed based on pattern matching, both the
new header names and the original header names need to be matched
against the pattern. Previously, only new headers were being
considered resulting in any matching original headers not being
removed. | spring-context/src/main/java/org/springframework/messaging/support/MessageHeaderAccessor.java | @@ -142,11 +142,8 @@ public void removeHeaders(String... headerPatterns) {
for (String pattern : headerPatterns) {
if (StringUtils.hasLength(pattern)){
if (pattern.contains("*")){
- for (String headerName : this.headers.keySet()) {
- if (PatternMatchUtils.simpleMatch(pattern, headerName)){
- headersToRemove.add(headerName);
- }
- }
+ headersToRemove.addAll(getMatchingHeaderNames(pattern, this.headers));
+ headersToRemove.addAll(getMatchingHeaderNames(pattern, this.originalHeaders));
}
else {
headersToRemove.add(pattern);
@@ -158,6 +155,18 @@ public void removeHeaders(String... headerPatterns) {
}
}
+ private List<String> getMatchingHeaderNames(String pattern, Map<String, Object> headers) {
+ List<String> matchingHeaderNames = new ArrayList<String>();
+ if (headers != null) {
+ for (Map.Entry<String, Object> header: headers.entrySet()) {
+ if (PatternMatchUtils.simpleMatch(pattern, header.getKey())) {
+ matchingHeaderNames.add(header.getKey());
+ }
+ }
+ }
+ return matchingHeaderNames;
+ }
+
/**
* Remove the value for the given header name.
*/ | false |
Other | spring-projects | spring-framework | 98d70733704fd96b999e1664a6609e5191affc2d.json | Verify types when setting header
When a header is being set, verify that the type that's provided is
legal for the header that's been set. For example, the error channel's
type must be a MessageChannel or a String.
The method that performs type verification is protected so that it
can be overriden by sub-classes. It is expected that an overriding
method will call the super method. | spring-context/src/main/java/org/springframework/messaging/support/MessageHeaderAccessor.java | @@ -113,6 +113,7 @@ else if (this.originalHeaders != null) {
*/
public void setHeader(String name, Object value) {
Assert.isTrue(!isReadOnly(name), "The '" + name + "' header is read-only.");
+ verifyType(name, value);
if (!ObjectUtils.nullSafeEquals(value, getHeader(name))) {
this.headers.put(name, value);
}
@@ -209,11 +210,19 @@ public void setErrorChannelName(String errorChannelName) {
setHeader(MessageHeaders.ERROR_CHANNEL, errorChannelName);
}
-
@Override
public String toString() {
return getClass().getSimpleName() + " [originalHeaders=" + this.originalHeaders
+ ", updated headers=" + this.headers + "]";
}
+ protected void verifyType(String headerName, Object headerValue) {
+ if (headerName != null && headerValue != null) {
+ if (MessageHeaders.ERROR_CHANNEL.equals(headerName)
+ || MessageHeaders.REPLY_CHANNEL.endsWith(headerName)) {
+ Assert.isTrue(headerValue instanceof MessageChannel || headerValue instanceof String, "The '"
+ + headerName + "' header value must be a MessageChannel or String.");
+ }
+ }
+ }
} | false |
Other | spring-projects | spring-framework | 465fc7638f1736c3803c4893a080f0a7e92497da.json | Fix typo in MessageHeaderAccessor's class name
Remove the extra 's' from the class name | spring-context/src/main/java/org/springframework/messaging/support/MessageBuilder.java | @@ -34,7 +34,7 @@
private final T payload;
- private final MessageHeaderAccesssor headerAccessor;
+ private final MessageHeaderAccessor headerAccessor;
private final Message<T> originalMessage;
@@ -46,7 +46,7 @@ private MessageBuilder(T payload, Message<T> originalMessage) {
Assert.notNull(payload, "payload must not be null");
this.payload = payload;
this.originalMessage = originalMessage;
- this.headerAccessor = new MessageHeaderAccesssor(originalMessage);
+ this.headerAccessor = new MessageHeaderAccessor(originalMessage);
}
/** | true |
Other | spring-projects | spring-framework | 465fc7638f1736c3803c4893a080f0a7e92497da.json | Fix typo in MessageHeaderAccessor's class name
Remove the extra 's' from the class name | spring-context/src/main/java/org/springframework/messaging/support/MessageHeaderAccessor.java | @@ -37,15 +37,15 @@
* A base class for read/write access to {@link MessageHeaders}. Supports creation of new
* headers or modification of existing message headers.
* <p>
- * Sub-classes can provide additinoal typed getters and setters for convenient access to
+ * Sub-classes can provide additional typed getters and setters for convenient access to
* specific headers. Getters and setters should delegate to {@link #getHeader(String)} or
* {@link #setHeader(String, Object)} respectively. At the end {@link #toMap()} can be
* used to obtain the resulting headers.
*
* @author Rossen Stoyanchev
* @since 4.0
*/
-public class MessageHeaderAccesssor {
+public class MessageHeaderAccessor {
protected Log logger = LogFactory.getLog(getClass());
@@ -60,14 +60,14 @@ public class MessageHeaderAccesssor {
/**
* A constructor for creating new message headers.
*/
- public MessageHeaderAccesssor() {
+ public MessageHeaderAccessor() {
this.originalHeaders = null;
}
/**
* A constructor for accessing and modifying existing message headers.
*/
- public MessageHeaderAccesssor(Message<?> message) {
+ public MessageHeaderAccessor(Message<?> message) {
this.originalHeaders = (message != null) ? message.getHeaders() : null;
}
| true |
Other | spring-projects | spring-framework | 465fc7638f1736c3803c4893a080f0a7e92497da.json | Fix typo in MessageHeaderAccessor's class name
Remove the extra 's' from the class name | spring-context/src/main/java/org/springframework/messaging/support/NativeMessageHeaderAccessor.java | @@ -28,14 +28,14 @@
/**
- * An extension of {@link MessageHeaderAccesssor} that also provides read/write access to
+ * An extension of {@link MessageHeaderAccessor} that also provides read/write access to
* message headers from an external message source. Native message headers are kept
* in a {@link MultiValueMap} under the key {@link #NATIVE_HEADERS}.
*
* @author Rossen Stoyanchev
* @since 4.0
*/
-public class NativeMessageHeaderAccessor extends MessageHeaderAccesssor {
+public class NativeMessageHeaderAccessor extends MessageHeaderAccessor {
public static final String NATIVE_HEADERS = "nativeHeaders"; | true |
Other | spring-projects | spring-framework | 486b4101ec6675a53c1595350878a10857518331.json | Introduce MessageHeader accessor types
A new type MessageHeaderAccesssor provides read/write access to
MessageHeaders along with typed getter/setter methods along the lines
of the existing MessageBuilder methods (internally MessageBuilder
merely delegates to MessageHeaderAccessor). This class is extensible
with sub-classes expected to provide typed getter/setter methods for
specific categories of message headers.
NativeMessageHeaderAccessor is one specific sub-class that further
provides read/write access to headers from some external message
source (e.g. STOMP headers). Native headers are stored in a separate
MultiValueMap and kept under a specific key. | build.gradle | @@ -490,7 +490,7 @@ project("spring-websocket") {
repositories {
maven { url "https://repository.apache.org/content/repositories/snapshots" } // tomcat-websocket-* snapshots
maven { url "https://maven.java.net/content/repositories/releases" } // javax.websocket, tyrus
- mavenLocal() // temporary workaround for locally installed (latest) reactor
+ mavenLocal() // temporary workaround for locally installed (latest) reactor
maven { url 'http://repo.springsource.org/snapshot' } // reactor
}
} | true |
Other | spring-projects | spring-framework | 486b4101ec6675a53c1595350878a10857518331.json | Introduce MessageHeader accessor types
A new type MessageHeaderAccesssor provides read/write access to
MessageHeaders along with typed getter/setter methods along the lines
of the existing MessageBuilder methods (internally MessageBuilder
merely delegates to MessageHeaderAccessor). This class is extensible
with sub-classes expected to provide typed getter/setter methods for
specific categories of message headers.
NativeMessageHeaderAccessor is one specific sub-class that further
provides read/write access to headers from some external message
source (e.g. STOMP headers). Native headers are stored in a separate
MultiValueMap and kept under a specific key. | spring-context/src/main/java/org/springframework/messaging/MessageHeaders.java | @@ -35,8 +35,8 @@
/**
* The headers for a {@link Message}.<br>
- * IMPORTANT: MessageHeaders are immutable. Any mutating operation (e.g., put(..), putAll(..) etc.)
- * will result in {@link UnsupportedOperationException}
+ * IMPORTANT: This class is immutable. Any mutating operation (e.g., put(..), putAll(..) etc.)
+ * will throw {@link UnsupportedOperationException}
*
* <p>To create MessageHeaders instance use fluent MessageBuilder API
* <pre>
@@ -52,11 +52,10 @@
*
* @author Arjen Poutsma
* @author Mark Fisher
- * @author Oleg Zhurakousky
* @author Gary Russell
* @since 4.0
*/
-public class MessageHeaders implements Map<String, Object>, Serializable {
+public final class MessageHeaders implements Map<String, Object>, Serializable {
private static final long serialVersionUID = -4615750558355702881L;
@@ -74,26 +73,12 @@ public class MessageHeaders implements Map<String, Object>, Serializable {
public static final String TIMESTAMP = "timestamp";
- public static final String CORRELATION_ID = "correlationId";
-
public static final String REPLY_CHANNEL = "replyChannel";
public static final String ERROR_CHANNEL = "errorChannel";
- public static final String EXPIRATION_DATE = "expirationDate";
-
- public static final String PRIORITY = "priority";
-
- public static final String SEQUENCE_NUMBER = "sequenceNumber";
-
- public static final String SEQUENCE_SIZE = "sequenceSize";
-
- public static final String SEQUENCE_DETAILS = "sequenceDetails";
-
public static final String CONTENT_TYPE = "contentType";
- public static final String POSTPROCESS_RESULT = "postProcessResult";
-
public static final List<String> HEADER_NAMES = Arrays.asList(ID, TIMESTAMP);
@@ -121,28 +106,6 @@ public Long getTimestamp() {
return this.get(TIMESTAMP, Long.class);
}
- public Long getExpirationDate() {
- return this.get(EXPIRATION_DATE, Long.class);
- }
-
- public Object getCorrelationId() {
- return this.get(CORRELATION_ID);
- }
-
- public Integer getSequenceNumber() {
- Integer sequenceNumber = this.get(SEQUENCE_NUMBER, Integer.class);
- return (sequenceNumber != null ? sequenceNumber : 0);
- }
-
- public Integer getSequenceSize() {
- Integer sequenceSize = this.get(SEQUENCE_SIZE, Integer.class);
- return (sequenceSize != null ? sequenceSize : 0);
- }
-
- public Integer getPriority() {
- return this.get(PRIORITY, Integer.class);
- }
-
public Object getReplyChannel() {
return this.get(REPLY_CHANNEL);
} | true |
Other | spring-projects | spring-framework | 486b4101ec6675a53c1595350878a10857518331.json | Introduce MessageHeader accessor types
A new type MessageHeaderAccesssor provides read/write access to
MessageHeaders along with typed getter/setter methods along the lines
of the existing MessageBuilder methods (internally MessageBuilder
merely delegates to MessageHeaderAccessor). This class is extensible
with sub-classes expected to provide typed getter/setter methods for
specific categories of message headers.
NativeMessageHeaderAccessor is one specific sub-class that further
provides read/write access to headers from some external message
source (e.g. STOMP headers). Native headers are stored in a separate
MultiValueMap and kept under a specific key. | spring-context/src/main/java/org/springframework/messaging/support/GenericMessage.java | @@ -66,15 +66,11 @@ protected GenericMessage(T payload, Map<String, Object> headers) {
else {
headers = new HashMap<String, Object>(headers);
}
- this.headers = createMessageHeaders(headers);
+ this.headers = new MessageHeaders(headers);
this.payload = payload;
}
- protected MessageHeaders createMessageHeaders(Map<String, Object> headers) {
- return new MessageHeaders(headers);
- }
-
public MessageHeaders getHeaders() {
return this.headers;
} | true |
Other | spring-projects | spring-framework | 486b4101ec6675a53c1595350878a10857518331.json | Introduce MessageHeader accessor types
A new type MessageHeaderAccesssor provides read/write access to
MessageHeaders along with typed getter/setter methods along the lines
of the existing MessageBuilder methods (internally MessageBuilder
merely delegates to MessageHeaderAccessor). This class is extensible
with sub-classes expected to provide typed getter/setter methods for
specific categories of message headers.
NativeMessageHeaderAccessor is one specific sub-class that further
provides read/write access to headers from some external message
source (e.g. STOMP headers). Native headers are stored in a separate
MultiValueMap and kept under a specific key. | spring-context/src/main/java/org/springframework/messaging/support/MessageBuilder.java | @@ -16,41 +16,28 @@
package org.springframework.messaging.support;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
-import org.springframework.messaging.MessageHeaders;
import org.springframework.util.Assert;
-import org.springframework.util.PatternMatchUtils;
-import org.springframework.util.StringUtils;
/**
- * TODO
+ * A builder for creating {@link GenericMessage} or {@link ErrorMessage} if the payload is
+ * {@link Throwable}.
*
* @author Arjen Poutsma
* @author Mark Fisher
- * @author Oleg Zhurakousky
- * @author Dave Syer
* @since 4.0
*/
public final class MessageBuilder<T> {
private final T payload;
- private final Map<String, Object> headers = new HashMap<String, Object>();
+ private final MessageHeaderAccesssor headerAccessor;
private final Message<T> originalMessage;
- private volatile boolean modified;
/**
* Private constructor to be invoked from the static factory methods only.
@@ -59,15 +46,13 @@ private MessageBuilder(T payload, Message<T> originalMessage) {
Assert.notNull(payload, "payload must not be null");
this.payload = payload;
this.originalMessage = originalMessage;
- if (originalMessage != null) {
- this.copyHeaders(originalMessage.getHeaders());
- this.modified = (!this.payload.equals(originalMessage.getPayload()));
- }
+ this.headerAccessor = new MessageHeaderAccesssor(originalMessage);
}
/**
- * Create a builder for a new {@link Message} instance pre-populated with all of the headers copied from the
- * provided message. The payload of the provided Message will also be used as the payload for the new message.
+ * Create a builder for a new {@link Message} instance pre-populated with all of the
+ * headers copied from the provided message. The payload of the provided Message will
+ * also be used as the payload for the new message.
*
* @param message the Message from which the payload and all headers will be copied
*/
@@ -88,248 +73,88 @@ public static <T> MessageBuilder<T> withPayload(T payload) {
}
/**
- * Set the value for the given header name. If the provided value is <code>null</code>, the header will be removed.
+ * Set the value for the given header name. If the provided value is <code>null</code>
+ * , the header will be removed.
*/
public MessageBuilder<T> setHeader(String headerName, Object headerValue) {
- Assert.isTrue(!this.isReadOnly(headerName), "The '" + headerName + "' header is read-only.");
- if (StringUtils.hasLength(headerName) && !headerName.equals(MessageHeaders.ID)
- && !headerName.equals(MessageHeaders.TIMESTAMP)) {
- this.verifyType(headerName, headerValue);
- if (headerValue == null) {
- Object removedValue = this.headers.remove(headerName);
- if (removedValue != null) {
- this.modified = true;
- }
- }
- else {
- Object replacedValue = this.headers.put(headerName, headerValue);
- if (!headerValue.equals(replacedValue)) {
- this.modified = true;
- }
- }
- }
+ this.headerAccessor.setHeader(headerName, headerValue);
return this;
}
/**
- * Set the value for the given header name only if the header name is not already associated with a value.
+ * Set the value for the given header name only if the header name is not already
+ * associated with a value.
*/
public MessageBuilder<T> setHeaderIfAbsent(String headerName, Object headerValue) {
- if (this.headers.get(headerName) == null) {
- this.setHeader(headerName, headerValue);
- }
+ this.headerAccessor.setHeaderIfAbsent(headerName, headerValue);
return this;
}
/**
- * Removes all headers provided via array of 'headerPatterns'. As the name suggests the array
- * may contain simple matching patterns for header names. Supported pattern styles are:
- * "xxx*", "*xxx", "*xxx*" and "xxx*yyy".
- *
- * @param headerPatterns
+ * Removes all headers provided via array of 'headerPatterns'. As the name suggests
+ * the array may contain simple matching patterns for header names. Supported pattern
+ * styles are: "xxx*", "*xxx", "*xxx*" and "xxx*yyy".
*/
public MessageBuilder<T> removeHeaders(String... headerPatterns) {
- List<String> headersToRemove = new ArrayList<String>();
- for (String pattern : headerPatterns) {
- if (StringUtils.hasLength(pattern)){
- if (pattern.contains("*")){
- for (String headerName : this.headers.keySet()) {
- if (PatternMatchUtils.simpleMatch(pattern, headerName)){
- headersToRemove.add(headerName);
- }
- }
- }
- else {
- headersToRemove.add(pattern);
- }
- }
- }
- for (String headerToRemove : headersToRemove) {
- this.removeHeader(headerToRemove);
- }
+ this.headerAccessor.removeHeaders(headerPatterns);
return this;
}
/**
* Remove the value for the given header name.
*/
public MessageBuilder<T> removeHeader(String headerName) {
- if (StringUtils.hasLength(headerName) && !headerName.equals(MessageHeaders.ID)
- && !headerName.equals(MessageHeaders.TIMESTAMP)) {
- Object removedValue = this.headers.remove(headerName);
- if (removedValue != null) {
- this.modified = true;
- }
- }
+ this.headerAccessor.removeHeader(headerName);
return this;
}
/**
- * Copy the name-value pairs from the provided Map. This operation will overwrite any existing values. Use {
- * {@link #copyHeadersIfAbsent(Map)} to avoid overwriting values. Note that the 'id' and 'timestamp' header values
- * will never be overwritten.
- *
- * @see MessageHeaders#ID
- * @see MessageHeaders#TIMESTAMP
+ * Copy the name-value pairs from the provided Map. This operation will overwrite any
+ * existing values. Use { {@link #copyHeadersIfAbsent(Map)} to avoid overwriting
+ * values. Note that the 'id' and 'timestamp' header values will never be overwritten.
*/
public MessageBuilder<T> copyHeaders(Map<String, ?> headersToCopy) {
- Set<String> keys = headersToCopy.keySet();
- for (String key : keys) {
- if (!this.isReadOnly(key)) {
- this.setHeader(key, headersToCopy.get(key));
- }
- }
+ this.headerAccessor.copyHeaders(headersToCopy);
return this;
}
/**
- * Copy the name-value pairs from the provided Map. This operation will <em>not</em> overwrite any existing values.
+ * Copy the name-value pairs from the provided Map. This operation will <em>not</em>
+ * overwrite any existing values.
*/
public MessageBuilder<T> copyHeadersIfAbsent(Map<String, ?> headersToCopy) {
- Set<String> keys = headersToCopy.keySet();
- for (String key : keys) {
- if (!this.isReadOnly(key)) {
- this.setHeaderIfAbsent(key, headersToCopy.get(key));
- }
- }
- return this;
- }
-
- public MessageBuilder<T> setExpirationDate(Long expirationDate) {
- return this.setHeader(MessageHeaders.EXPIRATION_DATE, expirationDate);
- }
-
- public MessageBuilder<T> setExpirationDate(Date expirationDate) {
- if (expirationDate != null) {
- return this.setHeader(MessageHeaders.EXPIRATION_DATE, expirationDate.getTime());
- }
- else {
- return this.setHeader(MessageHeaders.EXPIRATION_DATE, null);
- }
- }
-
- public MessageBuilder<T> setCorrelationId(Object correlationId) {
- return this.setHeader(MessageHeaders.CORRELATION_ID, correlationId);
- }
-
- public MessageBuilder<T> pushSequenceDetails(Object correlationId, int sequenceNumber, int sequenceSize) {
- Object incomingCorrelationId = headers.get(MessageHeaders.CORRELATION_ID);
- @SuppressWarnings("unchecked")
- List<List<Object>> incomingSequenceDetails = (List<List<Object>>) headers.get(MessageHeaders.SEQUENCE_DETAILS);
- if (incomingCorrelationId != null) {
- if (incomingSequenceDetails == null) {
- incomingSequenceDetails = new ArrayList<List<Object>>();
- }
- else {
- incomingSequenceDetails = new ArrayList<List<Object>>(incomingSequenceDetails);
- }
- incomingSequenceDetails.add(Arrays.asList(incomingCorrelationId,
- headers.get(MessageHeaders.SEQUENCE_NUMBER), headers.get(MessageHeaders.SEQUENCE_SIZE)));
- incomingSequenceDetails = Collections.unmodifiableList(incomingSequenceDetails);
- }
- if (incomingSequenceDetails != null) {
- setHeader(MessageHeaders.SEQUENCE_DETAILS, incomingSequenceDetails);
- }
- return setCorrelationId(correlationId).setSequenceNumber(sequenceNumber).setSequenceSize(sequenceSize);
- }
-
- public MessageBuilder<T> popSequenceDetails() {
- String key = MessageHeaders.SEQUENCE_DETAILS;
- if (!headers.containsKey(key)) {
- return this;
- }
- @SuppressWarnings("unchecked")
- List<List<Object>> incomingSequenceDetails = new ArrayList<List<Object>>((List<List<Object>>) headers.get(key));
- List<Object> sequenceDetails = incomingSequenceDetails.remove(incomingSequenceDetails.size() - 1);
- Assert.state(sequenceDetails.size() == 3, "Wrong sequence details (not created by MessageBuilder?): "
- + sequenceDetails);
- setCorrelationId(sequenceDetails.get(0));
- Integer sequenceNumber = (Integer) sequenceDetails.get(1);
- Integer sequenceSize = (Integer) sequenceDetails.get(2);
- if (sequenceNumber != null) {
- setSequenceNumber(sequenceNumber);
- }
- if (sequenceSize != null) {
- setSequenceSize(sequenceSize);
- }
- if (!incomingSequenceDetails.isEmpty()) {
- headers.put(MessageHeaders.SEQUENCE_DETAILS, incomingSequenceDetails);
- }
- else {
- headers.remove(MessageHeaders.SEQUENCE_DETAILS);
- }
+ this.headerAccessor.copyHeadersIfAbsent(headersToCopy);
return this;
}
public MessageBuilder<T> setReplyChannel(MessageChannel replyChannel) {
- return this.setHeader(MessageHeaders.REPLY_CHANNEL, replyChannel);
+ this.headerAccessor.setReplyChannel(replyChannel);
+ return this;
}
public MessageBuilder<T> setReplyChannelName(String replyChannelName) {
- return this.setHeader(MessageHeaders.REPLY_CHANNEL, replyChannelName);
+ this.headerAccessor.setReplyChannelName(replyChannelName);
+ return this;
}
public MessageBuilder<T> setErrorChannel(MessageChannel errorChannel) {
- return this.setHeader(MessageHeaders.ERROR_CHANNEL, errorChannel);
+ this.headerAccessor.setErrorChannel(errorChannel);
+ return this;
}
public MessageBuilder<T> setErrorChannelName(String errorChannelName) {
- return this.setHeader(MessageHeaders.ERROR_CHANNEL, errorChannelName);
- }
-
- public MessageBuilder<T> setSequenceNumber(Integer sequenceNumber) {
- return this.setHeader(MessageHeaders.SEQUENCE_NUMBER, sequenceNumber);
- }
-
- public MessageBuilder<T> setSequenceSize(Integer sequenceSize) {
- return this.setHeader(MessageHeaders.SEQUENCE_SIZE, sequenceSize);
- }
-
- public MessageBuilder<T> setPriority(Integer priority) {
- return this.setHeader(MessageHeaders.PRIORITY, priority);
+ this.headerAccessor.setErrorChannelName(errorChannelName);
+ return this;
}
@SuppressWarnings("unchecked")
public Message<T> build() {
- if (!this.modified && this.originalMessage != null) {
+ if ((this.originalMessage != null) && !this.headerAccessor.isModified()) {
return this.originalMessage;
}
if (this.payload instanceof Throwable) {
- return (Message<T>) new ErrorMessage((Throwable) this.payload, this.headers);
- }
- return new GenericMessage<T>(this.payload, this.headers);
- }
-
- private boolean isReadOnly(String headerName) {
- return MessageHeaders.ID.equals(headerName) || MessageHeaders.TIMESTAMP.equals(headerName);
- }
-
- private void verifyType(String headerName, Object headerValue) {
- if (headerName != null && headerValue != null) {
- if (MessageHeaders.ID.equals(headerName)) {
- Assert.isTrue(headerValue instanceof UUID, "The '" + headerName + "' header value must be a UUID.");
- }
- else if (MessageHeaders.TIMESTAMP.equals(headerName)) {
- Assert.isTrue(headerValue instanceof Long, "The '" + headerName + "' header value must be a Long.");
- }
- else if (MessageHeaders.EXPIRATION_DATE.equals(headerName)) {
- Assert.isTrue(headerValue instanceof Date || headerValue instanceof Long, "The '" + headerName
- + "' header value must be a Date or Long.");
- }
- else if (MessageHeaders.ERROR_CHANNEL.equals(headerName)
- || MessageHeaders.REPLY_CHANNEL.endsWith(headerName)) {
- Assert.isTrue(headerValue instanceof MessageChannel || headerValue instanceof String, "The '"
- + headerName + "' header value must be a MessageChannel or String.");
- }
- else if (MessageHeaders.SEQUENCE_NUMBER.equals(headerName)
- || MessageHeaders.SEQUENCE_SIZE.equals(headerName)) {
- Assert.isTrue(Integer.class.isAssignableFrom(headerValue.getClass()), "The '" + headerName
- + "' header value must be an Integer.");
- }
- else if (MessageHeaders.PRIORITY.equals(headerName)) {
- Assert.isTrue(Integer.class.isAssignableFrom(headerValue.getClass()), "The '" + headerName
- + "' header value must be an Integer.");
- }
+ return (Message<T>) new ErrorMessage((Throwable) this.payload, this.headerAccessor.toMap());
}
+ return new GenericMessage<T>(this.payload, this.headerAccessor.toMap());
}
} | true |
Other | spring-projects | spring-framework | 486b4101ec6675a53c1595350878a10857518331.json | Introduce MessageHeader accessor types
A new type MessageHeaderAccesssor provides read/write access to
MessageHeaders along with typed getter/setter methods along the lines
of the existing MessageBuilder methods (internally MessageBuilder
merely delegates to MessageHeaderAccessor). This class is extensible
with sub-classes expected to provide typed getter/setter methods for
specific categories of message headers.
NativeMessageHeaderAccessor is one specific sub-class that further
provides read/write access to headers from some external message
source (e.g. STOMP headers). Native headers are stored in a separate
MultiValueMap and kept under a specific key. | spring-context/src/main/java/org/springframework/messaging/support/MessageHeaderAccesssor.java | @@ -0,0 +1,219 @@
+/*
+ * Copyright 2002-2013 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.messaging.support;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.springframework.messaging.Message;
+import org.springframework.messaging.MessageChannel;
+import org.springframework.messaging.MessageHeaders;
+import org.springframework.util.Assert;
+import org.springframework.util.ObjectUtils;
+import org.springframework.util.PatternMatchUtils;
+import org.springframework.util.StringUtils;
+
+
+/**
+ * A base class for read/write access to {@link MessageHeaders}. Supports creation of new
+ * headers or modification of existing message headers.
+ * <p>
+ * Sub-classes can provide additinoal typed getters and setters for convenient access to
+ * specific headers. Getters and setters should delegate to {@link #getHeader(String)} or
+ * {@link #setHeader(String, Object)} respectively. At the end {@link #toMap()} can be
+ * used to obtain the resulting headers.
+ *
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public class MessageHeaderAccesssor {
+
+ protected Log logger = LogFactory.getLog(getClass());
+
+
+ // wrapped read-only message headers
+ private final MessageHeaders originalHeaders;
+
+ // header updates
+ private final Map<String, Object> headers = new HashMap<String, Object>(4);
+
+
+ /**
+ * A constructor for creating new message headers.
+ */
+ public MessageHeaderAccesssor() {
+ this.originalHeaders = null;
+ }
+
+ /**
+ * A constructor for accessing and modifying existing message headers.
+ */
+ public MessageHeaderAccesssor(Message<?> message) {
+ this.originalHeaders = (message != null) ? message.getHeaders() : null;
+ }
+
+
+ /**
+ * Return a header map including original, wrapped headers (if any) plus additional
+ * header updates made through accessor methods.
+ */
+ public Map<String, Object> toMap() {
+ Map<String, Object> result = new HashMap<String, Object>();
+ if (this.originalHeaders != null) {
+ result.putAll(this.originalHeaders);
+ }
+ for (String key : this.headers.keySet()) {
+ Object value = this.headers.get(key);
+ if (value == null) {
+ result.remove(key);
+ }
+ else {
+ result.put(key, value);
+ }
+ }
+ return result;
+ }
+
+ public boolean isModified() {
+ return (!this.headers.isEmpty());
+ }
+
+ public Object getHeader(String headerName) {
+ if (this.headers.containsKey(headerName)) {
+ return this.headers.get(headerName);
+ }
+ else if (this.originalHeaders != null) {
+ return this.originalHeaders.get(headerName);
+ }
+ return null;
+ }
+
+ /**
+ * Set the value for the given header name. If the provided value is {@code null} the
+ * header will be removed.
+ */
+ public void setHeader(String name, Object value) {
+ Assert.isTrue(!isReadOnly(name), "The '" + name + "' header is read-only.");
+ if (!ObjectUtils.nullSafeEquals(value, getHeader(name))) {
+ this.headers.put(name, value);
+ }
+ }
+
+ protected boolean isReadOnly(String headerName) {
+ return MessageHeaders.ID.equals(headerName) || MessageHeaders.TIMESTAMP.equals(headerName);
+ }
+
+ /**
+ * Set the value for the given header name only if the header name is not already associated with a value.
+ */
+ public void setHeaderIfAbsent(String name, Object value) {
+ if (getHeader(name) == null) {
+ setHeader(name, value);
+ }
+ }
+
+ /**
+ * Removes all headers provided via array of 'headerPatterns'. As the name suggests
+ * the array may contain simple matching patterns for header names. Supported pattern
+ * styles are: "xxx*", "*xxx", "*xxx*" and "xxx*yyy".
+ */
+ public void removeHeaders(String... headerPatterns) {
+ List<String> headersToRemove = new ArrayList<String>();
+ for (String pattern : headerPatterns) {
+ if (StringUtils.hasLength(pattern)){
+ if (pattern.contains("*")){
+ for (String headerName : this.headers.keySet()) {
+ if (PatternMatchUtils.simpleMatch(pattern, headerName)){
+ headersToRemove.add(headerName);
+ }
+ }
+ }
+ else {
+ headersToRemove.add(pattern);
+ }
+ }
+ }
+ for (String headerToRemove : headersToRemove) {
+ removeHeader(headerToRemove);
+ }
+ }
+
+ /**
+ * Remove the value for the given header name.
+ */
+ public void removeHeader(String headerName) {
+ if (StringUtils.hasLength(headerName) && !isReadOnly(headerName)) {
+ setHeader(headerName, null);
+ }
+ }
+
+ /**
+ * Copy the name-value pairs from the provided Map. This operation will overwrite any
+ * existing values. Use { {@link #copyHeadersIfAbsent(Map)} to avoid overwriting
+ * values.
+ */
+ public void copyHeaders(Map<String, ?> headersToCopy) {
+ Set<String> keys = headersToCopy.keySet();
+ for (String key : keys) {
+ if (!isReadOnly(key)) {
+ setHeader(key, headersToCopy.get(key));
+ }
+ }
+ }
+
+ /**
+ * Copy the name-value pairs from the provided Map. This operation will <em>not</em>
+ * overwrite any existing values.
+ */
+ public void copyHeadersIfAbsent(Map<String, ?> headersToCopy) {
+ Set<String> keys = headersToCopy.keySet();
+ for (String key : keys) {
+ if (!this.isReadOnly(key)) {
+ setHeaderIfAbsent(key, headersToCopy.get(key));
+ }
+ }
+ }
+
+ public void setReplyChannel(MessageChannel replyChannel) {
+ setHeader(MessageHeaders.REPLY_CHANNEL, replyChannel);
+ }
+
+ public void setReplyChannelName(String replyChannelName) {
+ setHeader(MessageHeaders.REPLY_CHANNEL, replyChannelName);
+ }
+
+ public void setErrorChannel(MessageChannel errorChannel) {
+ setHeader(MessageHeaders.ERROR_CHANNEL, errorChannel);
+ }
+
+ public void setErrorChannelName(String errorChannelName) {
+ setHeader(MessageHeaders.ERROR_CHANNEL, errorChannelName);
+ }
+
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + " [originalHeaders=" + this.originalHeaders
+ + ", updated headers=" + this.headers + "]";
+ }
+
+} | true |
Other | spring-projects | spring-framework | 486b4101ec6675a53c1595350878a10857518331.json | Introduce MessageHeader accessor types
A new type MessageHeaderAccesssor provides read/write access to
MessageHeaders along with typed getter/setter methods along the lines
of the existing MessageBuilder methods (internally MessageBuilder
merely delegates to MessageHeaderAccessor). This class is extensible
with sub-classes expected to provide typed getter/setter methods for
specific categories of message headers.
NativeMessageHeaderAccessor is one specific sub-class that further
provides read/write access to headers from some external message
source (e.g. STOMP headers). Native headers are stored in a separate
MultiValueMap and kept under a specific key. | spring-context/src/main/java/org/springframework/messaging/support/NativeMessageHeaderAccessor.java | @@ -0,0 +1,140 @@
+/*
+ * Copyright 2002-2013 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.messaging.support;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.messaging.Message;
+import org.springframework.util.CollectionUtils;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.util.ObjectUtils;
+
+
+/**
+ * An extension of {@link MessageHeaderAccesssor} that also provides read/write access to
+ * message headers from an external message source. Native message headers are kept
+ * in a {@link MultiValueMap} under the key {@link #NATIVE_HEADERS}.
+ *
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public class NativeMessageHeaderAccessor extends MessageHeaderAccesssor {
+
+
+ public static final String NATIVE_HEADERS = "nativeHeaders";
+
+ // wrapped native headers
+ private final Map<String, List<String>> originalNativeHeaders;
+
+ // native header updates
+ private final MultiValueMap<String, String> nativeHeaders = new LinkedMultiValueMap<String, String>(4);
+
+
+ /**
+ * A constructor for creating new headers, accepting an optional native header map.
+ */
+ public NativeMessageHeaderAccessor(Map<String, List<String>> nativeHeaders) {
+ super();
+ this.originalNativeHeaders = nativeHeaders;
+ }
+
+ /**
+ * A constructor for accessing and modifying existing message headers.
+ */
+ public NativeMessageHeaderAccessor(Message<?> message) {
+ super(message);
+ this.originalNativeHeaders = initNativeHeaders(message);
+ }
+
+ private static Map<String, List<String>> initNativeHeaders(Message<?> message) {
+ if (message != null) {
+ @SuppressWarnings("unchecked")
+ Map<String, List<String>> headers = (Map<String, List<String>>) message.getHeaders().get(NATIVE_HEADERS);
+ if (headers != null) {
+ return headers;
+ }
+ }
+ return null;
+ }
+
+
+ @Override
+ public Map<String, Object> toMap() {
+ Map<String, Object> result = super.toMap();
+ result.put(NATIVE_HEADERS, toNativeHeaderMap());
+ return result;
+ }
+
+ @Override
+ public boolean isModified() {
+ return (super.isModified() || (!this.nativeHeaders.isEmpty()));
+ }
+
+ /**
+ * Return a map with native headers including original, wrapped headers (if any) plus
+ * additional header updates made through accessor methods.
+ */
+ public Map<String, List<String>> toNativeHeaderMap() {
+ Map<String, List<String>> result = new HashMap<String, List<String>>();
+ if (this.originalNativeHeaders != null) {
+ result.putAll(this.originalNativeHeaders);
+ }
+ for (String key : this.nativeHeaders.keySet()) {
+ List<String> value = this.nativeHeaders.get(key);
+ if (value == null) {
+ result.remove(key);
+ }
+ else {
+ result.put(key, value);
+ }
+ }
+ return result;
+ }
+
+ protected List<String> getNativeHeader(String headerName) {
+ if (this.nativeHeaders.containsKey(headerName)) {
+ return this.nativeHeaders.get(headerName);
+ }
+ else if (this.originalNativeHeaders != null) {
+ return this.originalNativeHeaders.get(headerName);
+ }
+ return null;
+ }
+
+ protected String getFirstNativeHeader(String headerName) {
+ List<String> values = getNativeHeader(headerName);
+ return CollectionUtils.isEmpty(values) ? null : values.get(0);
+ }
+
+ /**
+ * Set the value for the given header name. If the provided value is {@code null} the
+ * header will be removed.
+ */
+ protected void putNativeHeader(String name, List<String> value) {
+ if (!ObjectUtils.nullSafeEquals(value, getHeader(name))) {
+ this.nativeHeaders.put(name, value);
+ }
+ }
+
+ protected void setNativeHeader(String name, String value) {
+ this.nativeHeaders.set(name, value);
+ }
+
+} | true |
Other | spring-projects | spring-framework | 486b4101ec6675a53c1595350878a10857518331.json | Introduce MessageHeader accessor types
A new type MessageHeaderAccesssor provides read/write access to
MessageHeaders along with typed getter/setter methods along the lines
of the existing MessageBuilder methods (internally MessageBuilder
merely delegates to MessageHeaderAccessor). This class is extensible
with sub-classes expected to provide typed getter/setter methods for
specific categories of message headers.
NativeMessageHeaderAccessor is one specific sub-class that further
provides read/write access to headers from some external message
source (e.g. STOMP headers). Native headers are stored in a separate
MultiValueMap and kept under a specific key. | spring-websocket/src/main/java/org/springframework/web/messaging/service/AbstractPubSubMessageHandler.java | @@ -30,7 +30,7 @@
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.messaging.MessageType;
-import org.springframework.web.messaging.support.PubSubHeaderAccesssor;
+import org.springframework.web.messaging.support.WebMessageHeaderAccesssor;
/**
@@ -80,7 +80,7 @@ protected boolean canHandle(Message<?> message, MessageType messageType) {
protected boolean isDestinationAllowed(Message<?> message) {
- PubSubHeaderAccesssor headers = PubSubHeaderAccesssor.wrap(message);
+ WebMessageHeaderAccesssor headers = WebMessageHeaderAccesssor.wrap(message);
String destination = headers.getDestination();
if (destination == null) {
@@ -116,7 +116,7 @@ protected boolean isDestinationAllowed(Message<?> message) {
@Override
public final void handleMessage(Message<?> message) throws MessagingException {
- PubSubHeaderAccesssor headers = PubSubHeaderAccesssor.wrap(message);
+ WebMessageHeaderAccesssor headers = WebMessageHeaderAccesssor.wrap(message);
MessageType messageType = headers.getMessageType();
if (!canHandle(message, messageType)) { | true |
Other | spring-projects | spring-framework | 486b4101ec6675a53c1595350878a10857518331.json | Introduce MessageHeader accessor types
A new type MessageHeaderAccesssor provides read/write access to
MessageHeaders along with typed getter/setter methods along the lines
of the existing MessageBuilder methods (internally MessageBuilder
merely delegates to MessageHeaderAccessor). This class is extensible
with sub-classes expected to provide typed getter/setter methods for
specific categories of message headers.
NativeMessageHeaderAccessor is one specific sub-class that further
provides read/write access to headers from some external message
source (e.g. STOMP headers). Native headers are stored in a separate
MultiValueMap and kept under a specific key. | spring-websocket/src/main/java/org/springframework/web/messaging/service/ReactorPubSubMessageHandler.java | @@ -31,7 +31,7 @@
import org.springframework.web.messaging.PubSubChannelRegistry;
import org.springframework.web.messaging.converter.CompositeMessageConverter;
import org.springframework.web.messaging.converter.MessageConverter;
-import org.springframework.web.messaging.support.PubSubHeaderAccesssor;
+import org.springframework.web.messaging.support.WebMessageHeaderAccesssor;
import reactor.core.Reactor;
import reactor.fn.Consumer;
@@ -78,7 +78,7 @@ public void handleSubscribe(Message<?> message) {
logger.debug("Subscribe " + message);
}
- PubSubHeaderAccesssor headers = PubSubHeaderAccesssor.wrap(message);
+ WebMessageHeaderAccesssor headers = WebMessageHeaderAccesssor.wrap(message);
String subscriptionId = headers.getSubscriptionId();
BroadcastingConsumer consumer = new BroadcastingConsumer(subscriptionId);
@@ -107,7 +107,7 @@ public void handlePublish(Message<?> message) {
try {
// Convert to byte[] payload before the fan-out
- PubSubHeaderAccesssor headers = PubSubHeaderAccesssor.wrap(message);
+ WebMessageHeaderAccesssor headers = WebMessageHeaderAccesssor.wrap(message);
byte[] payload = payloadConverter.convertToPayload(message.getPayload(), headers.getContentType());
Message<?> m = MessageBuilder.withPayload(payload).copyHeaders(message.getHeaders()).build();
@@ -120,7 +120,7 @@ public void handlePublish(Message<?> message) {
@Override
public void handleDisconnect(Message<?> message) {
- PubSubHeaderAccesssor headers = PubSubHeaderAccesssor.wrap(message);
+ WebMessageHeaderAccesssor headers = WebMessageHeaderAccesssor.wrap(message);
removeSubscriptions(headers.getSessionId());
}
@@ -149,11 +149,11 @@ public void accept(Event<Message<?>> event) {
Message<?> sentMessage = event.getData();
- PubSubHeaderAccesssor headers = PubSubHeaderAccesssor.wrap(sentMessage);
+ WebMessageHeaderAccesssor headers = WebMessageHeaderAccesssor.wrap(sentMessage);
headers.setSubscriptionId(this.subscriptionId);
Message<?> clientMessage = MessageBuilder.withPayload(
- sentMessage.getPayload()).copyHeaders(headers.toHeaders()).build();
+ sentMessage.getPayload()).copyHeaders(headers.toMap()).build();
clientChannel.send(clientMessage);
} | true |
Other | spring-projects | spring-framework | 486b4101ec6675a53c1595350878a10857518331.json | Introduce MessageHeader accessor types
A new type MessageHeaderAccesssor provides read/write access to
MessageHeaders along with typed getter/setter methods along the lines
of the existing MessageBuilder methods (internally MessageBuilder
merely delegates to MessageHeaderAccessor). This class is extensible
with sub-classes expected to provide typed getter/setter methods for
specific categories of message headers.
NativeMessageHeaderAccessor is one specific sub-class that further
provides read/write access to headers from some external message
source (e.g. STOMP headers). Native headers are stored in a separate
MultiValueMap and kept under a specific key. | spring-websocket/src/main/java/org/springframework/web/messaging/service/method/AnnotationPubSubMessageHandler.java | @@ -45,7 +45,7 @@
import org.springframework.web.messaging.converter.MessageConverter;
import org.springframework.web.messaging.service.AbstractPubSubMessageHandler;
import org.springframework.web.messaging.support.MessageHolder;
-import org.springframework.web.messaging.support.PubSubHeaderAccesssor;
+import org.springframework.web.messaging.support.WebMessageHeaderAccesssor;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.HandlerMethodSelector;
@@ -185,7 +185,7 @@ public void handleUnsubscribe(Message<?> message) {
private void handleMessageInternal(final Message<?> message, Map<MappingInfo, HandlerMethod> handlerMethods) {
- PubSubHeaderAccesssor headers = PubSubHeaderAccesssor.wrap(message);
+ WebMessageHeaderAccesssor headers = WebMessageHeaderAccesssor.wrap(message);
String destination = headers.getDestination();
HandlerMethod match = getHandlerMethod(destination, handlerMethods); | true |
Other | spring-projects | spring-framework | 486b4101ec6675a53c1595350878a10857518331.json | Introduce MessageHeader accessor types
A new type MessageHeaderAccesssor provides read/write access to
MessageHeaders along with typed getter/setter methods along the lines
of the existing MessageBuilder methods (internally MessageBuilder
merely delegates to MessageHeaderAccessor). This class is extensible
with sub-classes expected to provide typed getter/setter methods for
specific categories of message headers.
NativeMessageHeaderAccessor is one specific sub-class that further
provides read/write access to headers from some external message
source (e.g. STOMP headers). Native headers are stored in a separate
MultiValueMap and kept under a specific key. | spring-websocket/src/main/java/org/springframework/web/messaging/service/method/MessageBodyArgumentResolver.java | @@ -25,7 +25,7 @@
import org.springframework.web.messaging.converter.CompositeMessageConverter;
import org.springframework.web.messaging.converter.MessageConversionException;
import org.springframework.web.messaging.converter.MessageConverter;
-import org.springframework.web.messaging.support.PubSubHeaderAccesssor;
+import org.springframework.web.messaging.support.WebMessageHeaderAccesssor;
/**
@@ -52,7 +52,7 @@ public Object resolveArgument(MethodParameter parameter, Message<?> message) thr
Object arg = null;
MessageBody annot = parameter.getParameterAnnotation(MessageBody.class);
- MediaType contentType = (MediaType) message.getHeaders().get(PubSubHeaderAccesssor.CONTENT_TYPE);
+ MediaType contentType = (MediaType) message.getHeaders().get(WebMessageHeaderAccesssor.CONTENT_TYPE);
if (annot == null || annot.required()) {
Class<?> sourceType = message.getPayload().getClass(); | true |