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 | 1e62ad8665bb0f4138e140974108d693a20ee287.json | Add beforeConcurrentHandling support
Previously CallableProcessingInterceptor and
DeferredResultProcessingInterceptor did not have support for capturing
the state of the original Thread just prior to processing. This made it
difficult to transfer the state of one Thread (i.e. ThreadLocal) to the
Thread used to process the Callable.
This commit adds a new method to CallableProcessingInterceptor and
DeferredResultProcessingInterceptor named beforeConcurrentHandling
which will be invoked on the original Thread used to submit the Callable
or DeferredResult. This means the state of the original Thread can be
captured in beforeConcurrentHandling and transfered to the new Thread
in preProcess.
Issue: SPR-10052 | spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptorAdapter.java | @@ -22,10 +22,17 @@
* interface for simplified implementation of individual methods.
*
* @author Rossen Stoyanchev
+ * @author Rob Winch
* @since 3.2
*/
public abstract class DeferredResultProcessingInterceptorAdapter implements DeferredResultProcessingInterceptor {
+ /**
+ * This implementation is empty.
+ */
+ public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception {
+ }
+
/**
* This implementation is empty.
*/ | true |
Other | spring-projects | spring-framework | 1e62ad8665bb0f4138e140974108d693a20ee287.json | Add beforeConcurrentHandling support
Previously CallableProcessingInterceptor and
DeferredResultProcessingInterceptor did not have support for capturing
the state of the original Thread just prior to processing. This made it
difficult to transfer the state of one Thread (i.e. ThreadLocal) to the
Thread used to process the Callable.
This commit adds a new method to CallableProcessingInterceptor and
DeferredResultProcessingInterceptor named beforeConcurrentHandling
which will be invoked on the original Thread used to submit the Callable
or DeferredResult. This means the state of the original Thread can be
captured in beforeConcurrentHandling and transfered to the new Thread
in preProcess.
Issue: SPR-10052 | spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java | @@ -249,12 +249,13 @@ public void clearConcurrentResult() {
* @param callable a unit of work to be executed asynchronously
* @param processingContext additional context to save that can be accessed
* via {@link #getConcurrentResultContext()}
+ * @throws Exception If concurrent processing failed to start
*
* @see #getConcurrentResult()
* @see #getConcurrentResultContext()
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
- public void startCallableProcessing(final Callable<?> callable, Object... processingContext) {
+ public void startCallableProcessing(final Callable<?> callable, Object... processingContext) throws Exception {
Assert.notNull(callable, "Callable must not be null");
startCallableProcessing(new WebAsyncTask(callable), processingContext);
}
@@ -267,8 +268,9 @@ public void startCallableProcessing(final Callable<?> callable, Object... proces
* @param webAsyncTask an WebAsyncTask containing the target {@code Callable}
* @param processingContext additional context to save that can be accessed
* via {@link #getConcurrentResultContext()}
+ * @throws Exception If concurrent processing failed to start
*/
- public void startCallableProcessing(final WebAsyncTask<?> webAsyncTask, Object... processingContext) {
+ public void startCallableProcessing(final WebAsyncTask<?> webAsyncTask, Object... processingContext) throws Exception {
Assert.notNull(webAsyncTask, "WebAsyncTask must not be null");
Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null");
@@ -306,6 +308,8 @@ public void run() {
}
});
+ interceptorChain.applyBeforeConcurrentHandling(asyncWebRequest, callable);
+
startAsyncProcessing(processingContext);
this.taskExecutor.submit(new Runnable() {
@@ -356,12 +360,13 @@ private void setConcurrentResultAndDispatch(Object result) {
* @param deferredResult the DeferredResult instance to initialize
* @param processingContext additional context to save that can be accessed
* via {@link #getConcurrentResultContext()}
+ * @throws Exception If concurrent processing failed to start
*
* @see #getConcurrentResult()
* @see #getConcurrentResultContext()
*/
public void startDeferredResultProcessing(
- final DeferredResult<?> deferredResult, Object... processingContext) {
+ final DeferredResult<?> deferredResult, Object... processingContext) throws Exception {
Assert.notNull(deferredResult, "DeferredResult must not be null");
Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null");
@@ -395,6 +400,8 @@ public void run() {
}
});
+ interceptorChain.applyBeforeConcurrentHandling(asyncWebRequest, deferredResult);
+
startAsyncProcessing(processingContext);
try { | true |
Other | spring-projects | spring-framework | 1e62ad8665bb0f4138e140974108d693a20ee287.json | Add beforeConcurrentHandling support
Previously CallableProcessingInterceptor and
DeferredResultProcessingInterceptor did not have support for capturing
the state of the original Thread just prior to processing. This made it
difficult to transfer the state of one Thread (i.e. ThreadLocal) to the
Thread used to process the Callable.
This commit adds a new method to CallableProcessingInterceptor and
DeferredResultProcessingInterceptor named beforeConcurrentHandling
which will be invoked on the original Thread used to submit the Callable
or DeferredResult. This means the state of the original Thread can be
captured in beforeConcurrentHandling and transfered to the new Thread
in preProcess.
Issue: SPR-10052 | spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java | @@ -66,7 +66,7 @@ public void setUp() {
}
@Test
- public void startAsyncProcessingWithoutAsyncWebRequest() {
+ public void startAsyncProcessingWithoutAsyncWebRequest() throws Exception {
WebAsyncManager manager = WebAsyncUtils.getAsyncManager(new MockHttpServletRequest());
try {
@@ -118,6 +118,7 @@ public void startCallableProcessing() throws Exception {
Callable<Object> task = new StubCallable(concurrentResult);
CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class);
+ interceptor.beforeConcurrentHandling(this.asyncWebRequest, task);
interceptor.preProcess(this.asyncWebRequest, task);
interceptor.postProcess(this.asyncWebRequest, task, new Integer(concurrentResult));
replay(interceptor);
@@ -140,6 +141,7 @@ public void startCallableProcessingCallableException() throws Exception {
Callable<Object> task = new StubCallable(concurrentResult);
CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class);
+ interceptor.beforeConcurrentHandling(this.asyncWebRequest, task);
interceptor.preProcess(this.asyncWebRequest, task);
interceptor.postProcess(this.asyncWebRequest, task, concurrentResult);
replay(interceptor);
@@ -155,13 +157,42 @@ public void startCallableProcessingCallableException() throws Exception {
verify(interceptor, this.asyncWebRequest);
}
+ @Test
+ public void startCallableProcessingBeforeConcurrentHandlingException() throws Exception {
+ Callable<Object> task = new StubCallable(21);
+ Exception exception = new Exception();
+
+ CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class);
+ interceptor.beforeConcurrentHandling(this.asyncWebRequest, task);
+ expectLastCall().andThrow(exception);
+ replay(interceptor);
+
+ this.asyncWebRequest.addTimeoutHandler((Runnable) notNull());
+ this.asyncWebRequest.addCompletionHandler((Runnable) notNull());
+ replay(this.asyncWebRequest);
+
+ this.asyncManager.registerCallableInterceptor("interceptor", interceptor);
+
+ try {
+ this.asyncManager.startCallableProcessing(task);
+ fail("Expected Exception");
+ }catch(Exception e) {
+ assertEquals(exception, e);
+ }
+
+ assertFalse(this.asyncManager.hasConcurrentResult());
+
+ verify(this.asyncWebRequest, interceptor);
+ }
+
@Test
public void startCallableProcessingPreProcessException() throws Exception {
Callable<Object> task = new StubCallable(21);
Exception exception = new Exception();
CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class);
+ interceptor.beforeConcurrentHandling(this.asyncWebRequest, task);
interceptor.preProcess(this.asyncWebRequest, task);
expectLastCall().andThrow(exception);
replay(interceptor);
@@ -184,6 +215,7 @@ public void startCallableProcessingPostProcessException() throws Exception {
Exception exception = new Exception();
CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class);
+ interceptor.beforeConcurrentHandling(this.asyncWebRequest, task);
interceptor.preProcess(this.asyncWebRequest, task);
interceptor.postProcess(this.asyncWebRequest, task, 21);
expectLastCall().andThrow(exception);
@@ -207,11 +239,13 @@ public void startCallableProcessingPostProcessContinueAfterException() throws Ex
Exception exception = new Exception();
CallableProcessingInterceptor interceptor1 = createMock(CallableProcessingInterceptor.class);
+ interceptor1.beforeConcurrentHandling(this.asyncWebRequest, task);
interceptor1.preProcess(this.asyncWebRequest, task);
interceptor1.postProcess(this.asyncWebRequest, task, 21);
replay(interceptor1);
CallableProcessingInterceptor interceptor2 = createMock(CallableProcessingInterceptor.class);
+ interceptor2.beforeConcurrentHandling(this.asyncWebRequest, task);
interceptor2.preProcess(this.asyncWebRequest, task);
interceptor2.postProcess(this.asyncWebRequest, task, 21);
expectLastCall().andThrow(exception);
@@ -231,7 +265,7 @@ public void startCallableProcessingPostProcessContinueAfterException() throws Ex
}
@Test
- public void startCallableProcessingWithAsyncTask() {
+ public void startCallableProcessingWithAsyncTask() throws Exception {
AsyncTaskExecutor executor = createMock(AsyncTaskExecutor.class);
expect(executor.submit((Runnable) notNull())).andReturn(null);
@@ -251,7 +285,7 @@ public void startCallableProcessingWithAsyncTask() {
}
@Test
- public void startCallableProcessingNullInput() {
+ public void startCallableProcessingNullInput() throws Exception {
try {
this.asyncManager.startCallableProcessing((Callable<?>) null);
fail("Expected exception");
@@ -268,6 +302,7 @@ public void startDeferredResultProcessing() throws Exception {
String concurrentResult = "abc";
DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class);
+ interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult);
interceptor.preProcess(this.asyncWebRequest, deferredResult);
interceptor.postProcess(asyncWebRequest, deferredResult, concurrentResult);
replay(interceptor);
@@ -284,13 +319,44 @@ public void startDeferredResultProcessing() throws Exception {
verify(this.asyncWebRequest, interceptor);
}
+ @Test
+ public void startDeferredResultProcessingBeforeConcurrentHandlingException() throws Exception {
+
+ DeferredResult<Integer> deferredResult = new DeferredResult<Integer>();
+ Exception exception = new Exception();
+
+ DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class);
+ interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult);
+ expectLastCall().andThrow(exception);
+ replay(interceptor);
+
+ this.asyncWebRequest.addTimeoutHandler((Runnable) notNull());
+ this.asyncWebRequest.addCompletionHandler((Runnable) notNull());
+ replay(this.asyncWebRequest);
+
+ this.asyncManager.registerDeferredResultInterceptor("interceptor", interceptor);
+
+ try {
+ this.asyncManager.startDeferredResultProcessing(deferredResult);
+ fail("Expected Exception");
+ }
+ catch(Exception success) {
+ assertEquals(exception, success);
+ }
+
+ assertFalse(this.asyncManager.hasConcurrentResult());
+
+ verify(this.asyncWebRequest, interceptor);
+ }
+
@Test
public void startDeferredResultProcessingPreProcessException() throws Exception {
DeferredResult<Integer> deferredResult = new DeferredResult<Integer>();
Exception exception = new Exception();
DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class);
+ interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult);
interceptor.preProcess(this.asyncWebRequest, deferredResult);
expectLastCall().andThrow(exception);
replay(interceptor);
@@ -313,6 +379,7 @@ public void startDeferredResultProcessingPostProcessException() throws Exception
Exception exception = new Exception();
DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class);
+ interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult);
interceptor.preProcess(this.asyncWebRequest, deferredResult);
interceptor.postProcess(this.asyncWebRequest, deferredResult, 25);
expectLastCall().andThrow(exception);
@@ -330,7 +397,7 @@ public void startDeferredResultProcessingPostProcessException() throws Exception
}
@Test
- public void startDeferredResultProcessingNullInput() {
+ public void startDeferredResultProcessingNullInput() throws Exception {
try {
this.asyncManager.startDeferredResultProcessing((DeferredResult<?>) null);
fail("Expected exception"); | true |
Other | spring-projects | spring-framework | 1e62ad8665bb0f4138e140974108d693a20ee287.json | Add beforeConcurrentHandling support
Previously CallableProcessingInterceptor and
DeferredResultProcessingInterceptor did not have support for capturing
the state of the original Thread just prior to processing. This made it
difficult to transfer the state of one Thread (i.e. ThreadLocal) to the
Thread used to process the Callable.
This commit adds a new method to CallableProcessingInterceptor and
DeferredResultProcessingInterceptor named beforeConcurrentHandling
which will be invoked on the original Thread used to submit the Callable
or DeferredResult. This means the state of the original Thread can be
captured in beforeConcurrentHandling and transfered to the new Thread
in preProcess.
Issue: SPR-10052 | spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTimeoutTests.java | @@ -80,6 +80,7 @@ public void startCallableProcessingTimeoutAndComplete() throws Exception {
StubCallable callable = new StubCallable();
CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class);
+ interceptor.beforeConcurrentHandling(this.asyncWebRequest, callable);
expect(interceptor.handleTimeout(this.asyncWebRequest, callable)).andReturn(RESULT_NONE);
interceptor.afterCompletion(this.asyncWebRequest, callable);
replay(interceptor);
@@ -123,6 +124,7 @@ public void startCallableProcessingTimeoutAndResumeThroughInterceptor() throws E
StubCallable callable = new StubCallable();
CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class);
+ interceptor.beforeConcurrentHandling(this.asyncWebRequest, callable);
expect(interceptor.handleTimeout(this.asyncWebRequest, callable)).andReturn(22);
replay(interceptor);
@@ -145,6 +147,7 @@ public void startCallableProcessingAfterTimeoutException() throws Exception {
Exception exception = new Exception();
CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class);
+ interceptor.beforeConcurrentHandling(this.asyncWebRequest, callable);
expect(interceptor.handleTimeout(this.asyncWebRequest, callable)).andThrow(exception);
replay(interceptor);
@@ -166,6 +169,7 @@ public void startDeferredResultProcessingTimeoutAndComplete() throws Exception {
DeferredResult<Integer> deferredResult = new DeferredResult<Integer>();
DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class);
+ interceptor.beforeConcurrentHandling(this.asyncWebRequest, deferredResult);
interceptor.preProcess(this.asyncWebRequest, deferredResult);
expect(interceptor.handleTimeout(this.asyncWebRequest, deferredResult)).andReturn(true);
interceptor.afterCompletion(this.asyncWebRequest, deferredResult); | true |
Other | spring-projects | spring-framework | 0d73d199ec645f6d332d3283b72a531b26575cf6.json | Reset MBean Servers after JRuby and JMX tests
Refactor MBean Server reset code from MBeanServerFactoryBeanTests
and reuse in AdvisedJRubyScriptFactoryTests and
AbstractMBeanServerTests.
Issue: SPR-9288 | spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java | @@ -25,17 +25,18 @@
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
+import org.springframework.util.MBeanTestUtils;
/**
* <strong>Note:</strong> the JMX test suite requires the presence of the
* <code>jmxremote_optional.jar</code> in your classpath. Thus, if you
* run into the <em>"Unsupported protocol: jmxmp"</em> error, you will
* need to download the
- * <a href="http://www.oracle.com/technetwork/java/javase/tech/download-jsp-141676.html">JMX Remote API 1.0.1_04 Reference Implementation</a>
+ * <a href="http://www.oracle.com/technetwork/java/javase/tech/download-jsp-141676.html">JMX Remote API 1.0.1_04 Reference Implementation</a>
* from Oracle and extract <code>jmxremote_optional.jar</code> into your
* classpath, for example in the <code>lib/ext</code> folder of your JVM.
* See also <a href="https://issuetracker.springsource.com/browse/EBR-349">EBR-349</a>.
- *
+ *
* @author Rob Harrop
* @author Juergen Hoeller
* @author Sam Brannen
@@ -67,8 +68,9 @@ protected void tearDown() throws Exception {
onTearDown();
}
- private void releaseServer() {
+ private void releaseServer() throws Exception {
MBeanServerFactory.releaseMBeanServer(getServer());
+ MBeanTestUtils.resetMBeanServers();
}
protected void onTearDown() throws Exception { | true |
Other | spring-projects | spring-framework | 0d73d199ec645f6d332d3283b72a531b26575cf6.json | Reset MBean Servers after JRuby and JMX tests
Refactor MBean Server reset code from MBeanServerFactoryBeanTests
and reuse in AdvisedJRubyScriptFactoryTests and
AbstractMBeanServerTests.
Issue: SPR-9288 | spring-context/src/test/java/org/springframework/jmx/support/MBeanServerFactoryBeanTests.java | @@ -17,14 +17,15 @@
package org.springframework.jmx.support;
import java.lang.management.ManagementFactory;
-import java.lang.reflect.Field;
import java.util.List;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import junit.framework.TestCase;
+import org.springframework.util.MBeanTestUtils;
+
/**
* @author Rob Harrop
* @author Juergen Hoeller
@@ -34,26 +35,12 @@ public class MBeanServerFactoryBeanTests extends TestCase {
@Override
protected void setUp() throws Exception {
- resetPlatformManager();
+ MBeanTestUtils.resetMBeanServers();
}
@Override
protected void tearDown() throws Exception {
- resetPlatformManager();
- }
-
- /**
- * Resets MBeanServerFactory and ManagementFactory to a known consistent state.
- * This involves releasing all currently registered MBeanServers and resetting
- * the platformMBeanServer to null.
- */
- private void resetPlatformManager() throws Exception {
- for (MBeanServer server : MBeanServerFactory.findMBeanServer(null)) {
- MBeanServerFactory.releaseMBeanServer(server);
- }
- Field field = ManagementFactory.class.getDeclaredField("platformMBeanServer");
- field.setAccessible(true);
- field.set(null, null);
+ MBeanTestUtils.resetMBeanServers();
}
public void testGetObject() throws Exception { | true |
Other | spring-projects | spring-framework | 0d73d199ec645f6d332d3283b72a531b26575cf6.json | Reset MBean Servers after JRuby and JMX tests
Refactor MBean Server reset code from MBeanServerFactoryBeanTests
and reuse in AdvisedJRubyScriptFactoryTests and
AbstractMBeanServerTests.
Issue: SPR-9288 | spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests.java | @@ -16,13 +16,16 @@
package org.springframework.scripting.jruby;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import org.junit.After;
import org.junit.Test;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scripting.Messenger;
+import org.springframework.util.MBeanTestUtils;
import test.advice.CountingBeforeAdvice;
@@ -31,41 +34,52 @@
* @author Chris Beams
*/
public final class AdvisedJRubyScriptFactoryTests {
-
+
private static final Class<?> CLASS = AdvisedJRubyScriptFactoryTests.class;
private static final String CLASSNAME = CLASS.getSimpleName();
-
+
private static final String FACTORYBEAN_CONTEXT = CLASSNAME + "-factoryBean.xml";
private static final String APC_CONTEXT = CLASSNAME + "-beanNameAutoProxyCreator.xml";
+ @After
+ public void resetMBeanServers() throws Exception {
+ MBeanTestUtils.resetMBeanServers();
+ }
+
@Test
public void testAdviseWithProxyFactoryBean() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(FACTORYBEAN_CONTEXT, CLASS);
+ try {
+ Messenger bean = (Messenger) ctx.getBean("messenger");
+ assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean));
+ assertTrue("Bean is not an Advised object", bean instanceof Advised);
- Messenger bean = (Messenger) ctx.getBean("messenger");
- assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean));
- assertTrue("Bean is not an Advised object", bean instanceof Advised);
-
- CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice");
- assertEquals(0, advice.getCalls());
- bean.getMessage();
- assertEquals(1, advice.getCalls());
+ CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice");
+ assertEquals(0, advice.getCalls());
+ bean.getMessage();
+ assertEquals(1, advice.getCalls());
+ } finally {
+ ctx.close();
+ }
}
@Test
public void testAdviseWithBeanNameAutoProxyCreator() {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext(APC_CONTEXT, CLASS);
+ try {
+ Messenger bean = (Messenger) ctx.getBean("messenger");
+ assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean));
+ assertTrue("Bean is not an Advised object", bean instanceof Advised);
- Messenger bean = (Messenger) ctx.getBean("messenger");
- assertTrue("Bean is not a proxy", AopUtils.isAopProxy(bean));
- assertTrue("Bean is not an Advised object", bean instanceof Advised);
-
- CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice");
- assertEquals(0, advice.getCalls());
- bean.getMessage();
- assertEquals(1, advice.getCalls());
+ CountingBeforeAdvice advice = (CountingBeforeAdvice) ctx.getBean("advice");
+ assertEquals(0, advice.getCalls());
+ bean.getMessage();
+ assertEquals(1, advice.getCalls());
+ } finally {
+ ctx.close();
+ }
}
} | true |
Other | spring-projects | spring-framework | 0d73d199ec645f6d332d3283b72a531b26575cf6.json | Reset MBean Servers after JRuby and JMX tests
Refactor MBean Server reset code from MBeanServerFactoryBeanTests
and reuse in AdvisedJRubyScriptFactoryTests and
AbstractMBeanServerTests.
Issue: SPR-9288 | spring-context/src/test/java/org/springframework/util/MBeanTestUtils.java | @@ -0,0 +1,46 @@
+/*
+ * Copyright 2002-2012 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.util;
+
+import java.lang.management.ManagementFactory;
+import java.lang.reflect.Field;
+
+import javax.management.MBeanServer;
+import javax.management.MBeanServerFactory;
+
+/**
+ * Utilities for MBean tests.
+ *
+ * @author Phillip Webb
+ */
+public class MBeanTestUtils {
+
+ /**
+ * Resets MBeanServerFactory and ManagementFactory to a known consistent state.
+ * This involves releasing all currently registered MBeanServers and resetting
+ * the platformMBeanServer to null.
+ */
+ public static void resetMBeanServers() throws Exception {
+ for (MBeanServer server : MBeanServerFactory.findMBeanServer(null)) {
+ MBeanServerFactory.releaseMBeanServer(server);
+ }
+ Field field = ManagementFactory.class.getDeclaredField("platformMBeanServer");
+ field.setAccessible(true);
+ field.set(null, null);
+ }
+
+} | true |
Other | spring-projects | spring-framework | dfdb31715fb4e972391dc477a0cf0ba3d440e8f7.json | Fix -XX:MaxHeapSize setting for Windows | build.gradle | @@ -852,7 +852,7 @@ configure(rootProject) {
doLast() {
def gradleOpts = "-XX:MaxPermSize=1024m -Xmx1024m"
- def gradleBatOpts = "$gradleOpts -XX:MaxHeapSize=256"
+ def gradleBatOpts = "$gradleOpts -XX:MaxHeapSize=256m"
File wrapperFile = file('gradlew')
wrapperFile.text = wrapperFile.text.replace("DEFAULT_JVM_OPTS=",
"GRADLE_OPTS=\"$gradleOpts \$GRADLE_OPTS\"\nDEFAULT_JVM_OPTS=") | false |
Other | spring-projects | spring-framework | 5cbc5b19019b1b78312d34a58ec7e170b28cc944.json | Release version 3.2.0.RC2 | gradle.properties | @@ -1,2 +1,2 @@
-version=3.2.0.BUILD-SNAPSHOT
previousVersion=3.2.0.RC1
+version=3.2.0.RC2 | false |
Other | spring-projects | spring-framework | b43bc8659aa9d0da6598b3e2385af1a2496cb55e.json | Remove unused imports | spring-aop/src/main/java/org/springframework/aop/support/AbstractRegexpMethodPointcut.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2012 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,8 +16,6 @@
package org.springframework.aop.support;
-import java.io.IOException;
-import java.io.ObjectInputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays; | true |
Other | spring-projects | spring-framework | b43bc8659aa9d0da6598b3e2385af1a2496cb55e.json | Remove unused imports | spring-aop/src/main/java/org/springframework/aop/support/AopUtils.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2010 the original author or authors.
+ * Copyright 2002-2012 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.
@@ -23,8 +23,6 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
import org.springframework.aop.Advisor;
import org.springframework.aop.AopInvocationException; | true |
Other | spring-projects | spring-framework | 79edf627dbfc4eff06ac3283d5c010885912feab.json | Fix failing test from last commit
Issue: SPR-9917 | spring-test-mvc/src/main/java/org/springframework/test/web/client/RequestMatcherClientHttpRequest.java | @@ -73,7 +73,7 @@ public ClientHttpResponse executeInternal() throws IOException {
setResponse(this.responseCreator.createResponse(this));
- return super.execute();
+ return super.executeInternal();
}
} | false |
Other | spring-projects | spring-framework | b1040af22e215eb3157dfe7513e13c713574c2aa.json | Update maximum width of reference HTML
This change upgrade the framework to consume the newly-published
docbook-reference-plugin version 0.2.1 containing a maximum width
for the HTML reference guide. | build.gradle | @@ -3,7 +3,7 @@ buildscript {
maven { url 'http://repo.springsource.org/plugins-release' }
}
dependencies {
- classpath 'org.springframework.build.gradle:docbook-reference-plugin:0.2.0'
+ classpath 'org.springframework.build.gradle:docbook-reference-plugin:0.2.1'
}
}
| false |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/aop.xml | @@ -2152,8 +2152,8 @@ public class SimpleProfiler {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<lineannotation><!-- this is the object that will be proxied by Spring's AOP infrastructure --></lineannotation>
<bean id="fooService" class="x.y.service.DefaultFooService"/>
@@ -3310,9 +3310,9 @@ public class ProfilingAspect {
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/context/spring-context.xsd">
<lineannotation><!-- a service object; we will be profiling its methods --></lineannotation>
<bean id="entitlementCalculationService"
@@ -3541,9 +3541,9 @@ public class AppConfig {
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/context/spring-context.xsd">
<context:load-time-weaver/>
@@ -3655,9 +3655,9 @@ public class AppConfig implements LoadTimeWeavingConfigurer {
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/context/spring-context.xsd">
<context:load-time-weaver
weaver-class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver"/> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/beans-annotation-config.xml | @@ -68,9 +68,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<lineannotation>xmlns:context="http://www.springframework.org/schema/context"</lineannotation>
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/context/spring-context.xsd">
<lineannotation><context:annotation-config/></lineannotation>
@@ -362,9 +362,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
@@ -479,9 +479,9 @@ public @interface Genre {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
@@ -602,9 +602,9 @@ public @interface MovieQualifier {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
| true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/beans-classpath-scanning.xml | @@ -113,9 +113,9 @@ public class JpaMovieFinder implements MovieFinder {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.example"/>
| true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/beans-dependencies.xml | @@ -537,7 +537,7 @@ public class ExampleBean {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
@@ -973,7 +973,7 @@ support=support@example.co.uk</programlisting>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="classic" class="com.example.ExampleBean">
<property name="email" value="foo@bar.com"/>
@@ -996,7 +996,7 @@ support=support@example.co.uk</programlisting>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="john-classic" class="com.example.Person">
<property name="name" value="John Doe"/> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/beans-extension-points.xml | @@ -180,9 +180,9 @@ public class InstantiationTracingBeanPostProcessor implements BeanPostProcessor
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/lang
- http://www.springframework.org/schema/lang/spring-lang-3.0.xsd">
+ http://www.springframework.org/schema/lang/spring-lang.xsd">
<lang:groovy id="messenger"
script-source="classpath:org/springframework/scripting/groovy/Messenger.groovy"> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/beans-scopes.xml | @@ -393,9 +393,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+ http://www.springframework.org/schema/aop/spring-aop.xsd">
<lineannotation><!-- an HTTP Session-scoped bean exposed as a proxy --></lineannotation>
<bean id="userPreferences" class="com.foo.UserPreferences" scope="session">
@@ -640,9 +640,9 @@ beanFactory.registerScope("thread", threadScope);</programlisting>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+ http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes"> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/beans.xml | @@ -187,7 +187,7 @@ The footnote should x-ref to first section in that chapter but I can't find the
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
@@ -241,7 +241,7 @@ The footnote should x-ref to first section in that chapter but I can't find the
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- services -->
@@ -264,7 +264,7 @@ The footnote should x-ref to first section in that chapter but I can't find the
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountDao"
class="org.springframework.samples.jpetstore.dao.ibatis.SqlMapAccountDao"> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/dynamic-languages.xml | @@ -130,8 +130,8 @@ class GroovyMessenger implements Messenger {
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd">
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd">
]]><lineannotation><!-- this is the bean definition for the Groovy-backed Messenger implementation --></lineannotation><![CDATA[
<lang:groovy id="messenger" script-source="classpath:Messenger.groovy">
@@ -1041,8 +1041,8 @@ class TestBeanValidator implements Validator {
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd">
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd">
<lang:groovy id="messenger" script-source="classpath:Messenger.groovy" ]]><lineannotation>scope="prototype"</lineannotation><![CDATA[>
<lang:property name="message" value="I Can Do The RoboCop" /> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/jdbc.xml | @@ -463,9 +463,9 @@ private static final class ActorMapper implements RowMapper<Actor> {
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="corporateEventDao" class="com.example.JdbcCorporateEventDao">
<property name="dataSource" ref="dataSource"/>
@@ -512,9 +512,9 @@ public class JdbcCorporateEventDao implements CorporateEventDao {
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Scans within the base package of the application for @Components to configure as beans -->
<context:component-scan base-package="org.springframework.docs.test" /> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/jms.xml | @@ -922,8 +922,8 @@ public interface SessionAwareMessageListener {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<emphasis role="bold">xmlns:jms="http://www.springframework.org/schema/jms"</emphasis>
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-<emphasis role="bold">http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd"</emphasis>>
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+<emphasis role="bold">http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd"</emphasis>>
<lineannotation><!-- <bean/> definitions here --></lineannotation>
| true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/mail.xml | @@ -376,7 +376,7 @@ public class SimpleRegistrationService implements RegistrationService {
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="mail.csonth.gov.uk"/> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/mvc.xml | @@ -749,9 +749,9 @@ public class HelloWorldController {
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.springframework.samples.petclinic.web"/>
@@ -4315,7 +4315,7 @@ public class ErrorController {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans.xsd">
<lineannotation><!-- this bean with the well known name generates view names for us --></lineannotation>
<bean id="viewNameTranslator"
@@ -4567,9 +4567,9 @@ public class WebConfig {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
+ http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
@@ -4713,7 +4713,7 @@ public class WebConfig extends WebMvcConfigurerAdapter {
<para>To customize the default configuration of
<literal><mvc:annotation-driven /></literal> check what
attributes and sub-elements it supports. You can view the
- <link xl:href="http://static.springsource.org/schema/mvc/spring-mvc-3.1.xsd">Spring MVC XML schema</link>
+ <link xl:href="http://static.springsource.org/schema/mvc/spring-mvc.xsd">Spring MVC XML schema</link>
or use the code completion feature of your IDE to discover
what attributes and sub-elements are available.
The sample below shows a subset of what is available:</para> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/orm.xml | @@ -419,11 +419,11 @@ TR: REVISED, PLS REVIEW.-->This declarative transaction capability allows you
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+ http://www.springframework.org/schema/aop/spring-aop.xsd">
<lineannotation><!-- SessionFactory, DataSource, etc. omitted --></lineannotation>
@@ -512,11 +512,11 @@ TR: REVISED, PLS REVIEW.-->This declarative transaction capability allows you
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+ http://www.springframework.org/schema/aop/spring-aop.xsd">
<lineannotation><!-- SessionFactory, DataSource, etc. omitted --></lineannotation>
@@ -1155,11 +1155,11 @@ TR: OK AS IS. Two different callback methhods - one is Spring's (*afterCompletio
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+ http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="myTxManager" class="org.springframework.orm.jdo.JdoTransactionManager">
<property name="persistenceManagerFactory" ref="myPmf"/>
@@ -1736,11 +1736,11 @@ TR: REVISED, PLS REVIEW. Should be *inside your war*. --><!-- </para>
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+ http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf"/> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/oxm.xml | @@ -319,9 +319,9 @@ public class Application {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
]]><emphasis role="bold"><![CDATA[xmlns:oxm="http://www.springframework.org/schema/oxm"]]></emphasis>
<![CDATA[xsi:schemaLocation="http://www.springframework.org/schema/beans
- ]]><![CDATA[http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ ]]><![CDATA[http://www.springframework.org/schema/beans/spring-beans.xsd
]]><emphasis role="bold"><![CDATA[http://www.springframework.org/schema/oxm
- ]]><![CDATA[http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd"]]></emphasis><![CDATA[>
+ ]]><![CDATA[http://www.springframework.org/schema/oxm/spring-oxm.xsd"]]></emphasis><![CDATA[>
]]></programlisting>
<para>
Currently, the following tags are available: | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/portlet.xml | @@ -1298,7 +1298,7 @@ public class FileUploadBean {
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
@@ -1350,9 +1350,9 @@ public class FileUploadBean {
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
+ http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.springframework.samples.petportal.portlet"/>
| true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/remoting.xml | @@ -1042,7 +1042,7 @@ public class SimpleCheckingAccountService implements CheckingAccountService {
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="tcp://ep-t43:61616"/>
@@ -1064,7 +1064,7 @@ public class SimpleCheckingAccountService implements CheckingAccountService {
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="checkingAccountService"
class="org.springframework.jms.remoting.JmsInvokerServiceExporter">
@@ -1109,7 +1109,7 @@ public class Server {
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="checkingAccountService"
class="org.springframework.jms.remoting.JmsInvokerProxyFactoryBean"> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/testing.xml | @@ -2009,7 +2009,7 @@ public class HibernateTitleRepositoryTests {
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+ http://www.springframework.org/schema/beans/spring-beans.xsd">
<lineannotation><!-- this bean will be injected into the HibernateTitleRepositoryTests class --></lineannotation>
<bean id="<emphasis role="bold">titleRepository</emphasis>" class="<emphasis | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/transaction.xml | @@ -380,9 +380,9 @@ TR:REVISED, PLS REVIEW-->
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jee
- http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
+ http://www.springframework.org/schema/jee/spring-jee.xsd">
<jee:jndi-lookup id="dataSource" jndi-name="jdbc/jpetstore"/>
@@ -800,11 +800,11 @@ public class DefaultFooService implements FooService {
<lineannotation>xmlns:tx="http://www.springframework.org/schema/tx"</lineannotation>
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
<lineannotation>http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd</lineannotation>
+ http://www.springframework.org/schema/tx/spring-tx.xsd</lineannotation>
http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+ http://www.springframework.org/schema/aop/spring-aop.xsd">
<lineannotation><!-- this is the service object that we want to make transactional --></lineannotation>
<bean id="fooService" class="x.y.service.DefaultFooService"/>
@@ -1084,11 +1084,11 @@ if the underlying application server infrastructure throws an Error the transact
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+ http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:config>
@@ -1128,11 +1128,11 @@ if the underlying application server infrastructure throws an Error the transact
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+ http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:config>
@@ -1361,11 +1361,11 @@ public class DefaultFooService implements FooService {
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+ http://www.springframework.org/schema/aop/spring-aop.xsd">
<lineannotation><!-- this is the service object that we want to make transactional --></lineannotation>
<bean id="fooService" class="x.y.service.DefaultFooService"/>
@@ -2026,11 +2026,11 @@ public class SimpleProfiler implements Ordered {
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+ http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="fooService" class="x.y.service.DefaultFooService"/>
@@ -2081,11 +2081,11 @@ TR: REVISED, PLS REVIEW. changed to 'desired'; seems clear that the desired orde
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
+ http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+ http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="fooService" class="x.y.service.DefaultFooService"/>
| true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/validation.xml | @@ -1438,9 +1438,9 @@ public interface FormatterRegistrar {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
+ http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven/>
@@ -1462,9 +1462,9 @@ public interface FormatterRegistrar {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
+ http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven conversion-service="conversionService"/>
@@ -1546,7 +1546,7 @@ public class AppConfig {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd>
+ http://www.springframework.org/schema/beans/spring-beans.xsd>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="registerDefaultFormatters" value="false" />
@@ -1840,9 +1840,9 @@ public class MyController {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
+ http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven validator="globalValidator"/>
@@ -1868,9 +1868,9 @@ public class MyController {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
+ http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- JSR-303 support will be detected on classpath and enabled automatically -->
<mvc:annotation-driven/> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/web-integration.xml | @@ -662,8 +662,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<emphasis role="bold">xmlns:jee="http://www.springframework.org/schema/jee"</emphasis>
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-<emphasis role="bold">http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd"</emphasis>>
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+<emphasis role="bold">http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd"</emphasis>>
<beans>
<!-- the DataSource --> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/xml-custom.xml | @@ -270,7 +270,7 @@ public class SimpleDateFormatBeanDefinitionParser extends AbstractSingleBeanDefi
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:myns="http://www.mycompany.com/schema/myns"
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.mycompany.com/schema/myns http://www.mycompany.com/schema/myns/myns.xsd">
]]><lineannotation><!-- as a top-level bean --></lineannotation><![CDATA[
@@ -297,7 +297,7 @@ http://www.mycompany.com/schema/myns http://www.mycompany.com/schema/myns/myns.x
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:foo="http://www.foo.com/schema/component"
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.foo.com/schema/component http://www.foo.com/schema/component/component.xsd">
]]><lineannotation><![CDATA[<foo:component id="bionic-family" name="Bionic-1"> | true |
Other | spring-projects | spring-framework | 2b6d724faeb493da2d818c91edde66c141efd26c.json | Remove xsd versions from reference samples
Remove all xsd versions from the reference manual samples in favor of
"versionless" XSDs. For example, spring-beans-3.0.xsd becomes
spring-beans.xsd
Issue: SPR-10010 | src/reference/docbook/xsd-configuration.xml | @@ -72,7 +72,7 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
]]><lineannotation><!-- bean definitions here --></lineannotation><![CDATA[
@@ -110,8 +110,8 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
]]><emphasis role="bold">xmlns:util="http://www.springframework.org/schema/util"</emphasis><![CDATA[
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-]]><emphasis role="bold">http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"</emphasis><![CDATA[>
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+]]><emphasis role="bold">http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"</emphasis><![CDATA[>
]]><lineannotation><!-- bean definitions here --></lineannotation><![CDATA[
@@ -481,8 +481,8 @@ public class Client {
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
]]><emphasis role="bold">xmlns:jee="http://www.springframework.org/schema/jee"</emphasis><![CDATA[
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-]]><emphasis role="bold">http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd"</emphasis><![CDATA[>
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+]]><emphasis role="bold">http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd"</emphasis><![CDATA[>
]]><lineannotation><!-- bean definitions here --></lineannotation><![CDATA[
@@ -640,8 +640,8 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
]]><emphasis role="bold">xmlns:lang="http://www.springframework.org/schema/lang"</emphasis><![CDATA[
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-]]><emphasis role="bold">http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd"</emphasis><![CDATA[>
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+]]><emphasis role="bold">http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd"</emphasis><![CDATA[>
]]><lineannotation><!-- bean definitions here --></lineannotation><![CDATA[
@@ -665,8 +665,8 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
]]><emphasis role="bold">xmlns:jms="http://www.springframework.org/schema/jms"</emphasis><![CDATA[
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-]]><emphasis role="bold">http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd"</emphasis><![CDATA[>
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+]]><emphasis role="bold">http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd"</emphasis><![CDATA[>
]]><lineannotation><!-- bean definitions here --></lineannotation><![CDATA[
@@ -698,9 +698,9 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem
xmlns:aop="http://www.springframework.org/schema/aop"
]]><emphasis role="bold">xmlns:tx="http://www.springframework.org/schema/tx"</emphasis><![CDATA[
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-]]><emphasis role="bold">http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd</emphasis><![CDATA[
-http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+]]><emphasis role="bold">http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd</emphasis><![CDATA[
+http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
]]><lineannotation><!-- bean definitions here --></lineannotation><![CDATA[
@@ -728,8 +728,8 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
]]><emphasis role="bold">xmlns:aop="http://www.springframework.org/schema/aop"</emphasis><![CDATA[
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-]]><emphasis role="bold">http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"</emphasis><![CDATA[>
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+]]><emphasis role="bold">http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"</emphasis><![CDATA[>
]]><lineannotation><!-- bean definitions here --></lineannotation><![CDATA[
@@ -748,8 +748,8 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
]]><emphasis role="bold">xmlns:context="http://www.springframework.org/schema/context"</emphasis><![CDATA[
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-]]><emphasis role="bold">http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"</emphasis><![CDATA[>
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+]]><emphasis role="bold">http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"</emphasis><![CDATA[>
]]><lineannotation><!-- bean definitions here --></lineannotation><![CDATA[
@@ -833,8 +833,8 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
]]><emphasis role="bold">xmlns:jdbc="http://www.springframework.org/schema/jdbc"</emphasis><![CDATA[
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
-]]><emphasis role="bold">http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd"</emphasis><![CDATA[>
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+]]><emphasis role="bold">http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd"</emphasis><![CDATA[>
]]><lineannotation><!-- bean definitions here --></lineannotation><![CDATA[
@@ -858,8 +858,8 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
]]><emphasis role="bold">xmlns:jdbc="http://www.springframework.org/schema/cache"</emphasis><![CDATA[
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
-]]><emphasis role="bold">http://www.springframework.org/schema/cache http://www.springframework.org/schema/jdbc/spring-cache-3.1.xsd"</emphasis><![CDATA[>
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
+]]><emphasis role="bold">http://www.springframework.org/schema/cache http://www.springframework.org/schema/jdbc/spring-cache.xsd"</emphasis><![CDATA[>
]]><lineannotation><!-- bean definitions here --></lineannotation><![CDATA[
@@ -886,7 +886,7 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
+http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="foo" class="x.y.Foo">
]]><emphasis role="bold"><![CDATA[<meta key="cacheName" value="foo"/>]]></emphasis><![CDATA[ | true |
Other | spring-projects | spring-framework | 3749313d2ff16446632cbf7201b937d323308214.json | Drop Appendix E. spring-beans-2.0.dtd from docs
Issue: SPR-10011 | src/reference/docbook/dtd.xml | @@ -1,688 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<appendix xml:id="springbeansdtd"
- xmlns="http://docbook.org/ns/docbook" version="5.0"
- xmlns:xl="http://www.w3.org/1999/xlink"
- xmlns:xi="http://www.w3.org/2001/XInclude"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="
- http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd
- http://www.w3.org/1999/xlink http://www.docbook.org/xml/5.0/xsd/xlink.xsd">
- <title><literal>spring-beans-2.0.dtd</literal></title>
-
- <para><programlisting language="xml"><!--
- Spring XML Beans DTD, version 2.0
- Authors: Rod Johnson, Juergen Hoeller, Alef Arendsen, Colin Sampaleanu, Rob Harrop
-
- This defines a simple and consistent way of creating a namespace
- of JavaBeans objects, managed by a Spring BeanFactory, read by
- XmlBeanDefinitionReader (with DefaultBeanDefinitionDocumentReader).
-
- This document type is used by most Spring functionality, including
- web application contexts, which are based on bean factories.
-
- Each "bean" element in this document defines a JavaBean.
- Typically the bean class is specified, along with JavaBean properties
- and/or constructor arguments.
-
- A bean instance can be a "singleton" (shared instance) or a "prototype"
- (independent instance). Further scopes can be provided by extended
- bean factories, for example in a web environment.
-
- References among beans are supported, that is, setting a JavaBean property
- or a constructor argument to refer to another bean in the same factory
- (or an ancestor factory).
-
- As alternative to bean references, "inner bean definitions" can be used.
- Singleton flags of such inner bean definitions are effectively ignored:
- Inner beans are typically anonymous prototypes.
-
- There is also support for lists, sets, maps, and java.util.Properties
- as bean property types or constructor argument types.
-
- For simple purposes, this DTD is sufficient. As of Spring 2.0,
- XSD-based bean definitions are supported as more powerful alternative.
-
- XML documents that conform to this DTD should declare the following doctype:
-
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
- "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
--->
-
-
-<!--
- The document root. A document can contain bean definitions only,
- imports only, or a mixture of both (typically with imports first).
--->
-<!ELEMENT beans (
- description?,
- (import | alias | bean)*
-)>
-
-<!--
- Default values for all bean definitions. Can be overridden at
- the "bean" level. See those attribute definitions for details.
--->
-<!ATTLIST beans default-lazy-init (true | false) "false">
-<!ATTLIST beans default-autowire (no | byName | byType | constructor | autodetect) "no">
-<!ATTLIST beans default-dependency-check (none | objects | simple | all) "none">
-<!ATTLIST beans default-init-method CDATA #IMPLIED>
-<!ATTLIST beans default-destroy-method CDATA #IMPLIED>
-<!ATTLIST beans default-merge (true | false) "false">
-
-<!--
- Element containing informative text describing the purpose of the enclosing
- element. Always optional.
- Used primarily for user documentation of XML bean definition documents.
--->
-<!ELEMENT description (#PCDATA)>
-
-
-<!--
- Specifies an XML bean definition resource to import.
--->
-<!ELEMENT import EMPTY>
-
-<!--
- The relative resource location of the XML bean definition file to import,
- for example "myImport.xml" or "includes/myImport.xml" or "../myImport.xml".
--->
-<!ATTLIST import resource CDATA #REQUIRED>
-
-
-<!--
- Defines an alias for a bean, which can reside in a different definition file.
--->
-<!ELEMENT alias EMPTY>
-
-<!--
- The name of the bean to define an alias for.
--->
-<!ATTLIST alias name CDATA #REQUIRED>
-
-<!--
- The alias name to define for the bean.
--->
-<!ATTLIST alias alias CDATA #REQUIRED>
-
-<!--
- Allows for arbitrary metadata to be attached to a bean definition.
--->
-<!ELEMENT meta EMPTY>
-
-<!--
- Specifies the key name of the metadata parameter being defined.
--->
-<!ATTLIST meta key CDATA #REQUIRED>
-
-<!--
- Specifies the value of the metadata parameter being defined as a String.
--->
-<!ATTLIST meta value CDATA #REQUIRED>
-
-<!--
- Defines a single (usually named) bean.
-
- A bean definition may contain nested tags for constructor arguments,
- property values, lookup methods, and replaced methods. Mixing constructor
- injection and setter injection on the same bean is explicitly supported.
--->
-<!ELEMENT bean (
- description?,
- (meta | constructor-arg | property | lookup-method | replaced-method)*
-)>
-
-<!--
- Beans can be identified by an id, to enable reference checking.
-
- There are constraints on a valid XML id: if you want to reference your bean
- in Java code using a name that's illegal as an XML id, use the optional
- "name" attribute. If neither is given, the bean class name is used as id
- (with an appended counter like "#2" if there is already a bean with that name).
--->
-<!ATTLIST bean id ID #IMPLIED>
-
-<!--
- Optional. Can be used to create one or more aliases illegal in an id.
- Multiple aliases can be separated by any number of spaces, commas, or
- semi-colons (or indeed any mixture of the three).
--->
-<!ATTLIST bean name CDATA #IMPLIED>
-
-<!--
- Each bean definition must specify the fully qualified name of the class,
- except if it pure serves as parent for child bean definitions.
--->
-<!ATTLIST bean class CDATA #IMPLIED>
-
-<!--
- Optionally specify a parent bean definition.
-
- Will use the bean class of the parent if none specified, but can
- also override it. In the latter case, the child bean class must be
- compatible with the parent, i.e. accept the parent's property values
- and constructor argument values, if any.
-
- A child bean definition will inherit constructor argument values,
- property values and method overrides from the parent, with the option
- to add new values. If init method, destroy method, factory bean and/or factory
- method are specified, they will override the corresponding parent settings.
-
- The remaining settings will always be taken from the child definition:
- depends on, autowire mode, dependency check, scope, lazy init.
--->
-<!ATTLIST bean parent CDATA #IMPLIED>
-
-<!--
- The scope of this bean: typically "singleton" (one shared instance,
- which will be returned by all calls to getBean() with the id),
- or "prototype" (independent instance resulting from each call to
- getBean(). Default is "singleton".
-
- Singletons are most commonly used, and are ideal for multi-threaded
- service objects. Further scopes, such as "request" or "session",
- might be supported by extended bean factories (for example, in a
- web environment).
-
- Note: This attribute will not be inherited by child bean definitions.
- Hence, it needs to be specified per concrete bean definition.
-
- Inner bean definitions inherit the singleton status of their containing
- bean definition, unless explicitly specified: The inner bean will be a
- singleton if the containing bean is a singleton, and a prototype if
- the containing bean has any other scope.
--->
-<!ATTLIST bean scope CDATA #IMPLIED>
-
-<!--
- Is this bean "abstract", i.e. not meant to be instantiated itself but
- rather just serving as parent for concrete child bean definitions.
- Default is "false". Specify "true" to tell the bean factory to not try to
- instantiate that particular bean in any case.
-
- Note: This attribute will not be inherited by child bean definitions.
- Hence, it needs to be specified per abstract bean definition.
--->
-<!ATTLIST bean abstract (true | false) #IMPLIED>
-
-<!--
- If this bean should be lazily initialized.
- If false, it will get instantiated on startup by bean factories
- that perform eager initialization of singletons.
-
- Note: This attribute will not be inherited by child bean definitions.
- Hence, it needs to be specified per concrete bean definition.
--->
-<!ATTLIST bean lazy-init (true | false | default) "default">
-
-<!--
- Indicates whether or not this bean should be considered when looking
- for candidates to satisfy another beans autowiring requirements.
--->
-<!ATTLIST bean autowire-candidate (true | false) #IMPLIED>
-
-<!--
- Optional attribute controlling whether to "autowire" bean properties.
- This is an automagical process in which bean references don't need to be coded
- explicitly in the XML bean definition file, but Spring works out dependencies.
-
- There are 5 modes:
-
- 1. "no"
- The traditional Spring default. No automagical wiring. Bean references
- must be defined in the XML file via the <ref> element. We recommend this
- in most cases as it makes documentation more explicit.
-
- 2. "byName"
- Autowiring by property name. If a bean of class Cat exposes a dog property,
- Spring will try to set this to the value of the bean "dog" in the current factory.
- If there is no matching bean by name, nothing special happens;
- use dependency-check="objects" to raise an error in that case.
-
- 3. "byType"
- Autowiring if there is exactly one bean of the property type in the bean factory.
- If there is more than one, a fatal error is raised, and you can't use byType
- autowiring for that bean. If there is none, nothing special happens;
- use dependency-check="objects" to raise an error in that case.
-
- 4. "constructor"
- Analogous to "byType" for constructor arguments. If there isn't exactly one bean
- of the constructor argument type in the bean factory, a fatal error is raised.
-
- 5. "autodetect"
- Chooses "constructor" or "byType" through introspection of the bean class.
- If a default no-arg constructor is found, "byType" gets applied.
-
- The latter two are similar to PicoContainer and make bean factories simple to
- configure for small namespaces, but doesn't work as well as standard Spring
- behavior for bigger applications.
-
- Note that explicit dependencies, i.e. "property" and "constructor-arg" elements,
- always override autowiring. Autowire behavior can be combined with dependency
- checking, which will be performed after all autowiring has been completed.
-
- Note: This attribute will not be inherited by child bean definitions.
- Hence, it needs to be specified per concrete bean definition.
--->
-<!ATTLIST bean autowire (no | byName | byType | constructor | autodetect | default) "default">
-
-<!--
- Optional attribute controlling whether to check whether all this
- beans dependencies, expressed in its properties, are satisfied.
- Default is no dependency checking.
-
- "simple" type dependency checking includes primitives and String;
- "objects" includes collaborators (other beans in the factory);
- "all" includes both types of dependency checking.
-
- Note: This attribute will not be inherited by child bean definitions.
- Hence, it needs to be specified per concrete bean definition.
--->
-<!ATTLIST bean dependency-check (none | objects | simple | all | default) "default">
-
-<!--
- The names of the beans that this bean depends on being initialized.
- The bean factory will guarantee that these beans get initialized before.
-
- Note that dependencies are normally expressed through bean properties or
- constructor arguments. This property should just be necessary for other kinds
- of dependencies like statics (*ugh*) or database preparation on startup.
-
- Note: This attribute will not be inherited by child bean definitions.
- Hence, it needs to be specified per concrete bean definition.
--->
-<!ATTLIST bean depends-on CDATA #IMPLIED>
-
-<!--
- Optional attribute for the name of the custom initialization method
- to invoke after setting bean properties. The method must have no arguments,
- but may throw any exception.
--->
-<!ATTLIST bean init-method CDATA #IMPLIED>
-
-<!--
- Optional attribute for the name of the custom destroy method to invoke
- on bean factory shutdown. The method must have no arguments,
- but may throw any exception.
-
- Note: Only invoked on beans whose lifecycle is under full control
- of the factory - which is always the case for singletons, but not
- guaranteed for any other scope.
--->
-<!ATTLIST bean destroy-method CDATA #IMPLIED>
-
-<!--
- Optional attribute specifying the name of a factory method to use to
- create this object. Use constructor-arg elements to specify arguments
- to the factory method, if it takes arguments. Autowiring does not apply
- to factory methods.
-
- If the "class" attribute is present, the factory method will be a static
- method on the class specified by the "class" attribute on this bean
- definition. Often this will be the same class as that of the constructed
- object - for example, when the factory method is used as an alternative
- to a constructor. However, it may be on a different class. In that case,
- the created object will *not* be of the class specified in the "class"
- attribute. This is analogous to FactoryBean behavior.
-
- If the "factory-bean" attribute is present, the "class" attribute is not
- used, and the factory method will be an instance method on the object
- returned from a getBean call with the specified bean name. The factory
- bean may be defined as a singleton or a prototype.
-
- The factory method can have any number of arguments. Autowiring is not
- supported. Use indexed constructor-arg elements in conjunction with the
- factory-method attribute.
-
- Setter Injection can be used in conjunction with a factory method.
- Method Injection cannot, as the factory method returns an instance,
- which will be used when the container creates the bean.
--->
-<!ATTLIST bean factory-method CDATA #IMPLIED>
-
-<!--
- Alternative to class attribute for factory-method usage.
- If this is specified, no class attribute should be used.
- This should be set to the name of a bean in the current or
- ancestor factories that contains the relevant factory method.
- This allows the factory itself to be configured using Dependency
- Injection, and an instance (rather than static) method to be used.
--->
-<!ATTLIST bean factory-bean CDATA #IMPLIED>
-
-<!--
- Bean definitions can specify zero or more constructor arguments.
- This is an alternative to "autowire constructor".
- Arguments correspond to either a specific index of the constructor argument
- list or are supposed to be matched generically by type.
-
- Note: A single generic argument value will just be used once, rather than
- potentially matched multiple times (as of Spring 1.1).
-
- constructor-arg elements are also used in conjunction with the factory-method
- element to construct beans using static or instance factory methods.
--->
-<!ELEMENT constructor-arg (
- description?,
- (bean | ref | idref | value | null | list | set | map | props)?
-)>
-
-<!--
- The constructor-arg tag can have an optional index attribute,
- to specify the exact index in the constructor argument list. Only needed
- to avoid ambiguities, e.g. in case of 2 arguments of the same type.
--->
-<!ATTLIST constructor-arg index CDATA #IMPLIED>
-
-<!--
- The constructor-arg tag can have an optional type attribute,
- to specify the exact type of the constructor argument. Only needed
- to avoid ambiguities, e.g. in case of 2 single argument constructors
- that can both be converted from a String.
--->
-<!ATTLIST constructor-arg type CDATA #IMPLIED>
-
-<!--
- A short-cut alternative to a child element "ref bean=".
--->
-<!ATTLIST constructor-arg ref CDATA #IMPLIED>
-
-<!--
- A short-cut alternative to a child element "value".
--->
-<!ATTLIST constructor-arg value CDATA #IMPLIED>
-
-
-<!--
- Bean definitions can have zero or more properties.
- Property elements correspond to JavaBean setter methods exposed
- by the bean classes. Spring supports primitives, references to other
- beans in the same or related factories, lists, maps and properties.
--->
-<!ELEMENT property (
- description?, meta*,
- (bean | ref | idref | value | null | list | set | map | props)?
-)>
-
-<!--
- The property name attribute is the name of the JavaBean property.
- This follows JavaBean conventions: a name of "age" would correspond
- to setAge()/optional getAge() methods.
--->
-<!ATTLIST property name CDATA #REQUIRED>
-
-<!--
- A short-cut alternative to a child element "ref bean=".
--->
-<!ATTLIST property ref CDATA #IMPLIED>
-
-<!--
- A short-cut alternative to a child element "value".
--->
-<!ATTLIST property value CDATA #IMPLIED>
-
-
-<!--
- A lookup method causes the IoC container to override the given method and return
- the bean with the name given in the bean attribute. This is a form of Method Injection.
- It's particularly useful as an alternative to implementing the BeanFactoryAware
- interface, in order to be able to make getBean() calls for non-singleton instances
- at runtime. In this case, Method Injection is a less invasive alternative.
--->
-<!ELEMENT lookup-method EMPTY>
-
-<!--
- Name of a lookup method. This method should take no arguments.
--->
-<!ATTLIST lookup-method name CDATA #IMPLIED>
-
-<!--
- Name of the bean in the current or ancestor factories that the lookup method
- should resolve to. Often this bean will be a prototype, in which case the
- lookup method will return a distinct instance on every invocation. This
- is useful for single-threaded objects.
--->
-<!ATTLIST lookup-method bean CDATA #IMPLIED>
-
-
-<!--
- Similar to the lookup method mechanism, the replaced-method element is used to control
- IoC container method overriding: Method Injection. This mechanism allows the overriding
- of a method with arbitrary code.
--->
-<!ELEMENT replaced-method (
- (arg-type)*
-)>
-
-<!--
- Name of the method whose implementation should be replaced by the IoC container.
- If this method is not overloaded, there's no need to use arg-type subelements.
- If this method is overloaded, arg-type subelements must be used for all
- override definitions for the method.
--->
-<!ATTLIST replaced-method name CDATA #IMPLIED>
-
-<!--
- Bean name of an implementation of the MethodReplacer interface in the current
- or ancestor factories. This may be a singleton or prototype bean. If it's
- a prototype, a new instance will be used for each method replacement.
- Singleton usage is the norm.
--->
-<!ATTLIST replaced-method replacer CDATA #IMPLIED>
-
-<!--
- Subelement of replaced-method identifying an argument for a replaced method
- in the event of method overloading.
--->
-<!ELEMENT arg-type (#PCDATA)>
-
-<!--
- Specification of the type of an overloaded method argument as a String.
- For convenience, this may be a substring of the FQN. E.g. all the
- following would match "java.lang.String":
- - java.lang.String
- - String
- - Str
-
- As the number of arguments will be checked also, this convenience can often
- be used to save typing.
--->
-<!ATTLIST arg-type match CDATA #IMPLIED>
-
-
-<!--
- Defines a reference to another bean in this factory or an external
- factory (parent or included factory).
--->
-<!ELEMENT ref EMPTY>
-
-<!--
- References must specify a name of the target bean.
- The "bean" attribute can reference any name from any bean in the context,
- to be checked at runtime.
- Local references, using the "local" attribute, have to use bean ids;
- they can be checked by this DTD, thus should be preferred for references
- within the same bean factory XML file.
--->
-<!ATTLIST ref bean CDATA #IMPLIED>
-<!ATTLIST ref local IDREF #IMPLIED>
-<!ATTLIST ref parent CDATA #IMPLIED>
-
-
-<!--
- Defines a string property value, which must also be the id of another
- bean in this factory or an external factory (parent or included factory).
- While a regular 'value' element could instead be used for the same effect,
- using idref in this case allows validation of local bean ids by the XML
- parser, and name completion by supporting tools.
--->
-<!ELEMENT idref EMPTY>
-
-<!--
- ID refs must specify a name of the target bean.
- The "bean" attribute can reference any name from any bean in the context,
- potentially to be checked at runtime by bean factory implementations.
- Local references, using the "local" attribute, have to use bean ids;
- they can be checked by this DTD, thus should be preferred for references
- within the same bean factory XML file.
--->
-<!ATTLIST idref bean CDATA #IMPLIED>
-<!ATTLIST idref local IDREF #IMPLIED>
-
-
-<!--
- Contains a string representation of a property value.
- The property may be a string, or may be converted to the required
- type using the JavaBeans PropertyEditor machinery. This makes it
- possible for application developers to write custom PropertyEditor
- implementations that can convert strings to arbitrary target objects.
-
- Note that this is recommended for simple objects only.
- Configure more complex objects by populating JavaBean
- properties with references to other beans.
--->
-<!ELEMENT value (#PCDATA)>
-
-<!--
- The value tag can have an optional type attribute, to specify the
- exact type that the value should be converted to. Only needed
- if the type of the target property or constructor argument is
- too generic: for example, in case of a collection element.
--->
-<!ATTLIST value type CDATA #IMPLIED>
-
-<!--
- Denotes a Java null value. Necessary because an empty "value" tag
- will resolve to an empty String, which will not be resolved to a
- null value unless a special PropertyEditor does so.
--->
-<!ELEMENT null (#PCDATA)>
-
-
-<!--
- A list can contain multiple inner bean, ref, collection, or value elements.
- Java lists are untyped, pending generics support in Java 1.5,
- although references will be strongly typed.
- A list can also map to an array type. The necessary conversion
- is automatically performed by the BeanFactory.
--->
-<!ELEMENT list (
- (bean | ref | idref | value | null | list | set | map | props)*
-)>
-
-<!--
- Enable/disable merging for collections when using parent/child beans.
--->
-<!ATTLIST list merge (true | false | default) "default">
-
-<!--
- Specify the default Java type for nested values.
--->
-<!ATTLIST list value-type CDATA #IMPLIED>
-
-
-<!--
- A set can contain multiple inner bean, ref, collection, or value elements.
- Java sets are untyped, pending generics support in Java 1.5,
- although references will be strongly typed.
--->
-<!ELEMENT set (
- (bean | ref | idref | value | null | list | set | map | props)*
-)>
-
-<!--
- Enable/disable merging for collections when using parent/child beans.
--->
-<!ATTLIST set merge (true | false | default) "default">
-
-<!--
- Specify the default Java type for nested values.
--->
-<!ATTLIST set value-type CDATA #IMPLIED>
-
-
-<!--
- A Spring map is a mapping from a string key to object.
- Maps may be empty.
--->
-<!ELEMENT map (
- (entry)*
-)>
-
-<!--
- Enable/disable merging for collections when using parent/child beans.
--->
-<!ATTLIST map merge (true | false | default) "default">
-
-<!--
- Specify the default Java type for nested entry keys.
--->
-<!ATTLIST map key-type CDATA #IMPLIED>
-
-<!--
- Specify the default Java type for nested entry values.
--->
-<!ATTLIST map value-type CDATA #IMPLIED>
-
-<!--
- A map entry can be an inner bean, ref, value, or collection.
- The key of the entry is given by the "key" attribute or child element.
--->
-<!ELEMENT entry (
- key?,
- (bean | ref | idref | value | null | list | set | map | props)?
-)>
-
-<!--
- Each map element must specify its key as attribute or as child element.
- A key attribute is always a String value.
--->
-<!ATTLIST entry key CDATA #IMPLIED>
-
-<!--
- A short-cut alternative to a "key" element with a "ref bean=" child element.
--->
-<!ATTLIST entry key-ref CDATA #IMPLIED>
-
-<!--
- A short-cut alternative to a child element "value".
--->
-<!ATTLIST entry value CDATA #IMPLIED>
-
-<!--
- A short-cut alternative to a child element "ref bean=".
--->
-<!ATTLIST entry value-ref CDATA #IMPLIED>
-
-<!--
- A key element can contain an inner bean, ref, value, or collection.
--->
-<!ELEMENT key (
- (bean | ref | idref | value | null | list | set | map | props)
-)>
-
-
-<!--
- Props elements differ from map elements in that values must be strings.
- Props may be empty.
--->
-<!ELEMENT props (
- (prop)*
-)>
-
-<!--
- Enable/disable merging for collections when using parent/child beans.
--->
-<!ATTLIST props merge (true | false | default) "default">
-
-<!--
- Element content is the string value of the property.
- Note that whitespace is trimmed off to avoid unwanted whitespace
- caused by typical XML formatting.
--->
-<!ELEMENT prop (#PCDATA)>
-
-<!--
- Each property element must specify its key.
--->
-<!ATTLIST prop key CDATA #REQUIRED></programlisting></para>
-</appendix> | true |
Other | spring-projects | spring-framework | 3749313d2ff16446632cbf7201b937d323308214.json | Drop Appendix E. spring-beans-2.0.dtd from docs
Issue: SPR-10011 | src/reference/docbook/index.xml | @@ -547,8 +547,6 @@
<xi:include href="xml-custom.xml"
xmlns:xi="http://www.w3.org/2001/XInclude" />
- <xi:include href="dtd.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
-
<xi:include href="spring.tld.xml"
xmlns:xi="http://www.w3.org/2001/XInclude" />
| true |
Other | spring-projects | spring-framework | e0b1c0e614b561aaa1788c0656ce5bdf1de9133b.json | Remove duplicate imagedata from reference guide
Prior to this commit many imagedata elements were duplicated in
order to configure PDF sizes. Since HTML generation is configured
to ignore image scaling altogether this was unnecessary duplication.
Issue: SPR-10033 | src/reference/docbook/aop.xml | @@ -2657,16 +2657,10 @@ public @interface Idempotent {
be seen below.</para>
<para><mediaobject>
- <imageobject role="fo">
+ <imageobject>
<imagedata align="center"
fileref="images/aop-proxy-plain-pojo-call.png"
- format="PNG" />
- </imageobject>
-
- <imageobject role="html">
- <imagedata align="center"
- fileref="images/aop-proxy-plain-pojo-call.png"
- format="PNG" />
+ format="PNG" width="400"/>
</imageobject>
</mediaobject></para>
@@ -2685,14 +2679,9 @@ public @interface Idempotent {
a proxy. Consider the following diagram and code snippet.</para>
<para><mediaobject>
- <imageobject role="fo">
- <imagedata align="center" fileref="images/aop-proxy-call.png"
- format="PNG" />
- </imageobject>
-
- <imageobject role="html">
+ <imageobject>
<imagedata align="center" fileref="images/aop-proxy-call.png"
- format="PNG" />
+ format="PNG" width="400" />
</imageobject>
</mediaobject></para>
| true |
Other | spring-projects | spring-framework | e0b1c0e614b561aaa1788c0656ce5bdf1de9133b.json | Remove duplicate imagedata from reference guide
Prior to this commit many imagedata elements were duplicated in
order to configure PDF sizes. Since HTML generation is configured
to ignore image scaling altogether this was unnecessary duplication.
Issue: SPR-10033 | src/reference/docbook/beans-scopes.xml | @@ -121,13 +121,8 @@
bean return the cached object.</para>
<para><mediaobject>
- <imageobject role="fo">
- <imagedata align="center" fileref="images/singleton.png" format="PNG"
- width="400"/>
- </imageobject>
-
- <imageobject role="html">
- <imagedata align="center" fileref="images/singleton.png" format="PNG"/>
+ <imageobject>
+ <imagedata align="center" fileref="images/singleton.png" format="PNG" width="400" />
</imageobject>
</mediaobject></para>
@@ -167,13 +162,8 @@
diagram.</emphasis><!--First it says diagram illustrates scope, but then says it's not typical of a prototype scope. Why not use realistic one? --></para>
<para><mediaobject>
- <imageobject role="fo">
- <imagedata align="center" fileref="images/prototype.png" format="PNG"
- width="400" />
- </imageobject>
-
- <imageobject role="html">
- <imagedata align="center" fileref="images/prototype.png" format="PNG"/>
+ <imageobject>
+ <imagedata align="center" fileref="images/prototype.png" format="PNG" width="400"/>
</imageobject>
</mediaobject></para>
| true |
Other | spring-projects | spring-framework | e0b1c0e614b561aaa1788c0656ce5bdf1de9133b.json | Remove duplicate imagedata from reference guide
Prior to this commit many imagedata elements were duplicated in
order to configure PDF sizes. Since HTML generation is configured
to ignore image scaling altogether this was unnecessary duplication.
Issue: SPR-10033 | src/reference/docbook/beans.xml | @@ -112,8 +112,7 @@ The footnote should x-ref to first section in that chapter but I can't find the
<para><mediaobject>
<imageobject>
- <imagedata align="center" fileref="images/container-magic.png"
- format="PNG" width="400" />
+ <imagedata align="center" fileref="images/container-magic.png" format="PNG" width="250" />
</imageobject>
<caption><para>The Spring IoC container</para></caption> | true |
Other | spring-projects | spring-framework | e0b1c0e614b561aaa1788c0656ce5bdf1de9133b.json | Remove duplicate imagedata from reference guide
Prior to this commit many imagedata elements were duplicated in
order to configure PDF sizes. Since HTML generation is configured
to ignore image scaling altogether this was unnecessary duplication.
Issue: SPR-10033 | src/reference/docbook/dao.xml | @@ -63,14 +63,8 @@
hierarchy.)</para>
<mediaobject>
- <imageobject role="fo">
- <imagedata align="center" fileref="images/DataAccessException.gif"
- format="PNG" width="400"/>
- </imageobject>
-
- <imageobject role="html">
- <imagedata align="center" fileref="images/DataAccessException.gif"
- format="PNG" width="400"/>
+ <imageobject>
+ <imagedata align="center" fileref="images/DataAccessException.gif" format="PNG" width="400" />
</imageobject>
</mediaobject>
</section> | true |
Other | spring-projects | spring-framework | e0b1c0e614b561aaa1788c0656ce5bdf1de9133b.json | Remove duplicate imagedata from reference guide
Prior to this commit many imagedata elements were duplicated in
order to configure PDF sizes. Since HTML generation is configured
to ignore image scaling altogether this was unnecessary duplication.
Issue: SPR-10033 | src/reference/docbook/mvc.xml | @@ -235,13 +235,8 @@
Spring Web MVC shares with many other leading web frameworks).</para>
<para><mediaobject>
- <imageobject role="fo">
- <imagedata align="center" fileref="images/mvc.png" format="PNG"
- width="400" />
- </imageobject>
-
- <imageobject role="html">
- <imagedata align="center" fileref="images/mvc.png" format="PNG" />
+ <imageobject>
+ <imagedata align="center" fileref="images/mvc.png" format="PNG" width="400"/>
</imageobject>
<caption><para>The request processing workflow in Spring Web MVC (high
@@ -319,14 +314,8 @@
new scope-specific beans local to a given Servlet instance.</para>
<para><mediaobject>
- <imageobject role="fo">
- <imagedata align="center" fileref="images/mvc-contexts.gif"
- format="GIF" width="400" />
- </imageobject>
-
- <imageobject role="html">
- <imagedata align="center" fileref="images/mvc-contexts.gif"
- format="GIF" />
+ <imageobject>
+ <imagedata align="center" fileref="images/mvc-contexts.gif" format="GIF" width="400" />
</imageobject>
<caption>Context hierarchy in Spring Web MVC</caption> | true |
Other | spring-projects | spring-framework | e0b1c0e614b561aaa1788c0656ce5bdf1de9133b.json | Remove duplicate imagedata from reference guide
Prior to this commit many imagedata elements were duplicated in
order to configure PDF sizes. Since HTML generation is configured
to ignore image scaling altogether this was unnecessary duplication.
Issue: SPR-10033 | src/reference/docbook/overview.xml | @@ -99,14 +99,8 @@ TR: This section doesn't read well and I think we should try to rewrite it.-->Nu
Instrumentation, and Test, as shown in the following diagram.</para>
<para><mediaobject>
- <imageobject role="fo">
- <imagedata align="left" fileref="images/spring-overview.png"
- format="PNG" width="400" />
- </imageobject>
-
- <imageobject role="html">
- <imagedata align="center" fileref="images/spring-overview.png"
- format="PNG" />
+ <imageobject>
+ <imagedata align="center" fileref="images/spring-overview.png" format="PNG" width="400" />
</imageobject>
<caption><para>Overview of the Spring Framework</para></caption>
@@ -261,14 +255,8 @@ TR: OK. Added to diagram.--></para>
web framework integration.</para>
<para><mediaobject>
- <imageobject role="fo">
- <imagedata align="center" fileref="images/overview-full.png"
- format="PNG" width="400" />
- </imageobject>
-
- <imageobject role="html">
- <imagedata align="center" fileref="images/overview-full.png"
- format="PNG" />
+ <imageobject>
+ <imagedata align="center" fileref="images/overview-full.png" format="PNG" width="400" />
</imageobject>
<caption><para>Typical full-fledged Spring web
@@ -291,17 +279,12 @@ TR: OK. Added to diagram.--></para>
that transform HTTP parameters to values for your domain model.</para>
<para><mediaobject>
- <imageobject role="fo">
+ <imageobject>
<imagedata align="center"
fileref="images/overview-thirdparty-web.png" format="PNG"
width="400"/>
</imageobject>
- <imageobject role="html">
- <imagedata align="center"
- fileref="images/overview-thirdparty-web.png" format="PNG" />
- </imageobject>
-
<caption><para>Spring middle-tier using a third-party web
framework</para></caption>
</mediaobject></para>
@@ -318,16 +301,10 @@ TR: OK. Added to diagram.--></para>
layer.</para>
<para><mediaobject>
- <imageobject role="fo">
+ <imageobject>
<imagedata align="center" fileref="images/overview-remoting.png"
format="PNG" width="400" />
</imageobject>
-
- <imageobject role="html">
- <imagedata align="center" fileref="images/overview-remoting.png"
- format="PNG" />
- </imageobject>
-
<caption><para>Remoting usage scenario</para></caption>
</mediaobject></para>
@@ -338,16 +315,10 @@ TR: OK. Added to diagram.--></para>
difficult.</para>
<para><mediaobject>
- <imageobject role="fo">
+ <imageobject>
<imagedata align="center" fileref="images/overview-ejb.png"
format="PNG" width="400" />
</imageobject>
-
- <imageobject role="html">
- <imagedata align="center" fileref="images/overview-ejb.png"
- format="PNG" />
- </imageobject>
-
<caption><para>EJBs - Wrapping existing POJOs</para></caption>
</mediaobject></para>
| true |
Other | spring-projects | spring-framework | e0b1c0e614b561aaa1788c0656ce5bdf1de9133b.json | Remove duplicate imagedata from reference guide
Prior to this commit many imagedata elements were duplicated in
order to configure PDF sizes. Since HTML generation is configured
to ignore image scaling altogether this was unnecessary duplication.
Issue: SPR-10033 | src/reference/docbook/oxm.xml | @@ -189,26 +189,11 @@ public interface Unmarshaller {
<para>
The O/X Mapping exception hierarchy is shown in the following figure:
<mediaobject>
- <imageobject role="fo">
+ <imageobject>
<imagedata align="center" fileref="images/oxm-exceptions.png"
format="PNG" width="400"/>
</imageobject>
- <caption>
- <para>
- O/X Mapping exception hierarchy
- </para>
- </caption>
- </mediaobject>
- <mediaobject>
- <imageobject role="html">
- <imagedata align="center" fileref="images/oxm-exceptions.png"
- format="PNG" width="400"/>
- </imageobject>
- <caption>
- <para>
- O/X Mapping exception hierarchy
- </para>
- </caption>
+ <caption>O/X Mapping exception hierarchy</caption>
</mediaobject>
</para>
</section> | true |
Other | spring-projects | spring-framework | e0b1c0e614b561aaa1788c0656ce5bdf1de9133b.json | Remove duplicate imagedata from reference guide
Prior to this commit many imagedata elements were duplicated in
order to configure PDF sizes. Since HTML generation is configured
to ignore image scaling altogether this was unnecessary duplication.
Issue: SPR-10033 | src/reference/docbook/transaction.xml | @@ -721,14 +721,10 @@ would be rolled back, not necessarily following the EJB rules-->
TR: OK AS IS. images don't show up in the editor, but they do show up in the generated docs-->
<para><mediaobject>
- <imageobject role="fo">
+ <imageobject>
<imagedata align="center" fileref="images/tx.png" format="PNG"
width="400"/>
</imageobject>
-
- <imageobject role="html">
- <imagedata align="center" fileref="images/tx.png" format="PNG" />
- </imageobject>
</mediaobject></para>
</section>
@@ -1869,17 +1865,11 @@ TR: REVISED, PLS REVIEW - changed it back; it's not just settings, the section d
<title>Required</title>
<para><mediaobject>
- <imageobject role="fo">
- <imagedata align="center" fileref="images/tx_prop_required.png"
- format="PNG" width="400"/>
- </imageobject>
-
- <imageobject role="html">
+ <imageobject>
<imagedata align="center" fileref="images/tx_prop_required.png"
format="PNG" width="400"/>
</imageobject>
-
- <caption><para>PROPAGATION_REQUIRED</para></caption>
+ <caption>PROPAGATION_REQUIRED</caption>
</mediaobject></para>
<para>When the propagation setting is
@@ -1916,7 +1906,7 @@ TR: REVISED, PLS REVIEW - changed it back; it's not just settings, the section d
<imageobject>
<imagedata align="center"
fileref="images/tx_prop_requires_new.png"
- format="PNG" />
+ format="PNG" width="400" />
</imageobject>
<caption><para>PROPAGATION_REQUIRES_NEW</para></caption> | true |
Other | spring-projects | spring-framework | 085176673876afc9282af0a8f4f94ee6a36e9e4e.json | Accept non-generic type match as a fallback
DefaultListableBeanFactory performs a fallback check for autowire candidates now, which GenericTypeAwareAutowireCandidateResolver implements to accept raw type matches if the target class has unresolvable type variables. Full generic matches are still preferred; the BeanFactory will only start looking for fallback matches if the first pass led to an empty result.
Issue: SPR-10993
Issue: SPR-11004 | spring-beans/src/main/java/org/springframework/beans/factory/config/DependencyDescriptor.java | @@ -212,6 +212,29 @@ public ResolvableType getResolvableType() {
ResolvableType.forMethodParameter(this.methodParameter));
}
+ /**
+ * Return whether a fallback match is allowed.
+ * <p>This is {@code false} by default but may be overridden to return {@code true} in order
+ * to suggest to a {@link org.springframework.beans.factory.support.AutowireCandidateResolver}
+ * that a fallback match is acceptable as well.
+ */
+ public boolean fallbackMatchAllowed() {
+ return false;
+ }
+
+ /**
+ * Return a variant of this descriptor that is intended for a fallback match.
+ * @see #fallbackMatchAllowed()
+ */
+ public DependencyDescriptor forFallbackMatch() {
+ return new DependencyDescriptor(this) {
+ @Override
+ public boolean fallbackMatchAllowed() {
+ return true;
+ }
+ };
+ }
+
/**
* Initialize parameter name discovery for the underlying method parameter, if any.
* <p>This method does not actually try to retrieve the parameter name at
@@ -241,7 +264,8 @@ public Class<?> getDependencyType() {
if (this.nestingLevel > 1) {
Type type = this.field.getGenericType();
if (type instanceof ParameterizedType) {
- Type arg = ((ParameterizedType) type).getActualTypeArguments()[0];
+ Type[] args = ((ParameterizedType) type).getActualTypeArguments();
+ Type arg = args[args.length - 1];
if (arg instanceof Class) {
return (Class) arg;
} | true |
Other | spring-projects | spring-framework | 085176673876afc9282af0a8f4f94ee6a36e9e4e.json | Accept non-generic type match as a fallback
DefaultListableBeanFactory performs a fallback check for autowire candidates now, which GenericTypeAwareAutowireCandidateResolver implements to accept raw type matches if the target class has unresolvable type variables. Full generic matches are still preferred; the BeanFactory will only start looking for fallback matches if the first pass led to an empty result.
Issue: SPR-10993
Issue: SPR-11004 | spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java | @@ -979,6 +979,14 @@ protected Map<String, Object> findAutowireCandidates(
result.put(candidateName, getBean(candidateName));
}
}
+ if (result.isEmpty()) {
+ DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch();
+ for (String candidateName : candidateNames) {
+ if (!candidateName.equals(beanName) && isAutowireCandidate(candidateName, fallbackDescriptor)) {
+ result.put(candidateName, getBean(candidateName));
+ }
+ }
+ }
return result;
}
| true |
Other | spring-projects | spring-framework | 085176673876afc9282af0a8f4f94ee6a36e9e4e.json | Accept non-generic type match as a fallback
DefaultListableBeanFactory performs a fallback check for autowire candidates now, which GenericTypeAwareAutowireCandidateResolver implements to accept raw type matches if the target class has unresolvable type variables. Full generic matches are still preferred; the BeanFactory will only start looking for fallback matches if the first pass led to an empty result.
Issue: SPR-10993
Issue: SPR-11004 | spring-beans/src/main/java/org/springframework/beans/factory/support/GenericTypeAwareAutowireCandidateResolver.java | @@ -57,24 +57,28 @@ public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDesc
// if explicitly false, do not proceed with any other checks
return false;
}
- return (descriptor == null || checkGenericTypeMatch(bdHolder, descriptor.getResolvableType()));
+ return (descriptor == null || checkGenericTypeMatch(bdHolder, descriptor));
}
/**
* Match the given dependency type with its generic type information
* against the given candidate bean definition.
*/
- protected boolean checkGenericTypeMatch(BeanDefinitionHolder bdHolder, ResolvableType dependencyType) {
- if (dependencyType.getType() instanceof Class) {
+ protected boolean checkGenericTypeMatch(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
+ ResolvableType dependencyType = descriptor.getResolvableType();
+ if (!dependencyType.hasGenerics()) {
// No generic type -> we know it's a Class type-match, so no need to check again.
return true;
}
- RootBeanDefinition bd = (RootBeanDefinition) bdHolder.getBeanDefinition();
ResolvableType targetType = null;
- if (bd.getResolvedFactoryMethod() != null) {
+ RootBeanDefinition rbd = null;
+ if (bdHolder.getBeanDefinition() instanceof RootBeanDefinition) {
+ rbd = (RootBeanDefinition) bdHolder.getBeanDefinition();
+ }
+ if (rbd != null && rbd.getResolvedFactoryMethod() != null) {
// Should typically be set for any kind of factory method, since the BeanFactory
// pre-resolves them before reaching out to the AutowireCandidateResolver...
- targetType = ResolvableType.forMethodReturnType(bd.getResolvedFactoryMethod());
+ targetType = ResolvableType.forMethodReturnType(rbd.getResolvedFactoryMethod());
}
if (targetType == null) {
// Regular case: straight bean instance, with BeanFactory available.
@@ -86,14 +90,20 @@ protected boolean checkGenericTypeMatch(BeanDefinitionHolder bdHolder, Resolvabl
}
// Fallback: no BeanFactory set, or no type resolvable through it
// -> best-effort match against the target class if applicable.
- if (targetType == null && bd.hasBeanClass() && bd.getFactoryMethodName() == null) {
- Class<?> beanClass = bd.getBeanClass();
+ if (targetType == null && rbd != null && rbd.hasBeanClass() && rbd.getFactoryMethodName() == null) {
+ Class<?> beanClass = rbd.getBeanClass();
if (!FactoryBean.class.isAssignableFrom(beanClass)) {
targetType = ResolvableType.forClass(ClassUtils.getUserClass(beanClass));
}
}
}
- return (targetType == null || dependencyType.isAssignableFrom(targetType));
+ if (targetType == null) {
+ return true;
+ }
+ if (descriptor.fallbackMatchAllowed() && targetType.hasUnresolvableGenerics()) {
+ return descriptor.getDependencyType().isAssignableFrom(targetType.getRawClass());
+ }
+ return dependencyType.isAssignableFrom(targetType);
}
| true |
Other | spring-projects | spring-framework | 085176673876afc9282af0a8f4f94ee6a36e9e4e.json | Accept non-generic type match as a fallback
DefaultListableBeanFactory performs a fallback check for autowire candidates now, which GenericTypeAwareAutowireCandidateResolver implements to accept raw type matches if the target class has unresolvable type variables. Full generic matches are still preferred; the BeanFactory will only start looking for fallback matches if the first pass led to an empty result.
Issue: SPR-10993
Issue: SPR-11004 | spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java | @@ -1305,6 +1305,130 @@ public void testGenericsBasedConstructorInjection() {
assertSame(ir, bean.integerRepositoryMap.get("integerRepo"));
}
+ @Test
+ public void testGenericsBasedConstructorInjectionWithNonTypedTarget() {
+ DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
+ bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
+ AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
+ bpp.setBeanFactory(bf);
+ bf.addBeanPostProcessor(bpp);
+ RootBeanDefinition bd = new RootBeanDefinition(RepositoryConstructorInjectionBean.class);
+ bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
+ bf.registerBeanDefinition("annotatedBean", bd);
+ GenericRepository gr = new GenericRepository();
+ bf.registerSingleton("genericRepo", gr);
+
+ RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean");
+ assertSame(gr, bean.stringRepository);
+ assertSame(gr, bean.integerRepository);
+ assertSame(1, bean.stringRepositoryArray.length);
+ assertSame(1, bean.integerRepositoryArray.length);
+ assertSame(gr, bean.stringRepositoryArray[0]);
+ assertSame(gr, bean.integerRepositoryArray[0]);
+ assertSame(1, bean.stringRepositoryList.size());
+ assertSame(1, bean.integerRepositoryList.size());
+ assertSame(gr, bean.stringRepositoryList.get(0));
+ assertSame(gr, bean.integerRepositoryList.get(0));
+ assertSame(1, bean.stringRepositoryMap.size());
+ assertSame(1, bean.integerRepositoryMap.size());
+ assertSame(gr, bean.stringRepositoryMap.get("genericRepo"));
+ assertSame(gr, bean.integerRepositoryMap.get("genericRepo"));
+ }
+
+ @Test
+ public void testGenericsBasedConstructorInjectionWithNonGenericTarget() {
+ DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
+ bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
+ AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
+ bpp.setBeanFactory(bf);
+ bf.addBeanPostProcessor(bpp);
+ RootBeanDefinition bd = new RootBeanDefinition(RepositoryConstructorInjectionBean.class);
+ bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
+ bf.registerBeanDefinition("annotatedBean", bd);
+ SimpleRepository ngr = new SimpleRepository();
+ bf.registerSingleton("simpleRepo", ngr);
+
+ RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean");
+ assertSame(ngr, bean.stringRepository);
+ assertSame(ngr, bean.integerRepository);
+ assertSame(1, bean.stringRepositoryArray.length);
+ assertSame(1, bean.integerRepositoryArray.length);
+ assertSame(ngr, bean.stringRepositoryArray[0]);
+ assertSame(ngr, bean.integerRepositoryArray[0]);
+ assertSame(1, bean.stringRepositoryList.size());
+ assertSame(1, bean.integerRepositoryList.size());
+ assertSame(ngr, bean.stringRepositoryList.get(0));
+ assertSame(ngr, bean.integerRepositoryList.get(0));
+ assertSame(1, bean.stringRepositoryMap.size());
+ assertSame(1, bean.integerRepositoryMap.size());
+ assertSame(ngr, bean.stringRepositoryMap.get("simpleRepo"));
+ assertSame(ngr, bean.integerRepositoryMap.get("simpleRepo"));
+ }
+
+ @Test
+ public void testGenericsBasedConstructorInjectionWithMixedTargets() {
+ DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
+ bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
+ AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
+ bpp.setBeanFactory(bf);
+ bf.addBeanPostProcessor(bpp);
+ RootBeanDefinition bd = new RootBeanDefinition(RepositoryConstructorInjectionBean.class);
+ bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
+ bf.registerBeanDefinition("annotatedBean", bd);
+ StringRepository sr = new StringRepository();
+ bf.registerSingleton("stringRepo", sr);
+ GenericRepository gr = new GenericRepositorySubclass();
+ bf.registerSingleton("genericRepo", gr);
+
+ RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean");
+ assertSame(sr, bean.stringRepository);
+ assertSame(gr, bean.integerRepository);
+ assertSame(1, bean.stringRepositoryArray.length);
+ assertSame(1, bean.integerRepositoryArray.length);
+ assertSame(sr, bean.stringRepositoryArray[0]);
+ assertSame(gr, bean.integerRepositoryArray[0]);
+ assertSame(1, bean.stringRepositoryList.size());
+ assertSame(1, bean.integerRepositoryList.size());
+ assertSame(sr, bean.stringRepositoryList.get(0));
+ assertSame(gr, bean.integerRepositoryList.get(0));
+ assertSame(1, bean.stringRepositoryMap.size());
+ assertSame(1, bean.integerRepositoryMap.size());
+ assertSame(sr, bean.stringRepositoryMap.get("stringRepo"));
+ assertSame(gr, bean.integerRepositoryMap.get("genericRepo"));
+ }
+
+ @Test
+ public void testGenericsBasedConstructorInjectionWithMixedTargetsIncludingNonGeneric() {
+ DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
+ bf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
+ AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
+ bpp.setBeanFactory(bf);
+ bf.addBeanPostProcessor(bpp);
+ RootBeanDefinition bd = new RootBeanDefinition(RepositoryConstructorInjectionBean.class);
+ bd.setScope(RootBeanDefinition.SCOPE_PROTOTYPE);
+ bf.registerBeanDefinition("annotatedBean", bd);
+ StringRepository sr = new StringRepository();
+ bf.registerSingleton("stringRepo", sr);
+ SimpleRepository ngr = new SimpleRepositorySubclass();
+ bf.registerSingleton("simpleRepo", ngr);
+
+ RepositoryConstructorInjectionBean bean = (RepositoryConstructorInjectionBean) bf.getBean("annotatedBean");
+ assertSame(sr, bean.stringRepository);
+ assertSame(ngr, bean.integerRepository);
+ assertSame(1, bean.stringRepositoryArray.length);
+ assertSame(1, bean.integerRepositoryArray.length);
+ assertSame(sr, bean.stringRepositoryArray[0]);
+ assertSame(ngr, bean.integerRepositoryArray[0]);
+ assertSame(1, bean.stringRepositoryList.size());
+ assertSame(1, bean.integerRepositoryList.size());
+ assertSame(sr, bean.stringRepositoryList.get(0));
+ assertSame(ngr, bean.integerRepositoryList.get(0));
+ assertSame(1, bean.stringRepositoryMap.size());
+ assertSame(1, bean.integerRepositoryMap.size());
+ assertSame(sr, bean.stringRepositoryMap.get("stringRepo"));
+ assertSame(ngr, bean.integerRepositoryMap.get("simpleRepo"));
+ }
+
public static class ResourceInjectionBean {
@@ -1859,6 +1983,18 @@ public static class StringRepository implements Repository<String> {
public static class IntegerRepository implements Repository<Integer> {
}
+ public static class GenericRepository<T> implements Repository<T> {
+ }
+
+ public static class GenericRepositorySubclass extends GenericRepository {
+ }
+
+ public static class SimpleRepository implements Repository {
+ }
+
+ public static class SimpleRepositorySubclass extends SimpleRepository {
+ }
+
public static class RepositoryFieldInjectionBean {
| true |
Other | spring-projects | spring-framework | 085176673876afc9282af0a8f4f94ee6a36e9e4e.json | Accept non-generic type match as a fallback
DefaultListableBeanFactory performs a fallback check for autowire candidates now, which GenericTypeAwareAutowireCandidateResolver implements to accept raw type matches if the target class has unresolvable type variables. Full generic matches are still preferred; the BeanFactory will only start looking for fallback matches if the first pass led to an empty result.
Issue: SPR-10993
Issue: SPR-11004 | spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java | @@ -251,27 +251,13 @@ public static Class[] resolveTypeArguments(Class<?> clazz, Class<?> genericIfc)
/**
* Resolve the specified generic type against the given TypeVariable map.
* @param genericType the generic type to resolve
- * @param typeVariableMap the TypeVariable Map to resolved against
+ * @param map the TypeVariable Map to resolved against
* @return the type if it resolves to a Class, or {@code Object.class} otherwise
* @deprecated as of Spring 4.0 in favor of {@link ResolvableType}
*/
@Deprecated
- 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);
+ public static Class<?> resolveType(Type genericType, Map<TypeVariable, Type> map) {
+ return ResolvableType.forType(genericType, new TypeVariableMapVariableResolver(map)).resolve(Object.class);
}
/**
@@ -315,4 +301,26 @@ private static void buildTypeVariableMap(ResolvableType type, Map<TypeVariable,
}
}
+
+ @SuppressWarnings("serial")
+ private static class TypeVariableMapVariableResolver implements ResolvableType.VariableResolver {
+
+ private final Map<TypeVariable, Type> typeVariableMap;
+
+ public TypeVariableMapVariableResolver(Map<TypeVariable, Type> typeVariableMap) {
+ this.typeVariableMap = typeVariableMap;
+ }
+
+ @Override
+ public ResolvableType resolveVariable(TypeVariable<?> variable) {
+ Type type = this.typeVariableMap.get(variable);
+ return (type != null ? ResolvableType.forType(type) : null);
+ }
+
+ @Override
+ public Object getSource() {
+ return this.typeVariableMap;
+ }
+ }
+
} | true |
Other | spring-projects | spring-framework | 085176673876afc9282af0a8f4f94ee6a36e9e4e.json | Accept non-generic type match as a fallback
DefaultListableBeanFactory performs a fallback check for autowire candidates now, which GenericTypeAwareAutowireCandidateResolver implements to accept raw type matches if the target class has unresolvable type variables. Full generic matches are still preferred; the BeanFactory will only start looking for fallback matches if the first pass led to an empty result.
Issue: SPR-10993
Issue: SPR-11004 | spring-core/src/main/java/org/springframework/core/MethodParameter.java | @@ -265,7 +265,8 @@ public Class<?> getNestedParameterType() {
Type type = getGenericParameterType();
if (type instanceof ParameterizedType) {
Integer index = getTypeIndexForCurrentLevel();
- Type arg = ((ParameterizedType) type).getActualTypeArguments()[index != null ? index : 0];
+ Type[] args = ((ParameterizedType) type).getActualTypeArguments();
+ Type arg = args[index != null ? index : args.length - 1];
if (arg instanceof Class) {
return (Class) arg;
} | true |
Other | spring-projects | spring-framework | 085176673876afc9282af0a8f4f94ee6a36e9e4e.json | Accept non-generic type match as a fallback
DefaultListableBeanFactory performs a fallback check for autowire candidates now, which GenericTypeAwareAutowireCandidateResolver implements to accept raw type matches if the target class has unresolvable type variables. Full generic matches are still preferred; the BeanFactory will only start looking for fallback matches if the first pass led to an empty result.
Issue: SPR-10993
Issue: SPR-11004 | spring-core/src/main/java/org/springframework/core/ResolvableType.java | @@ -105,8 +105,7 @@ public final class ResolvableType implements Serializable {
private boolean isResolved = false;
/**
- * Late binding stored copy of the resolved value (valid when {@link #isResolved} is
- * true).
+ * Late binding stored copy of the resolved value (valid when {@link #isResolved} is true).
*/
private Class<?> resolved;
@@ -116,7 +115,6 @@ public final class ResolvableType implements Serializable {
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})
@@ -131,13 +129,25 @@ private ResolvableType(Type type, VariableResolver variableResolver, ResolvableT
/**
- * Return the underling java {@link Type} being managed. With the exception of
+ * Return the underling Java {@link Type} being managed. With the exception of
* the {@link #NONE} constant, this method will never return {@code null}.
*/
public Type getType() {
return this.type;
}
+ /**
+ * Return the underlying Java {@link Class} being managed, if available;
+ * otherwise {@code null}.
+ */
+ public Class<?> getRawClass() {
+ Type rawType = this.type;
+ if (rawType instanceof ParameterizedType) {
+ rawType = ((ParameterizedType) rawType).getRawType();
+ }
+ return (rawType instanceof Class ? (Class) rawType : null);
+ }
+
/**
* Determines if this {@code ResolvableType} is assignable from the specified
* {@code type}. Attempts to follow the same rules as the Java compiler, considering
@@ -161,8 +171,7 @@ private boolean isAssignableFrom(ResolvableType type, boolean checkingGeneric) {
// Deal with array by delegating to the component type
if (isArray()) {
- return (type.isArray() && getComponentType().isAssignableFrom(
- type.getComponentType()));
+ return (type.isArray() && getComponentType().isAssignableFrom(type.getComponentType()));
}
// Deal with wildcard bounds
@@ -171,8 +180,8 @@ private boolean isAssignableFrom(ResolvableType type, boolean checkingGeneric) {
// in the from X is assignable to <? extends Number>
if (typeBounds != null) {
- return (ourBounds != null && ourBounds.isSameKind(typeBounds)
- && ourBounds.isAssignableFrom(typeBounds.getBounds()));
+ return (ourBounds != null && ourBounds.isSameKind(typeBounds) &&
+ ourBounds.isAssignableFrom(typeBounds.getBounds()));
}
// in the form <? extends Number> is assignable to X ...
@@ -189,8 +198,7 @@ private boolean isAssignableFrom(ResolvableType type, boolean checkingGeneric) {
// Recursively check each generic
for (int i = 0; i < getGenerics().length; i++) {
- rtn &= getGeneric(i).isAssignableFrom(
- type.as(resolve(Object.class)).getGeneric(i), true);
+ rtn &= getGeneric(i).isAssignableFrom(type.as(resolve(Object.class)).getGeneric(i), true);
}
return rtn;
@@ -228,8 +236,7 @@ public ResolvableType getComponentType() {
return forType(componentType, this.variableResolver);
}
if (this.type instanceof GenericArrayType) {
- return forType(((GenericArrayType) this.type).getGenericComponentType(),
- this.variableResolver);
+ return forType(((GenericArrayType) this.type).getGenericComponentType(), this.variableResolver);
}
return resolveType().getComponentType();
}
@@ -291,7 +298,7 @@ public ResolvableType as(Class<?> type) {
* @see #getInterfaces()
*/
public ResolvableType getSuperType() {
- final Class<?> resolved = resolve();
+ Class<?> resolved = resolve();
if (resolved == null || resolved.getGenericSuperclass() == null) {
return NONE;
}
@@ -305,7 +312,7 @@ public ResolvableType getSuperType() {
* @see #getSuperType()
*/
public ResolvableType[] getInterfaces() {
- final Class<?> resolved = resolve();
+ Class<?> resolved = resolve();
if (resolved == null || ObjectUtils.isEmpty(resolved.getGenericInterfaces())) {
return EMPTY_TYPES_ARRAY;
}
@@ -321,6 +328,35 @@ public boolean hasGenerics() {
return (getGenerics().length > 0);
}
+ /**
+ * Determine whether the underlying type has unresolvable generics:
+ * either through an unresolvable type variable on the type itself
+ * or through implementing a generic interface in a raw fashion,
+ * i.e. without substituting that interface's type variables.
+ * The result will be {@code true} only in those two scenarios.
+ */
+ public boolean hasUnresolvableGenerics() {
+ ResolvableType[] generics = getGenerics();
+ for (ResolvableType generic : generics) {
+ if (generic.resolve() == null) {
+ return true;
+ }
+ }
+ Class<?> resolved = resolve();
+ Type[] ifcs = resolved.getGenericInterfaces();
+ for (Type ifc : ifcs) {
+ if (ifc instanceof Class) {
+ if (forClass((Class) ifc).hasGenerics()) {
+ return true;
+ }
+ }
+ }
+ if (resolved.getGenericSuperclass() != null) {
+ return getSuperType().hasUnresolvableGenerics();
+ }
+ return false;
+ }
+
/**
* Return a {@link ResolvableType} for the specified nesting level. See
* {@link #getNested(int, Map)} for details.
@@ -362,8 +398,7 @@ public ResolvableType getNested(int nestingLevel, Map<Integer, Integer> typeInde
while (result != ResolvableType.NONE && !result.hasGenerics()) {
result = result.getSuperType();
}
- Integer index = (typeIndexesPerLevel == null ? null
- : typeIndexesPerLevel.get(i));
+ Integer index = (typeIndexesPerLevel != null ? typeIndexesPerLevel.get(i) : null);
index = (index == null ? result.getGenerics().length - 1 : index);
result = result.getGeneric(index);
}
@@ -515,10 +550,8 @@ private Class<?> resolveClass() {
* it cannot be serialized.
*/
ResolvableType resolveType() {
-
if (this.type instanceof ParameterizedType) {
- return forType(((ParameterizedType) this.type).getRawType(),
- this.variableResolver);
+ return forType(((ParameterizedType) this.type).getRawType(), this.variableResolver);
}
if (this.type instanceof WildcardType) {
@@ -535,7 +568,7 @@ ResolvableType resolveType() {
// Try default variable resolution
if (this.variableResolver != null) {
ResolvableType resolved = this.variableResolver.resolveVariable(variable);
- if(resolved != null) {
+ if (resolved != null) {
return resolved;
}
}
@@ -555,7 +588,6 @@ private Type resolveBounds(Type[] bounds) {
}
private ResolvableType resolveVariable(TypeVariable<?> variable) {
-
if (this.type instanceof TypeVariable) {
return resolveType().resolveVariable(variable);
}
@@ -571,8 +603,7 @@ private ResolvableType resolveVariable(TypeVariable<?> variable) {
}
if (parameterizedType.getOwnerType() != null) {
- return forType(parameterizedType.getOwnerType(),
- this.variableResolver).resolveVariable(variable);
+ return forType(parameterizedType.getOwnerType(), this.variableResolver).resolveVariable(variable);
}
}
@@ -627,7 +658,7 @@ public int hashCode() {
}
/**
- * Custom serialization support for {@value #NONE}.
+ * Custom serialization support for {@link #NONE}.
*/
private Object readResolve() throws ObjectStreamException {
return (this.type == null ? NONE : this);
@@ -640,22 +671,7 @@ VariableResolver asVariableResolver() {
if (this == NONE) {
return null;
}
-
- return new VariableResolver() {
-
- private static final long serialVersionUID = 1L;
-
-
- @Override
- public ResolvableType resolveVariable(TypeVariable<?> variable) {
- return ResolvableType.this.resolveVariable(variable);
- }
-
- @Override
- public Object getSource() {
- return ResolvableType.this;
- }
- };
+ return new DefaultVariableResolver();
}
private static boolean variableResolverSourceEquals(VariableResolver o1, VariableResolver o2) {
@@ -842,8 +858,7 @@ public static ResolvableType forMethodParameter(Method method, int parameterInde
* @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);
@@ -858,8 +873,7 @@ public static ResolvableType forMethodParameter(Method method, int parameterInde
*/
public static ResolvableType forMethodParameter(MethodParameter methodParameter) {
Assert.notNull(methodParameter, "MethodParameter must not be null");
- ResolvableType owner = forType(methodParameter.getContainingClass()).as(
- methodParameter.getDeclaringClass());
+ ResolvableType owner = forType(methodParameter.getContainingClass()).as(methodParameter.getDeclaringClass());
return forType(SerializableTypeWrapper.forMethodParameter(methodParameter),
owner.asVariableResolver()).getNested(methodParameter.getNestingLevel(),
methodParameter.typeIndexesPerLevel);
@@ -877,15 +891,13 @@ public static ResolvableType forArrayComponent(final ResolvableType componentTyp
}
/**
- * Return a {@link ResolvableType} for the specified {@link Class} with pre-declared
- * generics.
+ * 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 forClassWithGenerics(Class<?> sourceClass,
- Class<?>... generics) {
+ 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];
@@ -896,44 +908,17 @@ public static ResolvableType forClassWithGenerics(Class<?> sourceClass,
}
/**
- * Return a {@link ResolvableType} for the specified {@link Class} with pre-declared
- * generics.
+ * 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) {
+ public static ResolvableType forClassWithGenerics(Class<?> sourceClass, 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() {
-
- private static final long serialVersionUID = 1L;
-
-
- @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);
+ TypeVariable<?>[] typeVariables = sourceClass.getTypeParameters();
+ return forType(sourceClass, new TypeVariablesVariableResolver(typeVariables, generics));
}
/**
@@ -948,9 +933,8 @@ public static ResolvableType forType(Type type) {
}
/**
- * 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}.
+ * 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
@@ -972,7 +956,7 @@ public static ResolvableType forType(Type type, ResolvableType owner) {
* @return a {@link ResolvableType} for the specified {@link Type} and {@link VariableResolver}
*/
static ResolvableType forType(Type type, VariableResolver variableResolver) {
- if(type == null) {
+ if (type == null) {
return NONE;
}
// Check the cache, we may have a ResolvableType that may have already been resolved
@@ -1002,7 +986,51 @@ static interface VariableResolver extends Serializable {
* @return the resolved variable or {@code null}
*/
ResolvableType resolveVariable(TypeVariable<?> variable);
+ }
+
+
+ @SuppressWarnings("serial")
+ private class DefaultVariableResolver implements VariableResolver {
+
+ @Override
+ public ResolvableType resolveVariable(TypeVariable<?> variable) {
+ return ResolvableType.this.resolveVariable(variable);
+ }
+
+ @Override
+ public Object getSource() {
+ return ResolvableType.this;
+ }
+ }
+
+
+ @SuppressWarnings("serial")
+ private static class TypeVariablesVariableResolver implements VariableResolver {
+
+ private final TypeVariable[] typeVariables;
+
+ private final ResolvableType[] generics;
+
+ public TypeVariablesVariableResolver(TypeVariable[] typeVariables, ResolvableType[] generics) {
+ Assert.isTrue(typeVariables.length == generics.length, "Mismatched number of generics specified");
+ this.typeVariables = typeVariables;
+ this.generics = generics;
+ }
+ @Override
+ public ResolvableType resolveVariable(TypeVariable<?> variable) {
+ for (int i = 0; i < this.typeVariables.length; i++) {
+ if (this.typeVariables[i].equals(variable)) {
+ return this.generics[i];
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public Object getSource() {
+ return this.generics;
+ }
}
@@ -1016,12 +1044,12 @@ private static class WildcardBounds {
private final ResolvableType[] bounds;
/**
- * Private constructor to create a new {@link WildcardBounds} instance.
+ * Internal constructor to create a new {@link WildcardBounds} instance.
* @param kind the kind of bounds
* @param bounds the bounds
* @see #get(ResolvableType)
*/
- private WildcardBounds(Kind kind, ResolvableType[] bounds) {
+ public WildcardBounds(Kind kind, ResolvableType[] bounds) {
this.kind = kind;
this.bounds = bounds;
}
@@ -1079,8 +1107,7 @@ 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] = ResolvableType.forType(bounds[i],
- type.variableResolver);
+ resolvableBounds[i] = ResolvableType.forType(bounds[i], type.variableResolver);
}
return new WildcardBounds(boundsType, resolvableBounds);
}
@@ -1089,7 +1116,6 @@ public static WildcardBounds get(ResolvableType type) {
* The various kinds of bounds.
*/
static enum Kind {UPPER, LOWER}
-
}
} | true |
Other | spring-projects | spring-framework | 085176673876afc9282af0a8f4f94ee6a36e9e4e.json | Accept non-generic type match as a fallback
DefaultListableBeanFactory performs a fallback check for autowire candidates now, which GenericTypeAwareAutowireCandidateResolver implements to accept raw type matches if the target class has unresolvable type variables. Full generic matches are still preferred; the BeanFactory will only start looking for fallback matches if the first pass led to an empty result.
Issue: SPR-10993
Issue: SPR-11004 | spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java | @@ -48,24 +48,21 @@
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}.
- *
* @author Phillip Webb
*/
@SuppressWarnings("rawtypes")
@RunWith(MockitoJUnitRunner.class)
public class ResolvableTypeTests {
-
@Rule
public ExpectedException thrown = ExpectedException.none();
@@ -1070,7 +1067,7 @@ public void classWithGenericsAs() throws Exception {
@Test
public void forClassWithMismatchedGenerics() throws Exception {
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("Missmatched number of generics specified");
+ thrown.expectMessage("Mismatched number of generics specified");
ResolvableType.forClassWithGenerics(Map.class, Integer.class);
}
| true |
Other | spring-projects | spring-framework | bfa6645c7d8e401ae2d1ea2587dbdd0eaa943265.json | Make changes for timing related test failures | spring-messaging/src/main/java/org/springframework/messaging/simp/BrokerAvailabilityEvent.java | @@ -45,4 +45,10 @@ public BrokerAvailabilityEvent(boolean brokerAvailable, Object source) {
public boolean isBrokerAvailable() {
return this.brokerAvailable;
}
+
+ @Override
+ public String toString() {
+ return "BrokerAvailabilityEvent=" + this.brokerAvailable;
+ }
+
} | true |
Other | spring-projects | spring-framework | bfa6645c7d8e401ae2d1ea2587dbdd0eaa943265.json | Make changes for timing related test failures | spring-messaging/src/test/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandlerIntegrationTests.java | @@ -68,33 +68,32 @@ public class StompBrokerRelayMessageHandlerIntegrationTests {
private int port;
+
@Before
public void setUp() throws Exception {
this.port = SocketUtils.findAvailableTcpPort(61613);
- createAndStartBroker();
-
this.responseChannel = new ExecutorSubscribableChannel();
this.responseHandler = new ExpectationMatchingMessageHandler();
this.responseChannel.subscribe(this.responseHandler);
-
this.eventPublisher = new ExpectationMatchingEventPublisher();
+ startActiveMqBroker();
createAndStartRelay();
}
- private void createAndStartBroker() throws Exception {
+ private void startActiveMqBroker() throws Exception {
this.activeMQBroker = new BrokerService();
- this.activeMQBroker.addConnector("stomp://localhost:" + port);
+ this.activeMQBroker.addConnector("stomp://localhost:" + this.port);
this.activeMQBroker.setStartAsync(false);
this.activeMQBroker.setDeleteAllMessagesOnStartup(true);
this.activeMQBroker.start();
}
private void createAndStartRelay() throws InterruptedException {
this.relay = new StompBrokerRelayMessageHandler(this.responseChannel, Arrays.asList("/queue/", "/topic/"));
- this.relay.setRelayPort(port);
+ this.relay.setRelayPort(this.port);
this.relay.setApplicationEventPublisher(this.eventPublisher);
this.relay.setSystemHeartbeatReceiveInterval(0);
this.relay.setSystemHeartbeatSendInterval(0);
@@ -110,10 +109,28 @@ public void tearDown() throws Exception {
this.relay.stop();
}
finally {
- stopBrokerAndAwait();
+ stopActiveMqBrokerAndAwait();
}
}
+ private void stopActiveMqBrokerAndAwait() throws Exception {
+ logger.debug("Stopping ActiveMQ broker and will await shutdown");
+ if (!this.activeMQBroker.isStarted()) {
+ logger.debug("Broker not running");
+ return;
+ }
+ final CountDownLatch latch = new CountDownLatch(1);
+ this.activeMQBroker.addShutdownHook(new Runnable() {
+ public void run() {
+ latch.countDown();
+ }
+ });
+ this.activeMQBroker.stop();
+ assertTrue("Broker did not stop", latch.await(5, TimeUnit.SECONDS));
+ logger.debug("Broker stopped");
+ }
+
+
// When TCP client is behind interface and configurable:
// test "host" header (virtualHost property)
// test "/user/.." destination is excluded
@@ -122,23 +139,22 @@ public void tearDown() throws Exception {
public void publishSubscribe() throws Exception {
String sess1 = "sess1";
- MessageExchange conn1 = MessageExchangeBuilder.connect(sess1).build();
- this.relay.handleMessage(conn1.message);
- this.responseHandler.expect(conn1);
-
String sess2 = "sess2";
+ MessageExchange conn1 = MessageExchangeBuilder.connect(sess1).build();
MessageExchange conn2 = MessageExchangeBuilder.connect(sess2).build();
- this.relay.handleMessage(conn2.message);
- this.responseHandler.expect(conn2);
+ this.responseHandler.expect(conn1, conn2);
+ this.relay.handleMessage(conn1.message);
+ this.relay.handleMessage(conn2.message);
this.responseHandler.awaitAndAssert();
String subs1 = "subs1";
String destination = "/topic/test";
MessageExchange subscribe = MessageExchangeBuilder.subscribeWithReceipt(sess1, subs1, destination, "r1").build();
- this.relay.handleMessage(subscribe.message);
this.responseHandler.expect(subscribe);
+
+ this.relay.handleMessage(subscribe.message);
this.responseHandler.awaitAndAssert();
MessageExchange send = MessageExchangeBuilder.send(destination, "foo").andExpectMessage(sess1, subs1).build();
@@ -151,7 +167,7 @@ public void publishSubscribe() throws Exception {
@Test
public void brokerUnvailableErrorFrameOnConnect() throws Exception {
- stopBrokerAndAwait();
+ stopActiveMqBrokerAndAwait();
MessageExchange connect = MessageExchangeBuilder.connectWithError("sess1").build();
this.responseHandler.expect(connect);
@@ -162,7 +178,7 @@ public void brokerUnvailableErrorFrameOnConnect() throws Exception {
@Test(expected=MessageDeliveryException.class)
public void messageDeliverExceptionIfSystemSessionForwardFails() throws Exception {
- stopBrokerAndAwait();
+ stopActiveMqBrokerAndAwait();
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SEND);
this.relay.handleMessage(MessageBuilder.withPayload("test".getBytes()).setHeaders(headers).build());
}
@@ -175,20 +191,19 @@ public void brokerBecomingUnvailableTriggersErrorFrame() throws Exception {
this.responseHandler.expect(connect);
this.relay.handleMessage(connect.message);
-
this.responseHandler.awaitAndAssert();
this.responseHandler.expect(MessageExchangeBuilder.error(sess1).build());
- stopBrokerAndAwait();
+ stopActiveMqBrokerAndAwait();
this.responseHandler.awaitAndAssert();
}
@Test
public void brokerAvailabilityEventWhenStopped() throws Exception {
this.eventPublisher.expectAvailabilityStatusChanges(false);
- stopBrokerAndAwait();
+ stopActiveMqBrokerAndAwait();
this.eventPublisher.awaitAndAssert();
}
@@ -198,6 +213,7 @@ public void relayReconnectsIfBrokerComesBackUp() throws Exception {
String sess1 = "sess1";
MessageExchange conn1 = MessageExchangeBuilder.connect(sess1).build();
this.responseHandler.expect(conn1);
+
this.relay.handleMessage(conn1.message);
this.responseHandler.awaitAndAssert();
@@ -212,15 +228,15 @@ public void relayReconnectsIfBrokerComesBackUp() throws Exception {
this.responseHandler.expect(MessageExchangeBuilder.error(sess1).build());
- stopBrokerAndAwait();
+ stopActiveMqBrokerAndAwait();
this.responseHandler.awaitAndAssert();
this.eventPublisher.expectAvailabilityStatusChanges(false);
this.eventPublisher.awaitAndAssert();
this.eventPublisher.expectAvailabilityStatusChanges(true);
- createAndStartBroker();
+ startActiveMqBroker();
this.eventPublisher.awaitAndAssert();
// TODO The event publisher assertions show that the broker's back up and the system relay session
@@ -231,14 +247,15 @@ public void relayReconnectsIfBrokerComesBackUp() throws Exception {
@Test
public void disconnectClosesRelaySessionCleanly() throws Exception {
+
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");
-
this.relay.handleMessage(MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build());
Thread.sleep(2000);
@@ -248,24 +265,6 @@ public void disconnectClosesRelaySessionCleanly() throws Exception {
}
- private void stopBrokerAndAwait() throws Exception {
- logger.debug("Stopping ActiveMQ broker and will await shutdown");
- if (!this.activeMQBroker.isStarted()) {
- logger.debug("Broker not running");
- return;
- }
- final CountDownLatch latch = new CountDownLatch(1);
- this.activeMQBroker.addShutdownHook(new Runnable() {
- public void run() {
- latch.countDown();
- }
- });
- this.activeMQBroker.stop();
- assertTrue("Broker did not stop", latch.await(5, TimeUnit.SECONDS));
- logger.debug("Broker stopped");
- }
-
-
/**
* Handles messages by matching them to expectations including a latch to wait for
* the completion of expected messages.
@@ -408,6 +407,7 @@ public static MessageExchangeBuilder connect(String sessionId) {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.CONNECT);
headers.setSessionId(sessionId);
headers.setAcceptVersion("1.1,1.2");
+ headers.setHeartbeat(0, 0);
Message<?> message = MessageBuilder.withPayload(new byte[0]).setHeaders(headers).build();
MessageExchangeBuilder builder = new MessageExchangeBuilder(message);
@@ -595,8 +595,8 @@ public void expectAvailabilityStatusChanges(Boolean... expected) {
public void awaitAndAssert() throws InterruptedException {
synchronized(this.monitor) {
- long endTime = System.currentTimeMillis() + 6000;
- while (this.expected.size() != this.actual.size() && System.currentTimeMillis() < endTime) {
+ long endTime = System.currentTimeMillis() + 10000;
+ while ((this.expected.size() != this.actual.size()) && (System.currentTimeMillis() < endTime)) {
this.monitor.wait(500);
}
assertEquals(this.expected, this.actual);
@@ -605,6 +605,7 @@ public void awaitAndAssert() throws InterruptedException {
@Override
public void publishEvent(ApplicationEvent event) {
+ logger.debug("Processing ApplicationEvent " + event);
if (event instanceof BrokerAvailabilityEvent) {
synchronized(this.monitor) {
this.actual.add(((BrokerAvailabilityEvent) event).isBrokerAvailable()); | true |
Other | spring-projects | spring-framework | 6b0a62569bfb5c8e20746eead6723a3ea23e443f.json | Fix broken test in MvcNamespaceTests
The testDefaultConfig() method in MvcNamespaceTests creates a new Date()
in its test fixture but then performs an assertion against a hard coded
data string of "2013-10-21". This test therefore only passed yesterday,
on October 21, 2013.
This commit addresses this by changing the hard coded date string to one
based on the current date.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java | @@ -19,6 +19,8 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@@ -161,8 +163,8 @@ public void testDefaultConfig() throws Exception {
testController.testBind(now, null, null);
MvcUrls mvcUrls = this.appContext.getBean(MvcUrls.class);
UriComponents uriComponents = mvcUrls.linkToMethodOn(testController);
-
- assertEquals("http://localhost/?date=2013-10-21", uriComponents.toUriString());
+ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
+ assertEquals("http://localhost/?date=" + dateFormat.format(now), uriComponents.toUriString());
}
finally {
RequestContextHolder.resetRequestAttributes(); | false |
Other | spring-projects | spring-framework | e95bd9e25086bf1dad37f8d08293c948621faf6b.json | Add @PropertySources and ignoreResourceNotFound
Support repeatable @PropertySource annotations in Java 8 and add
@PropertySources container annotation for Java 6/7. Also add an
ignoreResourceNotFound attribute to @PropertySource allowing missing
property resources to be silently ignored.
This commit also introduces some generally useful methods to
AnnotationUtils for working with @Repeatable annotations.
Issue: SPR-8371 | spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigUtils.java | @@ -16,7 +16,9 @@
package org.springframework.context.annotation;
+import java.util.Collections;
import java.util.LinkedHashSet;
+import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
@@ -32,6 +34,7 @@
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.core.type.AnnotatedTypeMetadata;
+import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
/**
@@ -44,6 +47,7 @@
* @author Mark Fisher
* @author Juergen Hoeller
* @author Chris Beams
+ * @author Phillip Webb
* @since 2.5
* @see ContextAnnotationAutowireCandidateResolver
* @see CommonAnnotationBeanPostProcessor
@@ -297,12 +301,40 @@ static BeanDefinitionHolder applyScopedProxyMode(
return ScopedProxyCreator.createScopedProxy(definition, registry, proxyTargetClass);
}
- static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, Class<?> annoClass) {
- return attributesFor(metadata, annoClass.getName());
+ static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, Class<?> annotationClass) {
+ return attributesFor(metadata, annotationClass.getName());
}
- static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, String annoClassName) {
- return AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annoClassName, false));
+ static AnnotationAttributes attributesFor(AnnotatedTypeMetadata metadata, String annotationClassName) {
+ return AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annotationClassName, false));
+ }
+
+ static Set<AnnotationAttributes> attributesForRepeatable(AnnotationMetadata metadata,
+ Class<?> containerClass, Class<?> annotationClass) {
+ return attributesForRepeatable(metadata, containerClass.getName(), annotationClass.getName());
+ }
+
+ @SuppressWarnings("unchecked")
+ static Set<AnnotationAttributes> attributesForRepeatable(AnnotationMetadata metadata,
+ String containerClassName, String annotationClassName) {
+ Set<AnnotationAttributes> result = new LinkedHashSet<AnnotationAttributes>();
+
+ addAttributesIfNotNull(result, metadata.getAnnotationAttributes(annotationClassName, false));
+
+ Map<String, Object> container = metadata.getAnnotationAttributes(containerClassName, false);
+ if (container != null && container.containsKey("value")) {
+ for (Map<String, Object> containedAttributes : (Map<String, Object>[]) container.get("value")) {
+ addAttributesIfNotNull(result, containedAttributes);
+ }
+ }
+ return Collections.unmodifiableSet(result);
+ }
+
+ private static void addAttributesIfNotNull(Set<AnnotationAttributes> result,
+ Map<String, Object> attributes) {
+ if (attributes != null) {
+ result.add(AnnotationAttributes.fromMap(attributes));
+ }
}
} | true |
Other | spring-projects | spring-framework | e95bd9e25086bf1dad37f8d08293c948621faf6b.json | Add @PropertySources and ignoreResourceNotFound
Support repeatable @PropertySource annotations in Java 8 and add
@PropertySources container annotation for Java 6/7. Also add an
ignoreResourceNotFound attribute to @PropertySource allowing missing
property resources to be silently ignored.
This commit also introduces some generally useful methods to
AnnotationUtils for working with @Repeatable annotations.
Issue: SPR-8371 | spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java | @@ -16,6 +16,7 @@
package org.springframework.context.annotation;
+import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -55,6 +56,7 @@
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
+import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePropertySource;
import org.springframework.core.type.AnnotationMetadata;
@@ -63,6 +65,8 @@
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AssignableTypeFilter;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
/**
@@ -112,7 +116,7 @@ public int compare(DeferredImportSelectorHolder o1, DeferredImportSelectorHolder
private final Map<String, ConfigurationClass> knownSuperclasses = new HashMap<String, ConfigurationClass>();
- private final Stack<PropertySource<?>> propertySources = new Stack<PropertySource<?>>();
+ private final MultiValueMap<String, PropertySource<?>> propertySources = new LinkedMultiValueMap<String, PropertySource<?>>();
private final ImportStack importStack = new ImportStack();
@@ -218,9 +222,9 @@ protected final SourceClass doProcessConfigurationClass(ConfigurationClass confi
processMemberClasses(configClass, sourceClass);
// process any @PropertySource annotations
- AnnotationAttributes propertySource = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(),
- org.springframework.context.annotation.PropertySource.class);
- if (propertySource != null) {
+ for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
+ sourceClass.getMetadata(), PropertySources.class,
+ org.springframework.context.annotation.PropertySource.class)) {
processPropertySource(propertySource);
}
@@ -301,29 +305,29 @@ private void processMemberClasses(ConfigurationClass configClass, SourceClass so
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
String name = propertySource.getString("name");
String[] locations = propertySource.getStringArray("value");
+ boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");
int locationCount = locations.length;
if (locationCount == 0) {
throw new IllegalArgumentException("At least one @PropertySource(value) location is required");
}
- for (int i = 0; i < locationCount; i++) {
- locations[i] = this.environment.resolveRequiredPlaceholders(locations[i]);
- }
- ClassLoader classLoader = this.resourceLoader.getClassLoader();
- if (!StringUtils.hasText(name)) {
- for (String location : locations) {
- this.propertySources.push(new ResourcePropertySource(location, classLoader));
- }
- }
- else {
- if (locationCount == 1) {
- this.propertySources.push(new ResourcePropertySource(name, locations[0], classLoader));
+ for (String location : locations) {
+ Resource resource = this.resourceLoader.getResource(
+ this.environment.resolveRequiredPlaceholders(location));
+ try {
+ if (!StringUtils.hasText(name) || this.propertySources.containsKey(name)) {
+ // We need to ensure unique names when the property source will
+ // ultimately end up in a composite
+ ResourcePropertySource ps = new ResourcePropertySource(resource);
+ this.propertySources.add((StringUtils.hasText(name) ? name : ps.getName()), ps);
+ }
+ else {
+ this.propertySources.add(name, new ResourcePropertySource(name, resource));
+ }
}
- else {
- CompositePropertySource ps = new CompositePropertySource(name);
- for (int i = locations.length - 1; i >= 0; i--) {
- ps.addPropertySource(new ResourcePropertySource(locations[i], classLoader));
+ catch (FileNotFoundException ex) {
+ if (!ignoreResourceNotFound) {
+ throw ex;
}
- this.propertySources.push(ps);
}
}
}
@@ -473,10 +477,27 @@ public Set<ConfigurationClass> getConfigurationClasses() {
return this.configurationClasses;
}
- public Stack<PropertySource<?>> getPropertySources() {
- return this.propertySources;
+ public List<PropertySource<?>> getPropertySources() {
+ List<PropertySource<?>> propertySources = new LinkedList<PropertySource<?>>();
+ for (Map.Entry<String, List<PropertySource<?>>> entry : this.propertySources.entrySet()) {
+ propertySources.add(0, collatePropertySources(entry.getKey(), entry.getValue()));
+ }
+ return propertySources;
}
+ private PropertySource<?> collatePropertySources(String name,
+ List<PropertySource<?>> propertySources) {
+ if (propertySources.size() == 1) {
+ return propertySources.get(0);
+ }
+ CompositePropertySource result = new CompositePropertySource(name);
+ for (int i = propertySources.size() - 1; i >= 0; i--) {
+ result.addPropertySource(propertySources.get(i));
+ }
+ return result;
+ }
+
+
ImportRegistry getImportRegistry() {
return this.importStack;
} | true |
Other | spring-projects | spring-framework | e95bd9e25086bf1dad37f8d08293c948621faf6b.json | Add @PropertySources and ignoreResourceNotFound
Support repeatable @PropertySource annotations in Java 8 and add
@PropertySources container annotation for Java 6/7. Also add an
ignoreResourceNotFound attribute to @PropertySource allowing missing
property resources to be silently ignored.
This commit also introduces some generally useful methods to
AnnotationUtils for working with @Repeatable annotations.
Issue: SPR-8371 | spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java | @@ -21,13 +21,12 @@
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
+import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.Stack;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.BeanClassLoaderAware;
@@ -298,16 +297,16 @@ public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
parser.validate();
// Handle any @PropertySource annotations
- Stack<PropertySource<?>> parsedPropertySources = parser.getPropertySources();
+ List<PropertySource<?>> parsedPropertySources = parser.getPropertySources();
if (!parsedPropertySources.isEmpty()) {
if (!(this.environment instanceof ConfigurableEnvironment)) {
logger.warn("Ignoring @PropertySource annotations. " +
"Reason: Environment must implement ConfigurableEnvironment");
}
else {
MutablePropertySources envPropertySources = ((ConfigurableEnvironment)this.environment).getPropertySources();
- while (!parsedPropertySources.isEmpty()) {
- envPropertySources.addLast(parsedPropertySources.pop());
+ for (PropertySource<?> propertySource : parsedPropertySources) {
+ envPropertySources.addLast(propertySource);
}
}
} | true |
Other | spring-projects | spring-framework | e95bd9e25086bf1dad37f8d08293c948621faf6b.json | Add @PropertySources and ignoreResourceNotFound
Support repeatable @PropertySource annotations in Java 8 and add
@PropertySources container annotation for Java 6/7. Also add an
ignoreResourceNotFound attribute to @PropertySource allowing missing
property resources to be silently ignored.
This commit also introduces some generally useful methods to
AnnotationUtils for working with @Repeatable annotations.
Issue: SPR-8371 | spring-context/src/main/java/org/springframework/context/annotation/PropertySource.java | @@ -1,5 +1,5 @@
/*
- * Copyright 2002-2011 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 java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
+import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@@ -132,7 +133,9 @@
* Javadoc for details.
*
* @author Chris Beams
+ * @author Phillip Webb
* @since 3.1
+ * @see PropertySources
* @see Configuration
* @see org.springframework.core.env.PropertySource
* @see org.springframework.core.env.ConfigurableEnvironment#getPropertySources()
@@ -141,6 +144,7 @@
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
+@Repeatable(PropertySources.class)
public @interface PropertySource {
/**
@@ -166,4 +170,13 @@
*/
String[] value();
+ /**
+ * Indicate if failure to find the a {@link #value() property resource} should be
+ * ignored.
+ * <p>{@code true} is appropriate if the properties file is completely optional.
+ * Default is {@code false}.
+ * @since 4.0
+ */
+ boolean ignoreResourceNotFound() default false;
+
} | true |
Other | spring-projects | spring-framework | e95bd9e25086bf1dad37f8d08293c948621faf6b.json | Add @PropertySources and ignoreResourceNotFound
Support repeatable @PropertySource annotations in Java 8 and add
@PropertySources container annotation for Java 6/7. Also add an
ignoreResourceNotFound attribute to @PropertySource allowing missing
property resources to be silently ignored.
This commit also introduces some generally useful methods to
AnnotationUtils for working with @Repeatable annotations.
Issue: SPR-8371 | spring-context/src/main/java/org/springframework/context/annotation/PropertySources.java | @@ -0,0 +1,44 @@
+/*
+ * 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.context.annotation;
+
+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;
+
+/**
+ * Container annotation that aggregates several {@link PropertySource} annotations.
+ *
+ * <p>Can be used natively, declaring several nested {@link PropertySource} annotations.
+ * Can also be used in conjunction with Java 8's support for repeatable annotations,
+ * where {@link PropertySource} can simply be declared several times on the same method,
+ * implicitly generating this container annotation.
+ *
+ * @author Phillip Webb
+ * @since 4.0
+ * @see PropertySource
+ */
+@Target(ElementType.TYPE)
+@Retention(RetentionPolicy.RUNTIME)
+@Documented
+public @interface PropertySources {
+
+ PropertySource[] value();
+
+} | true |
Other | spring-projects | spring-framework | e95bd9e25086bf1dad37f8d08293c948621faf6b.json | Add @PropertySources and ignoreResourceNotFound
Support repeatable @PropertySource annotations in Java 8 and add
@PropertySources container annotation for Java 6/7. Also add an
ignoreResourceNotFound attribute to @PropertySource allowing missing
property resources to be silently ignored.
This commit also introduces some generally useful methods to
AnnotationUtils for working with @Repeatable annotations.
Issue: SPR-8371 | spring-context/src/main/java/org/springframework/scheduling/annotation/Scheduled.java | @@ -42,6 +42,7 @@
* @since 3.0
* @see EnableScheduling
* @see ScheduledAnnotationBeanPostProcessor
+ * @see Schedules
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME) | true |
Other | spring-projects | spring-framework | e95bd9e25086bf1dad37f8d08293c948621faf6b.json | Add @PropertySources and ignoreResourceNotFound
Support repeatable @PropertySource annotations in Java 8 and add
@PropertySources container annotation for Java 6/7. Also add an
ignoreResourceNotFound attribute to @PropertySource allowing missing
property resources to be silently ignored.
This commit also introduces some generally useful methods to
AnnotationUtils for working with @Repeatable annotations.
Issue: SPR-8371 | spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.java | @@ -117,17 +117,8 @@ public Object postProcessAfterInitialization(final Object bean, String beanName)
ReflectionUtils.doWithMethods(targetClass, new MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
- Schedules schedules = AnnotationUtils.getAnnotation(method, Schedules.class);
- if (schedules != null) {
- for (Scheduled scheduled : schedules.value()) {
- processScheduled(scheduled, method, bean);
- }
- }
- else {
- Scheduled scheduled = AnnotationUtils.getAnnotation(method, Scheduled.class);
- if (scheduled != null) {
- processScheduled(scheduled, method, bean);
- }
+ for (Scheduled scheduled : AnnotationUtils.getRepeatableAnnotation(method, Schedules.class, Scheduled.class)) {
+ processScheduled(scheduled, method, bean);
}
}
}); | true |
Other | spring-projects | spring-framework | e95bd9e25086bf1dad37f8d08293c948621faf6b.json | Add @PropertySources and ignoreResourceNotFound
Support repeatable @PropertySource annotations in Java 8 and add
@PropertySources container annotation for Java 6/7. Also add an
ignoreResourceNotFound attribute to @PropertySource allowing missing
property resources to be silently ignored.
This commit also introduces some generally useful methods to
AnnotationUtils for working with @Repeatable annotations.
Issue: SPR-8371 | spring-context/src/test/java/org/springframework/context/annotation/PropertySourceAnnotationTests.java | @@ -16,29 +16,35 @@
package org.springframework.context.annotation;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
+import java.io.FileNotFoundException;
import java.util.Iterator;
import javax.inject.Inject;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
-
import org.springframework.tests.sample.beans.TestBean;
+import static org.hamcrest.CoreMatchers.*;
+import static org.junit.Assert.*;
+
/**
* Tests the processing of @PropertySource annotations on @Configuration classes.
*
* @author Chris Beams
+ * @author Phillip Webb
* @since 3.1
*/
public class PropertySourceAnnotationTests {
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+
@Test
public void withExplicitName() {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
@@ -149,6 +155,29 @@ public void withEmptyResourceLocations() {
ctx.refresh();
}
+ @Test
+ public void withPropertySources() {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithPropertySources.class);
+ assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true));
+ assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true));
+ // p2 should 'win' as it was registered last
+ assertThat(ctx.getEnvironment().getProperty("testbean.name"), equalTo("p2TestBean"));
+ }
+
+ @Test
+ public void withMissingPropertySource() {
+ thrown.expect(BeanDefinitionStoreException.class);
+ thrown.expectCause(isA(FileNotFoundException.class));
+ new AnnotationConfigApplicationContext(ConfigWithMissingPropertySource.class);
+ }
+
+ @Test
+ public void withIgnoredPropertySource() {
+ AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithIgnoredPropertySource.class);
+ assertThat(ctx.getEnvironment().containsProperty("from.p1"), is(true));
+ assertThat(ctx.getEnvironment().containsProperty("from.p2"), is(true));
+ }
+
@Configuration
@PropertySource(value="classpath:${unresolvable}/p1.properties")
@@ -231,6 +260,33 @@ static class ConfigWithMultipleResourceLocations {
}
+ @Configuration
+ @PropertySources({
+ @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/p1.properties"),
+ @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/p2.properties")
+ })
+ static class ConfigWithPropertySources {
+ }
+
+ @Configuration
+ @PropertySources({
+ @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/p1.properties"),
+ @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/missing.properties"),
+ @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/p2.properties")
+ })
+ static class ConfigWithMissingPropertySource {
+ }
+
+
+ @Configuration
+ @PropertySources({
+ @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/p1.properties"),
+ @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/missing.properties", ignoreResourceNotFound=true),
+ @PropertySource(name = "psName", value="classpath:org/springframework/context/annotation/p2.properties")
+ })
+ static class ConfigWithIgnoredPropertySource {
+ }
+
@Configuration
@PropertySource(value = {})
static class ConfigWithEmptyResourceLocations { | true |
Other | spring-projects | spring-framework | e95bd9e25086bf1dad37f8d08293c948621faf6b.json | Add @PropertySources and ignoreResourceNotFound
Support repeatable @PropertySource annotations in Java 8 and add
@PropertySources container annotation for Java 6/7. Also add an
ignoreResourceNotFound attribute to @PropertySource allowing missing
property resources to be silently ignored.
This commit also introduces some generally useful methods to
AnnotationUtils for working with @Repeatable annotations.
Issue: SPR-8371 | spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java | @@ -19,12 +19,18 @@
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.WeakHashMap;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.util.Assert;
+import org.springframework.util.ObjectUtils;
/**
* General utility methods for working with annotations, handling bridge methods (which the compiler
@@ -43,6 +49,7 @@
* @author Sam Brannen
* @author Mark Fisher
* @author Chris Beams
+ * @author Phillip Webb
* @since 2.0
* @see java.lang.reflect.Method#getAnnotations()
* @see java.lang.reflect.Method#getAnnotation(Class)
@@ -117,6 +124,45 @@ public static <A extends Annotation> A getAnnotation(Method method, Class<A> ann
return getAnnotation((AnnotatedElement) resolvedMethod, annotationType);
}
+ /**
+ * Get the possibly repeating {@link Annotation}s of {@code annotationType} from the
+ * supplied {@link Method}. Deals with both a single direct annotation and repeating
+ * annotations nested within a containing annotation.
+ * <p>Correctly handles bridge {@link Method Methods} generated by the compiler.
+ * @param method the method to look for annotations on
+ * @param containerAnnotationType the class of the container that holds the annotations
+ * @param annotationType the annotation class to look for
+ * @return the annotations found
+ * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method)
+ * @since 4.0
+ */
+ public static <A extends Annotation> Set<A> getRepeatableAnnotation(Method method,
+ Class<? extends Annotation> containerAnnotationType, Class<A> annotationType) {
+ Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method);
+ return getRepeatableAnnotation((AnnotatedElement) resolvedMethod,
+ containerAnnotationType, annotationType);
+ }
+
+ /**
+ * Get the possibly repeating {@link Annotation}s of {@code annotationType} from the
+ * supplied {@link AnnotatedElement}. Deals with both a single direct annotation and
+ * repeating annotations nested within a containing annotation.
+ * <p>Correctly handles bridge {@link Method Methods} generated by the compiler.
+ * @param annotatedElement the element to look for annotations on
+ * @param containerAnnotationType the class of the container that holds the annotations
+ * @param annotationType the annotation class to look for
+ * @return the annotations found
+ * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method)
+ * @since 4.0
+ */
+ public static <A extends Annotation> Set<A> getRepeatableAnnotation(AnnotatedElement annotatedElement,
+ Class<? extends Annotation> containerAnnotationType, Class<A> annotationType) {
+ if (annotatedElement.getAnnotations().length == 0) {
+ return Collections.emptySet();
+ }
+ return new AnnotationCollector<A>(containerAnnotationType, annotationType).getResult(annotatedElement);
+ }
+
/**
* Get a single {@link Annotation} of {@code annotationType} from the supplied {@link Method},
* traversing its super methods if no annotation can be found on the given method itself.
@@ -521,4 +567,59 @@ public static Object getDefaultValue(Class<? extends Annotation> annotationType,
}
}
+
+ private static class AnnotationCollector<A extends Annotation> {
+
+
+ private final Class<? extends Annotation> containerAnnotationType;
+
+ private final Class<A> annotationType;
+
+ private final Set<AnnotatedElement> visited = new HashSet<AnnotatedElement>();
+
+ private final Set<A> result = new LinkedHashSet<A>();
+
+
+ public AnnotationCollector(Class<? extends Annotation> containerAnnotationType,
+ Class<A> annotationType) {
+ this.containerAnnotationType = containerAnnotationType;
+ this.annotationType = annotationType;
+ }
+
+
+ public Set<A> getResult(AnnotatedElement element) {
+ process(element);
+ return Collections.unmodifiableSet(this.result);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void process(AnnotatedElement annotatedElement) {
+ if (this.visited.add(annotatedElement)) {
+ for (Annotation annotation : annotatedElement.getAnnotations()) {
+ if (ObjectUtils.nullSafeEquals(this.annotationType, annotation.annotationType())) {
+ this.result.add((A) annotation);
+ }
+ else if (ObjectUtils.nullSafeEquals(this.containerAnnotationType, annotation.annotationType())) {
+ result.addAll(Arrays.asList(getValue(annotation)));
+ }
+ else {
+ process(annotation.annotationType());
+ }
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private A[] getValue(Annotation annotation) {
+ try {
+ Method method = annotation.annotationType().getDeclaredMethod("value");
+ return (A[]) method.invoke(annotation);
+ }
+ catch (Exception ex) {
+ throw new IllegalStateException("Unable to read value from repeating annotation container "
+ + this.containerAnnotationType.getName(), ex);
+ }
+ }
+
+ }
} | true |
Other | spring-projects | spring-framework | e95bd9e25086bf1dad37f8d08293c948621faf6b.json | Add @PropertySources and ignoreResourceNotFound
Support repeatable @PropertySource annotations in Java 8 and add
@PropertySources container annotation for Java 6/7. Also add an
ignoreResourceNotFound attribute to @PropertySource allowing missing
property resources to be silently ignored.
This commit also introduces some generally useful methods to
AnnotationUtils for working with @Repeatable annotations.
Issue: SPR-8371 | spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java | @@ -18,17 +18,21 @@
import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;
+import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
import java.util.Arrays;
+import java.util.HashSet;
import java.util.List;
+import java.util.Set;
import org.junit.Test;
-
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
+import static org.hamcrest.Matchers.*;
+
import static org.junit.Assert.*;
import static org.springframework.core.annotation.AnnotationUtils.*;
@@ -37,6 +41,7 @@
* @author Juergen Hoeller
* @author Sam Brannen
* @author Chris Beams
+ * @author Phillip Webb
*/
public class AnnotationUtilsTests {
@@ -268,6 +273,19 @@ public void testFindAnnotationFromInterfaceWhenSuperDoesNotImplementMethod() thr
assertNotNull(order);
}
+ @Test
+ public void testGetRepeatableFromMethod() throws Exception {
+ Method method = InterfaceWithRepeated.class.getMethod("foo");
+ Set<MyRepeatable> annotions = AnnotationUtils.getRepeatableAnnotation(method,
+ MyRepeatableContainer.class, MyRepeatable.class);
+ Set<String> values = new HashSet<String>();
+ for (MyRepeatable myRepeatable : annotions) {
+ values.add(myRepeatable.value());
+ }
+ assertThat(values, equalTo((Set<String>) new HashSet<String>(
+ Arrays.asList("a", "b", "c", "meta"))));
+ }
+
@Component(value = "meta1")
@Retention(RetentionPolicy.RUNTIME)
@@ -428,10 +446,46 @@ public void foo() {
}
}
+ public static interface InterfaceWithRepeated {
+
+ @MyRepeatable("a")
+ @MyRepeatableContainer({ @MyRepeatable("b"), @MyRepeatable("c") })
+ @MyRepeatableMeta
+ void foo();
+
+ }
+
}
+
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@interface Transactional {
}
+
+
+@Retention(RetentionPolicy.RUNTIME)
+@Inherited
+@interface MyRepeatableContainer {
+
+ MyRepeatable[] value();
+
+}
+
+
+@Retention(RetentionPolicy.RUNTIME)
+@Inherited
+@Repeatable(MyRepeatableContainer.class)
+@interface MyRepeatable {
+
+ String value();
+
+}
+
+
+@Retention(RetentionPolicy.RUNTIME)
+@Inherited
+@MyRepeatable("meta")
+@interface MyRepeatableMeta {
+} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | build.gradle | @@ -689,6 +689,7 @@ project("spring-webmvc") {
testCompile("commons-io:commons-io:1.3")
testCompile("org.hibernate:hibernate-validator:4.3.0.Final")
testCompile("org.apache.httpcomponents:httpclient:4.3-beta2")
+ testCompile("joda-time:joda-time:2.2")
}
// pick up DispatcherServlet.properties in src/main | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-core/src/main/java/org/springframework/core/AnnotationAttribute.java | @@ -1,125 +0,0 @@
-/*
- * Copyright 2012-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.annotation.Annotation;
-import java.lang.reflect.AnnotatedElement;
-import java.lang.reflect.Method;
-
-import org.springframework.core.annotation.AnnotationUtils;
-import org.springframework.util.Assert;
-
-/**
- * Simply helper to reference a dedicated attribute of an {@link Annotation}.
- *
- * @author Oliver Gierke
- */
-public class AnnotationAttribute {
-
- private final Class<? extends Annotation> annotationType;
-
- private final String attributeName;
-
- /**
- * Creates a new {@link AnnotationAttribute} to the {@code value} attribute of the
- * given {@link Annotation} type.
- *
- * @param annotationType must not be {@literal null}.
- */
- public AnnotationAttribute(Class<? extends Annotation> annotationType) {
- this(annotationType, null);
- }
-
- /**
- * Creates a new {@link AnnotationAttribute} for the given {@link Annotation} type and
- * annotation attribute name.
- *
- * @param annotationType must not be {@literal null}.
- * @param attributeName can be {@literal null}, defaults to {@code value}.
- */
- public AnnotationAttribute(Class<? extends Annotation> annotationType,
- String attributeName) {
-
- Assert.notNull(annotationType);
-
- this.annotationType = annotationType;
- this.attributeName = attributeName;
- }
-
- /**
- * Returns the annotation type.
- *
- * @return the annotationType
- */
- public Class<? extends Annotation> getAnnotationType() {
- return annotationType;
- }
-
- /**
- * Reads the {@link Annotation} attribute's value from the given
- * {@link MethodParameter}.
- *
- * @param parameter must not be {@literal null}.
- * @return
- */
- public Object getValueFrom(MethodParameter parameter) {
-
- Assert.notNull(parameter, "MethodParameter must not be null!");
- Annotation annotation = parameter.getParameterAnnotation(annotationType);
- return annotation == null ? null : getValueFrom(annotation);
- }
-
- /**
- * Reads the {@link Annotation} attribute's value from the given type.
- *
- * @param type must not be {@literal null}.
- * @return
- */
- public Object findValueOn(Class<?> type) {
-
- Assert.notNull(type, "Type must not be null!");
- Annotation annotation = AnnotationUtils.findAnnotation(type, annotationType);
- return annotation == null ? null : getValueFrom(annotation);
- }
-
- public Object findValueOn(Method method) {
-
- Assert.notNull(method, "Method must nor be null!");
- Annotation annotation = AnnotationUtils.findAnnotation(method, annotationType);
- return annotation == null ? null : getValueFrom(annotation);
- }
-
- public Object getValueFrom(AnnotatedElement element) {
-
- Assert.notNull(element, "Annotated element must not be null!");
- Annotation annotation = AnnotationUtils.getAnnotation(element, annotationType);
- return annotation == null ? null : getValueFrom(annotation);
- }
-
- /**
- * Returns the {@link Annotation} attribute's value from the given {@link Annotation}.
- *
- * @param annotation must not be {@literal null}.
- * @return
- */
- public Object getValueFrom(Annotation annotation) {
-
- Assert.notNull(annotation, "Annotation must not be null!");
- return attributeName == null ? AnnotationUtils.getValue(annotation)
- : AnnotationUtils.getValue(annotation, attributeName);
- }
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-core/src/main/java/org/springframework/core/MethodParameters.java | @@ -1,170 +0,0 @@
-/*
- * Copyright 2012-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.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.springframework.util.Assert;
-
-/**
- * Value object to represent {@link MethodParameters} to allow to easily find the ones
- * with a given annotation.
- *
- * @author Oliver Gierke
- */
-public class MethodParameters {
-
- private static final ParameterNameDiscoverer DISCOVERER = new LocalVariableTableParameterNameDiscoverer();
-
- private final List<MethodParameter> parameters;
-
- /**
- * Creates a new {@link MethodParameters} from the given {@link Method}.
- *
- * @param method must not be {@literal null}.
- */
- public MethodParameters(Method method) {
- this(method, null);
- }
-
- /**
- * Creates a new {@link MethodParameters} for the given {@link Method} and
- * {@link AnnotationAttribute}. If the latter is given, method parameter names will be
- * looked up from the annotation attribute if present.
- *
- * @param method must not be {@literal null}.
- * @param namingAnnotation can be {@literal null}.
- */
- public MethodParameters(Method method, AnnotationAttribute namingAnnotation) {
-
- Assert.notNull(method);
- this.parameters = new ArrayList<MethodParameter>();
-
- for (int i = 0; i < method.getParameterTypes().length; i++) {
-
- MethodParameter parameter = new AnnotationNamingMethodParameter(method, i,
- namingAnnotation);
- parameter.initParameterNameDiscovery(DISCOVERER);
- parameters.add(parameter);
- }
- }
-
- /**
- * Returns all {@link MethodParameter}s.
- *
- * @return
- */
- public List<MethodParameter> getParameters() {
- return parameters;
- }
-
- /**
- * Returns the {@link MethodParameter} with the given name or {@literal null} if none
- * found.
- *
- * @param name must not be {@literal null} or empty.
- * @return
- */
- public MethodParameter getParameter(String name) {
-
- Assert.hasText(name, "Parameter name must not be null!");
-
- for (MethodParameter parameter : parameters) {
- if (name.equals(parameter.getParameterName())) {
- return parameter;
- }
- }
-
- return null;
- }
-
- /**
- * Returns all {@link MethodParameter}s annotated with the given annotation type.
- *
- * @param annotation must not be {@literal null}.
- * @return
- */
- public List<MethodParameter> getParametersWith(Class<? extends Annotation> annotation) {
-
- Assert.notNull(annotation);
- List<MethodParameter> result = new ArrayList<MethodParameter>();
-
- for (MethodParameter parameter : getParameters()) {
- if (parameter.hasParameterAnnotation(annotation)) {
- result.add(parameter);
- }
- }
-
- return result;
- }
-
- /**
- * Custom {@link MethodParameter} extension that will favor the name configured in the
- * {@link AnnotationAttribute} if set over discovering it.
- *
- * @author Oliver Gierke
- */
- private static class AnnotationNamingMethodParameter extends MethodParameter {
-
- private final AnnotationAttribute attribute;
-
- private String name;
-
- /**
- * Creates a new {@link AnnotationNamingMethodParameter} for the given
- * {@link Method}'s parameter with the given index.
- *
- * @param method must not be {@literal null}.
- * @param parameterIndex
- * @param attribute can be {@literal null}
- */
- public AnnotationNamingMethodParameter(Method method, int parameterIndex,
- AnnotationAttribute attribute) {
-
- super(method, parameterIndex);
- this.attribute = attribute;
-
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.core.MethodParameter#getParameterName()
- */
- @Override
- public String getParameterName() {
-
- if (name != null) {
- return name;
- }
-
- if (attribute != null) {
- Object foundName = attribute.getValueFrom(this);
- if (foundName != null) {
- name = foundName.toString();
- return name;
- }
- }
-
- name = super.getParameterName();
- return name;
- }
- }
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-core/src/test/java/org/springframework/core/AnnotationAttributeUnitTests.java | @@ -1,72 +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.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
-import org.junit.Test;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.*;
-
-/**
- * Unit tests for {@link AnnotationAttribute}.
- *
- * @author Oliver Gierke
- */
-public class AnnotationAttributeUnitTests {
-
- AnnotationAttribute valueAttribute = new AnnotationAttribute(MyAnnotation.class);
-
- AnnotationAttribute nonValueAttribute = new AnnotationAttribute(MyAnnotation.class,
- "nonValue");
-
- @Test
- public void readsAttributesFromType() {
-
- assertThat(valueAttribute.findValueOn(Sample.class), is((Object) "foo"));
- assertThat(nonValueAttribute.findValueOn(Sample.class), is((Object) "bar"));
- }
-
- @Test
- public void findsAttributesFromSubType() {
- assertThat(valueAttribute.findValueOn(SampleSub.class), is((Object) "foo"));
- }
-
- @Test
- public void doesNotGetValueFromSubTyp() {
- assertThat(valueAttribute.getValueFrom(SampleSub.class), is(nullValue()));
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- public static @interface MyAnnotation {
-
- String value() default "";
-
- String nonValue() default "";
- }
-
- @MyAnnotation(value = "foo", nonValue = "bar")
- static class Sample {
-
- }
-
- static class SampleSub extends Sample {
-
- }
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-core/src/test/java/org/springframework/core/MethodParametersUnitTests.java | @@ -1,58 +0,0 @@
-/*
- * Copyright 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.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.reflect.Method;
-
-import org.junit.Test;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.*;
-
-/**
- * Unit tests for {@link MethodParameters}.
- *
- * @author Oliver Gierke
- */
-public class MethodParametersUnitTests {
-
- @Test
- public void prefersAnnotatedParameterOverDiscovered() throws Exception {
-
- Method method = Sample.class.getMethod("method", String.class, String.class);
- MethodParameters parameters = new MethodParameters(method,
- new AnnotationAttribute(Qualifier.class));
-
- assertThat(parameters.getParameter("param"), is(notNullValue()));
- assertThat(parameters.getParameter("foo"), is(notNullValue()));
- assertThat(parameters.getParameter("another"), is(nullValue()));
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- public static @interface Qualifier {
-
- String value() default "";
- }
-
- static class Sample {
-
- public void method(String param, @Qualifier("foo") String another) {
- }
- }
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolver.java | @@ -29,6 +29,8 @@
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.GenericCollectionTypeResolver;
import org.springframework.core.MethodParameter;
+import org.springframework.core.convert.ConversionService;
+import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
@@ -38,10 +40,12 @@
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ValueConstants;
import org.springframework.web.context.request.NativeWebRequest;
+import org.springframework.web.method.support.UriComponentsContributor;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
+import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.WebUtils;
/**
@@ -69,7 +73,10 @@
* @since 3.1
* @see RequestParamMapMethodArgumentResolver
*/
-public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver {
+public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver
+ implements UriComponentsContributor {
+
+ private static final TypeDescriptor STRING_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(String.class);
private final boolean useDefaultResolution;
@@ -83,7 +90,8 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod
* request parameter name is derived from the method parameter name.
*/
public RequestParamMethodArgumentResolver(ConfigurableBeanFactory beanFactory,
- boolean useDefaultResolution) {
+ boolean useDefaultResolution) {
+
super(beanFactory);
this.useDefaultResolution = useDefaultResolution;
}
@@ -218,6 +226,39 @@ protected void handleMissingValue(String paramName, MethodParameter parameter) t
throw new MissingServletRequestParameterException(paramName, parameter.getParameterType().getSimpleName());
}
+ @Override
+ public void contributeMethodArgument(MethodParameter parameter, Object value,
+ UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {
+
+ Class<?> paramType = parameter.getParameterType();
+ if (Map.class.isAssignableFrom(paramType) || MultipartFile.class.equals(paramType) ||
+ "javax.servlet.http.Part".equals(paramType.getName())) {
+ return;
+ }
+
+ RequestParam annot = parameter.getParameterAnnotation(RequestParam.class);
+ String name = StringUtils.isEmpty(annot.value()) ? parameter.getParameterName() : annot.value();
+
+ if (value == null) {
+ builder.queryParam(name);
+ }
+ else if (value instanceof Collection) {
+ for (Object v : (Collection) value) {
+ v = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), v);
+ builder.queryParam(name, v);
+ }
+ }
+ else {
+ builder.queryParam(name, formatUriValue(conversionService, new TypeDescriptor(parameter), value));
+ }
+ }
+
+ protected String formatUriValue(ConversionService cs, TypeDescriptor sourceType, Object value) {
+ return (cs != null) ?
+ (String) cs.convert(value, sourceType, STRING_TYPE_DESCRIPTOR) : null;
+ }
+
+
private class RequestParamNamedValueInfo extends NamedValueInfo {
private RequestParamNamedValueInfo() {
@@ -228,4 +269,5 @@ private RequestParamNamedValueInfo(RequestParam annotation) {
super(annotation.value(), annotation.required(), annotation.defaultValue());
}
}
+
} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-web/src/main/java/org/springframework/web/method/support/UriComponentsContributor.java | @@ -0,0 +1,56 @@
+/*
+ * Copyright 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.web.method.support;
+
+import java.util.Map;
+
+import org.springframework.core.MethodParameter;
+import org.springframework.core.convert.ConversionService;
+import org.springframework.web.util.UriComponents;
+import org.springframework.web.util.UriComponentsBuilder;
+
+/**
+ * Strategy for contributing to the building of a {@link UriComponents} by
+ * looking at a method parameter and an argument value and deciding what
+ * part of the target URL should be updated.
+ *
+ * @author Oliver Gierke
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public interface UriComponentsContributor {
+
+ /**
+ * Whether this contributor supports the given method parameter.
+ */
+ boolean supportsParameter(MethodParameter parameter);
+
+ /**
+ * Process the given method argument and either update the
+ * {@link UriComponentsBuilder} or add to the map with URI variables to use to
+ * expand the URI after all arguments are processed.
+ *
+ * @param parameter the controller method parameter, never {@literal null}.
+ * @param value the argument value, possibly {@literal null}.
+ * @param builder the builder to update, never {@literal null}.
+ * @param uriVariables a map to add URI variables to, never {@literal null}.
+ * @param conversionService a ConversionService to format values as Strings
+ */
+ void contributeMethodArgument(MethodParameter parameter, Object value, UriComponentsBuilder builder,
+ Map<String, Object> uriVariables, ConversionService conversionService);
+
+} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java | @@ -248,7 +248,7 @@ public static UriComponentsBuilder fromHttpUrl(String httpUrl) {
throw new IllegalArgumentException("[" + httpUrl + "] is not a valid HTTP URL");
}
}
-
+
// build methods
@@ -362,6 +362,43 @@ public UriComponentsBuilder scheme(String scheme) {
return this;
}
+ /**
+ * Initializes all components of this URI builder from the given {@link UriComponents}.
+ * @param uriComponents the UriComponents instance
+ * @return this UriComponentsBuilder
+ */
+ public UriComponentsBuilder uriComponents(UriComponents uriComponents) {
+ Assert.notNull(uriComponents, "'uriComponents' must not be null");
+ this.scheme = uriComponents.getScheme();
+ if (uriComponents instanceof OpaqueUriComponents) {
+ this.ssp = uriComponents.getSchemeSpecificPart();
+ resetHierarchicalComponents();
+ }
+ else {
+ if (uriComponents.getUserInfo() != null) {
+ this.userInfo = uriComponents.getUserInfo();
+ }
+ if (uriComponents.getHost() != null) {
+ this.host = uriComponents.getHost();
+ }
+ if (uriComponents.getPort() != -1) {
+ this.port = uriComponents.getPort();
+ }
+ if (StringUtils.hasLength(uriComponents.getPath())) {
+ this.pathBuilder = new CompositePathComponentBuilder(uriComponents.getPath());
+ }
+ if (!uriComponents.getQueryParams().isEmpty()) {
+ this.queryParams.clear();
+ this.queryParams.putAll(uriComponents.getQueryParams());
+ }
+ resetSchemeSpecificPart();
+ }
+ if (uriComponents.getFragment() != null) {
+ this.fragment = uriComponents.getFragment();
+ }
+ return this;
+ }
+
/**
* Set the URI scheme-specific-part. When invoked, this method overwrites
* {@linkplain #userInfo(String) user-info}, {@linkplain #host(String) host},
@@ -554,36 +591,6 @@ public UriComponentsBuilder fragment(String fragment) {
return this;
}
- public UriComponentsBuilder with(UriComponentsBuilder builder) {
-
- UriComponents components = builder.build().normalize();
-
- if (StringUtils.hasText(components.getScheme())) {
- scheme(components.getScheme());
- }
-
- if (StringUtils.hasText(components.getHost())) {
- host(components.getHost());
- }
-
- if (components.getPort() != -1) {
- port(components.getPort());
- }
-
- if (StringUtils.hasText(components.getPath())) {
- path(components.getPath());
- }
-
- if (StringUtils.hasText(components.getQuery())) {
- query(components.getQuery());
- }
-
- if (StringUtils.hasText(components.getFragment())) {
- fragment(components.getFragment());
- }
-
- return this;
- }
private interface PathComponentBuilder {
| true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java | @@ -207,6 +207,13 @@ public BeanDefinition parse(Element element, ParserContext parserContext) {
handlerAdapterDef.getPropertyValues().add("deferredResultInterceptors", deferredResultInterceptors);
String handlerAdapterName = parserContext.getReaderContext().registerWithGeneratedName(handlerAdapterDef);
+ String mvcUrlsName = "mvcUrls";
+ RootBeanDefinition mvcUrlsDef = new RootBeanDefinition(DefaultMvcUrlsFactoryBean.class);
+ mvcUrlsDef.setSource(source);
+ mvcUrlsDef.getPropertyValues().addPropertyValue("handlerAdapter", handlerAdapterDef);
+ mvcUrlsDef.getPropertyValues().addPropertyValue("conversionService", conversionService);
+ parserContext.getReaderContext().getRegistry().registerBeanDefinition(mvcUrlsName, mvcUrlsDef);
+
RootBeanDefinition csInterceptorDef = new RootBeanDefinition(ConversionServiceExposingInterceptor.class);
csInterceptorDef.setSource(source);
csInterceptorDef.getConstructorArgumentValues().addIndexedArgumentValue(0, conversionService);
@@ -242,6 +249,7 @@ public BeanDefinition parse(Element element, ParserContext parserContext) {
parserContext.registerComponent(new BeanComponentDefinition(handlerMappingDef, methodMappingName));
parserContext.registerComponent(new BeanComponentDefinition(handlerAdapterDef, handlerAdapterName));
+ parserContext.registerComponent(new BeanComponentDefinition(mvcUrlsDef, mvcUrlsName));
parserContext.registerComponent(new BeanComponentDefinition(exceptionHandlerExceptionResolver, methodExceptionResolverName));
parserContext.registerComponent(new BeanComponentDefinition(responseStatusExceptionResolver, responseStatusExceptionResolverName));
parserContext.registerComponent(new BeanComponentDefinition(defaultExceptionResolver, defaultExceptionResolverName)); | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/config/DefaultMvcUrlsFactoryBean.java | @@ -0,0 +1,89 @@
+/*
+ * 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.web.servlet.config;
+
+import org.springframework.beans.factory.FactoryBean;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.core.convert.ConversionService;
+import org.springframework.web.method.support.HandlerMethodArgumentResolver;
+import org.springframework.web.method.support.UriComponentsContributor;
+import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
+import org.springframework.web.servlet.mvc.support.DefaultMvcUrls;
+import org.springframework.web.servlet.mvc.support.MvcUrls;
+
+
+/**
+ * A factory bean for creating an instance of {@link MvcUrls} that discovers
+ * {@link UriComponentsContributor}s by obtaining the
+ * {@link HandlerMethodArgumentResolver}s configured in a
+ * {@link RequestMappingHandlerAdapter}.
+ * <p>
+ * This is mainly provided as a convenience in XML configuration. Otherwise call the
+ * constructors of {@link DefaultMvcUrls} directly. Also note the MVC Java config and
+ * XML namespace already create an instance of {@link MvcUrls} and when using either
+ * of them this {@code FactoryBean} is not needed.
+ *
+ * @author Rossen Stoyanchev
+ * @since 4.0
+ */
+public class DefaultMvcUrlsFactoryBean implements InitializingBean, FactoryBean<MvcUrls> {
+
+ private RequestMappingHandlerAdapter handlerAdapter;
+
+ private ConversionService conversionService;
+
+ private MvcUrls mvcUrls;
+
+
+ /**
+ * Provide a {@link RequestMappingHandlerAdapter} from which to obtain
+ * the list of configured {@link HandlerMethodArgumentResolver}s. This
+ * is provided for ease of configuration in XML.
+ */
+ public void setHandlerAdapter(RequestMappingHandlerAdapter handlerAdapter) {
+ this.handlerAdapter = handlerAdapter;
+ }
+
+ /**
+ * Configure the {@link ConversionService} instance that {@link MvcUrls} should
+ * use to format Object values being added to a URI.
+ */
+ public void setConversionService(ConversionService conversionService) {
+ this.conversionService = conversionService;
+ }
+
+ @Override
+ public void afterPropertiesSet() throws Exception {
+ this.mvcUrls = new DefaultMvcUrls(this.handlerAdapter.getArgumentResolvers(), this.conversionService);
+ }
+
+ @Override
+ public MvcUrls getObject() throws Exception {
+ return this.mvcUrls;
+ }
+
+ @Override
+ public Class<?> getObjectType() {
+ return MvcUrls.class;
+ }
+
+ @Override
+ public boolean isSingleton() {
+ return true;
+ }
+
+} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java | @@ -78,6 +78,8 @@
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
+import org.springframework.web.servlet.mvc.support.DefaultMvcUrls;
+import org.springframework.web.servlet.mvc.support.MvcUrls;
/**
* This is the main class providing the configuration behind the MVC Java config.
@@ -563,6 +565,15 @@ protected void addFormatters(FormatterRegistry registry) {
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
}
+ /**
+ * Return an instance of {@link MvcUrls} for injection into controllers to create
+ * URLs by referencing controllers and controller methods.
+ */
+ @Bean
+ public MvcUrls mvcUrls() {
+ return new DefaultMvcUrls(requestMappingHandlerAdapter().getArgumentResolvers(), mvcConversionService());
+ }
+
/**
* Returns a {@link HttpRequestHandlerAdapter} for processing requests
* with {@link HttpRequestHandler}s. | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/hypermedia/AnnotatedParametersParameterAccessor.java | @@ -1,160 +0,0 @@
-/*
- * Copyright 2012-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.web.servlet.hypermedia;
-
-import java.lang.annotation.Annotation;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.springframework.core.AnnotationAttribute;
-import org.springframework.core.MethodParameter;
-import org.springframework.core.MethodParameters;
-import org.springframework.core.convert.ConversionService;
-import org.springframework.core.convert.TypeDescriptor;
-import org.springframework.format.support.DefaultFormattingConversionService;
-import org.springframework.util.Assert;
-import org.springframework.util.StringUtils;
-import org.springframework.web.servlet.hypermedia.RecordedInvocationUtils.RecordedMethodInvocation;
-import org.springframework.web.util.UriTemplate;
-
-/**
- * Value object to allow accessing {@link RecordedMethodInvocation} parameters with the
- * configured {@link AnnotationAttribute}.
- *
- * @author Oliver Gierke
- */
-class AnnotatedParametersParameterAccessor {
-
- private final AnnotationAttribute attribute;
-
- /**
- * Creates a new {@link AnnotatedParametersParameterAccessor} using the given
- * {@link AnnotationAttribute}.
- *
- * @param attribute must not be {@literal null}.
- */
- public AnnotatedParametersParameterAccessor(AnnotationAttribute attribute) {
-
- Assert.notNull(attribute);
- this.attribute = attribute;
- }
-
- /**
- * Returns {@link BoundMethodParameter}s contained in the given
- * {@link RecordedMethodInvocation}.
- *
- * @param invocation must not be {@literal null}.
- * @return
- */
- public List<BoundMethodParameter> getBoundParameters(RecordedMethodInvocation invocation) {
-
- Assert.notNull(invocation, "RecordedMethodInvocation must not be null!");
-
- MethodParameters parameters = new MethodParameters(invocation.getMethod());
- Object[] arguments = invocation.getArguments();
- List<BoundMethodParameter> result = new ArrayList<BoundMethodParameter>();
-
- for (MethodParameter parameter : parameters.getParametersWith(attribute.getAnnotationType())) {
- result.add(new BoundMethodParameter(parameter,
- arguments[parameter.getParameterIndex()], attribute));
- }
-
- return result;
- }
-
- /**
- * Represents a {@link MethodParameter} alongside the value it has been bound to.
- *
- * @author Oliver Gierke
- */
- static class BoundMethodParameter {
-
- private static final ConversionService CONVERSION_SERVICE = new DefaultFormattingConversionService();
-
- private static final TypeDescriptor STRING_DESCRIPTOR = TypeDescriptor.valueOf(String.class);
-
- private final MethodParameter parameter;
-
- private final Object value;
-
- private final AnnotationAttribute attribute;
-
- private final TypeDescriptor parameterTypeDecsriptor;
-
- /**
- * Creates a new {@link BoundMethodParameter}
- *
- * @param parameter
- * @param value
- * @param attribute
- */
- public BoundMethodParameter(MethodParameter parameter, Object value,
- AnnotationAttribute attribute) {
-
- Assert.notNull(parameter, "MethodParameter must not be null!");
-
- this.parameter = parameter;
- this.value = value;
- this.attribute = attribute;
- this.parameterTypeDecsriptor = TypeDescriptor.nested(parameter, 0);
- }
-
- /**
- * Returns the name of the {@link UriTemplate} variable to be bound. The name will
- * be derived from the configured {@link AnnotationAttribute} or the
- * {@link MethodParameter} name as fallback.
- *
- * @return
- */
- public String getVariableName() {
-
- if (attribute == null) {
- return parameter.getParameterName();
- }
-
- Annotation annotation = parameter.getParameterAnnotation(attribute.getAnnotationType());
- String annotationAttributeValue = attribute.getValueFrom(annotation).toString();
- return StringUtils.hasText(annotationAttributeValue) ? annotationAttributeValue
- : parameter.getParameterName();
- }
-
- /**
- * Returns the raw value bound to the {@link MethodParameter}.
- *
- * @return
- */
- public Object getValue() {
- return value;
- }
-
- /**
- * Returns the bound value converted into a {@link String} based on default
- * conversion service setup.
- *
- * @return
- */
- public String asString() {
-
- if (value == null) {
- return null;
- }
-
- return (String) CONVERSION_SERVICE.convert(value, parameterTypeDecsriptor,
- STRING_DESCRIPTOR);
- }
- }
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/hypermedia/AnnotationMappingDiscoverer.java | @@ -1,121 +0,0 @@
-/*
- * Copyright 2012 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.web.servlet.hypermedia;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-
-import org.springframework.core.AnnotationAttribute;
-import org.springframework.util.Assert;
-
-/**
- * {@link MappingDiscoverer} implementation that inspects mappings from a particular
- * annotation.
- *
- * @author Oliver Gierke
- */
-class AnnotationMappingDiscoverer {
-
- private final AnnotationAttribute attribute;
-
- /**
- * Creates an {@link AnnotationMappingDiscoverer} for the given annotation type. Will
- * lookup the {@code value} attribute by default.
- *
- * @param annotation must not be {@literal null}.
- */
- public AnnotationMappingDiscoverer(Class<? extends Annotation> annotation) {
- this(new AnnotationAttribute(annotation));
- }
-
- /**
- * Creates an {@link AnnotationMappingDiscoverer} for the given annotation type and
- * attribute name.
- *
- * @param annotation must not be {@literal null}.
- * @param mappingAttributeName if {@literal null}, it defaults to {@code value}.
- */
- public AnnotationMappingDiscoverer(AnnotationAttribute attribute) {
-
- Assert.notNull(attribute);
- this.attribute = attribute;
- }
-
- /**
- * Returns the mapping associated with the given type.
- *
- * @param type must not be {@literal null}.
- * @return the type-level mapping or {@literal null} in case none is present.
- */
- public String getMapping(Class<?> type) {
-
- String[] mapping = getMappingFrom(attribute.findValueOn(type));
-
- if (mapping.length > 1) {
- throw new IllegalStateException(String.format(
- "Multiple class level mappings defined on class %s!", type.getName()));
- }
-
- return mapping.length == 0 ? null : mapping[0];
- }
-
- /**
- * Returns the mapping associated with the given {@link Method}. This will include the
- * type-level mapping.
- *
- * @param method must not be {@literal null}.
- * @return the method mapping including the type-level one or {@literal null} if
- * neither of them present.
- */
- public String getMapping(Method method) {
-
- String[] mapping = getMappingFrom(attribute.findValueOn(method));
-
- if (mapping.length > 1) {
- throw new IllegalStateException(String.format(
- "Multiple method level mappings defined on method %s!",
- method.toString()));
- }
-
- String typeMapping = getMapping(method.getDeclaringClass());
-
- if (mapping == null || mapping.length == 0) {
- return typeMapping;
- }
-
- return typeMapping == null || "/".equals(typeMapping) ? mapping[0] : typeMapping
- + mapping[0];
- }
-
- private String[] getMappingFrom(Object annotationValue) {
-
- if (annotationValue instanceof String) {
- return new String[] { (String) annotationValue };
- }
- else if (annotationValue instanceof String[]) {
- return (String[]) annotationValue;
- }
- else if (annotationValue == null) {
- return new String[0];
- }
-
- throw new IllegalStateException(
- String.format(
- "Unsupported type for the mapping attribute! Support String and String[] but got %s!",
- annotationValue.getClass()));
- }
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/hypermedia/MvcUriComponentsBuilder.java | @@ -1,328 +0,0 @@
-/*
- * Copyright 2012-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.web.servlet.hypermedia;
-
-import java.lang.reflect.Method;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.core.AnnotationAttribute;
-import org.springframework.core.MethodParameter;
-import org.springframework.core.MethodParameters;
-import org.springframework.util.Assert;
-import org.springframework.util.StringUtils;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.context.request.RequestAttributes;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
-import org.springframework.web.context.support.SpringBeanAutowiringSupport;
-import org.springframework.web.method.support.HandlerMethodArgumentResolver;
-import org.springframework.web.servlet.hypermedia.AnnotatedParametersParameterAccessor.BoundMethodParameter;
-import org.springframework.web.servlet.hypermedia.RecordedInvocationUtils.LastInvocationAware;
-import org.springframework.web.servlet.hypermedia.RecordedInvocationUtils.RecordedMethodInvocation;
-import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
-import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
-import org.springframework.web.util.UriComponents;
-//import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
-import org.springframework.web.util.UriComponentsBuilder;
-import org.springframework.web.util.UriTemplate;
-
-import static org.springframework.web.servlet.hypermedia.RecordedInvocationUtils.*;
-
-/**
- * Builder to ease building {@link URI} instances pointing to Spring MVC controllers.
- *
- * @author Oliver Gierke
- */
-public class MvcUriComponentsBuilder extends UriComponentsBuilder {
-
- private static final AnnotationMappingDiscoverer DISCOVERER = new AnnotationMappingDiscoverer(
- RequestMapping.class);
-
- private static final AnnotatedParametersParameterAccessor PATH_VARIABLE_ACCESSOR = new AnnotatedParametersParameterAccessor(
- new AnnotationAttribute(PathVariable.class));
-
- private static final AnnotatedParametersParameterAccessor REQUEST_PARAM_ACCESSOR = new AnnotatedParametersParameterAccessor(
- new AnnotationAttribute(RequestParam.class));
-
- private final List<UriComponentsContributor> contributors;
-
- @Autowired(required = false)
- private RequestMappingHandlerAdapter adapter;
-
- /**
- * Creates a new {@link LinkBuilderSupport} to grab the
- * {@link UriComponentsContributor}s registered in the
- * {@link RequestMappingHandlerAdapter}.
- *
- * @param builder must not be {@literal null}.
- */
- MvcUriComponentsBuilder() {
-
- SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
- List<UriComponentsContributor> contributors = new ArrayList<UriComponentsContributor>();
-
- if (adapter != null) {
- for (HandlerMethodArgumentResolver resolver : adapter.getArgumentResolvers()) {
- if (resolver instanceof UriComponentsContributor) {
- contributors.add((UriComponentsContributor) resolver);
- }
- }
- }
-
- this.contributors = contributors;
- }
-
- /**
- * Creates a new {@link MvcUriComponentsBuilder} with a base of the mapping annotated
- * to the given controller class.
- *
- * @param controller the class to discover the annotation on, must not be
- * {@literal null}.
- * @return
- */
- public static UriComponentsBuilder from(Class<?> controller) {
- return from(controller, new Object[0]);
- }
-
- /**
- * Creates a new {@link MvcUriComponentsBuilder} with a base of the mapping annotated
- * to the given controller class. The additional parameters are used to fill up
- * potentially available path variables in the class scop request mapping.
- *
- * @param controller the class to discover the annotation on, must not be
- * {@literal null}.
- * @param parameters additional parameters to bind to the URI template declared in the
- * annotation, must not be {@literal null}.
- * @return
- */
- public static UriComponentsBuilder from(Class<?> controller, Object... parameters) {
-
- Assert.notNull(controller);
-
- String mapping = DISCOVERER.getMapping(controller);
- UriTemplate template = new UriTemplate(mapping == null ? "/" : mapping);
- UriComponentsBuilder builder = UriComponentsBuilder.fromUri(template.expand(parameters));
- return getRootBuilder().with(builder);
- }
-
- public static UriComponentsBuilder from(Method method, Object... parameters) {
- MvcUriComponentsBuilder builder = new MvcUriComponentsBuilder();
- return from(method, parameters, builder.contributors);
- }
-
- static UriComponentsBuilder from(Method method, Object[] parameters,
- List<UriComponentsContributor> contributors) {
-
- UriTemplate template = new UriTemplate(DISCOVERER.getMapping(method));
- UriComponentsBuilder builder = UriComponentsBuilder.fromUri(template.expand(parameters));
-
- RecordedMethodInvocation invocation = getInvocation(method, parameters);
- UriComponentsBuilder appender = applyUriComponentsContributer(invocation,
- builder, contributors);
-
- return getRootBuilder().with(appender);
- }
-
- /**
- * Creates a {@link MvcUriComponentsBuilder} pointing to a controller method. Hand in
- * a dummy method invocation result you can create via
- * {@link #methodOn(Class, Object...)} or
- * {@link RecordedInvocationUtils#methodOn(Class, Object...)}.
- *
- * <pre>
- * @RequestMapping("/customers")
- * class CustomerController {
- *
- * @RequestMapping("/{id}/addresses")
- * HttpEntity<Addresses> showAddresses(@PathVariable Long id) { … }
- * }
- *
- * URI uri = linkTo(methodOn(CustomerController.class).showAddresses(2L)).toURI();
- * </pre>
- *
- * The resulting {@link URI} instance will point to {@code /customers/2/addresses}.
- * For more details on the method invocation constraints, see
- * {@link RecordedInvocationUtils#methodOn(Class, Object...)}.
- *
- * @param invocationValue
- * @return
- */
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.hateoas.MethodLinkBuilderFactory#linkTo(java.lang.Object)
- */
- public static UriComponentsBuilder from(Object invocationValue) {
-
- MvcUriComponentsBuilder builder = new MvcUriComponentsBuilder();
- return from(invocationValue, builder.contributors);
- }
-
- static UriComponentsBuilder from(Object invocationValue,
- List<? extends UriComponentsContributor> contributors) {
-
- Assert.isInstanceOf(LastInvocationAware.class, invocationValue);
- LastInvocationAware invocations = (LastInvocationAware) invocationValue;
-
- RecordedMethodInvocation invocation = invocations.getLastInvocation();
- Iterator<Object> classMappingParameters = invocations.getObjectParameters();
- Method method = invocation.getMethod();
-
- String mapping = DISCOVERER.getMapping(method);
- UriComponentsBuilder builder = getRootBuilder().path(mapping);
-
- UriTemplate template = new UriTemplate(mapping);
- Map<String, Object> values = new HashMap<String, Object>();
-
- Iterator<String> names = template.getVariableNames().iterator();
- while (classMappingParameters.hasNext()) {
- values.put(names.next(), classMappingParameters.next());
- }
-
- for (BoundMethodParameter parameter : PATH_VARIABLE_ACCESSOR.getBoundParameters(invocation)) {
- values.put(parameter.getVariableName(), parameter.asString());
- }
-
- for (BoundMethodParameter parameter : REQUEST_PARAM_ACCESSOR.getBoundParameters(invocation)) {
-
- Object value = parameter.getValue();
- String key = parameter.getVariableName();
-
- if (value instanceof Collection) {
- for (Object element : (Collection<?>) value) {
- builder.queryParam(key, element);
- }
- }
- else {
- builder.queryParam(key, parameter.asString());
- }
- }
-
- UriComponents components = applyUriComponentsContributer(invocation, builder,
- contributors).buildAndExpand(values);
- return UriComponentsBuilder.fromUri(components.toUri());
- }
-
- /**
- * Wrapper for {@link RecordedInvocationUtils#methodOn(Class, Object...)} to be
- * available in case you work with static imports of {@link MvcUriComponentsBuilder}.
- *
- * @param controller must not be {@literal null}.
- * @param parameters parameters to extend template variables in the type level
- * mapping.
- * @return
- */
- public static <T> T methodOn(Class<T> controller, Object... parameters) {
- return RecordedInvocationUtils.methodOn(controller, parameters);
- }
-
- /**
- * Returns a {@link UriComponentsBuilder} obtained from the current servlet mapping
- * with the host tweaked in case the request contains an {@code X-Forwarded-Host}
- * header.
- *
- * @return
- */
- static UriComponentsBuilder getRootBuilder() {
-
- HttpServletRequest request = getCurrentRequest();
- UriComponentsBuilder builder = ServletUriComponentsBuilder.fromServletMapping(request);
-
- String header = request.getHeader("X-Forwarded-Host");
-
- if (!StringUtils.hasText(header)) {
- return builder;
- }
-
- String[] hosts = StringUtils.commaDelimitedListToStringArray(header);
- String hostToUse = hosts[0];
-
- if (hostToUse.contains(":")) {
-
- String[] hostAndPort = StringUtils.split(hostToUse, ":");
-
- builder.host(hostAndPort[0]);
- builder.port(Integer.parseInt(hostAndPort[1]));
-
- }
- else {
- builder.host(hostToUse);
- }
-
- return builder;
- }
-
- /**
- * Applies the configured {@link UriComponentsContributor}s to the given
- * {@link UriComponentsBuilder}.
- *
- * @param builder will never be {@literal null}.
- * @param invocation will never be {@literal null}.
- * @return
- */
- private static UriComponentsBuilder applyUriComponentsContributer(
- RecordedMethodInvocation invocation, UriComponentsBuilder builder,
- Collection<? extends UriComponentsContributor> contributors) {
-
- if (contributors.isEmpty()) {
- return builder;
- }
-
- MethodParameters parameters = new MethodParameters(invocation.getMethod());
- Iterator<Object> parameterValues = Arrays.asList(invocation.getArguments()).iterator();
-
- for (MethodParameter parameter : parameters.getParameters()) {
- Object parameterValue = parameterValues.next();
- for (UriComponentsContributor contributor : contributors) {
- if (contributor.supportsParameter(parameter)) {
- contributor.enhance(builder, parameter, parameterValue);
- }
- }
- }
-
- return builder;
- }
-
- /**
- * Copy of {@link ServletUriComponentsBuilder#getCurrentRequest()} until SPR-10110
- * gets fixed.
- *
- * @return
- */
- private static HttpServletRequest getCurrentRequest() {
-
- RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
- Assert.state(requestAttributes != null,
- "Could not find current request via RequestContextHolder");
- Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes);
- HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
- Assert.state(servletRequest != null, "Could not find current HttpServletRequest");
- return servletRequest;
- }
-}
| true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/hypermedia/MvcUriComponentsBuilderFactory.java | @@ -1,55 +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.web.servlet.hypermedia;
-
-import java.lang.reflect.Method;
-import java.util.List;
-
-import org.springframework.web.util.UriComponentsBuilder;
-
-/**
- *
- * @author olivergierke
- */
-public class MvcUriComponentsBuilderFactory implements MvcUris {
-
- private final List<? extends UriComponentsContributor> contributors;
-
- /**
- * @param contributors
- */
- public MvcUriComponentsBuilderFactory(
- List<? extends UriComponentsContributor> contributors) {
- this.contributors = contributors;
- }
-
- public UriComponentsBuilder from(Class<?> controller) {
- return from(controller, new Object[0]);
- }
-
- public UriComponentsBuilder from(Class<?> controller, Object... parameters) {
- return MvcUriComponentsBuilder.from(controller, parameters);
- }
-
- public UriComponentsBuilder from(Object invocationValue) {
- return MvcUriComponentsBuilder.from(invocationValue, contributors);
- }
-
- public UriComponentsBuilder from(Method method, Object... parameters) {
- return MvcUriComponentsBuilder.from(method, parameters, contributors);
- }
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/hypermedia/MvcUris.java | @@ -1,36 +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.web.servlet.hypermedia;
-
-import java.lang.reflect.Method;
-
-import org.springframework.web.util.UriComponentsBuilder;
-
-/**
- *
- * @author olivergierke
- */
-public interface MvcUris {
-
- UriComponentsBuilder from(Class<?> controller);
-
- UriComponentsBuilder from(Class<?> controller, Object... parameters);
-
- UriComponentsBuilder from(Object invocationValue);
-
- UriComponentsBuilder from(Method method, Object... parameters);
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/hypermedia/RecordedInvocationUtils.java | @@ -1,240 +0,0 @@
-/*
- * Copyright 2012-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.web.servlet.hypermedia;
-
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.Iterator;
-
-import org.aopalliance.intercept.MethodInterceptor;
-import org.springframework.aop.framework.ProxyFactory;
-import org.springframework.aop.target.EmptyTargetSource;
-import org.springframework.cglib.proxy.Callback;
-import org.springframework.cglib.proxy.Enhancer;
-import org.springframework.cglib.proxy.Factory;
-import org.springframework.cglib.proxy.MethodProxy;
-import org.springframework.objenesis.ObjenesisStd;
-import org.springframework.util.Assert;
-import org.springframework.util.ReflectionUtils;
-
-/**
- * Utility methods to capture dummy method invocations.
- *
- * @author Oliver Gierke
- */
-class RecordedInvocationUtils {
-
- private static ObjenesisStd OBJENESIS = new ObjenesisStd(true);
-
- public interface LastInvocationAware {
-
- Iterator<Object> getObjectParameters();
-
- RecordedMethodInvocation getLastInvocation();
- }
-
- /**
- * Method interceptor that records the last method invocation and creates a proxy for
- * the return value that exposes the method invocation.
- *
- * @author Oliver Gierke
- */
- private static class InvocationRecordingMethodInterceptor implements
- MethodInterceptor, LastInvocationAware,
- org.springframework.cglib.proxy.MethodInterceptor {
-
- private static final Method GET_INVOCATIONS;
-
- private static final Method GET_OBJECT_PARAMETERS;
-
- private final Object[] objectParameters;
-
- private RecordedMethodInvocation invocation;
-
- static {
- GET_INVOCATIONS = ReflectionUtils.findMethod(LastInvocationAware.class,
- "getLastInvocation");
- GET_OBJECT_PARAMETERS = ReflectionUtils.findMethod(LastInvocationAware.class,
- "getObjectParameters");
- }
-
- /**
- * Creates a new {@link InvocationRecordingMethodInterceptor} carrying the given
- * parameters forward that might be needed to populate the class level mapping.
- *
- * @param parameters
- */
- public InvocationRecordingMethodInterceptor(Object... parameters) {
- this.objectParameters = parameters.clone();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.springframework.cglib.proxy.MethodInterceptor#intercept(java.lang.Object,
- * java.lang.reflect.Method, java.lang.Object[],
- * org.springframework.cglib.proxy.MethodProxy)
- */
- public Object intercept(Object obj, Method method, Object[] args,
- MethodProxy proxy) {
-
- if (GET_INVOCATIONS.equals(method)) {
- return getLastInvocation();
- }
- else if (GET_OBJECT_PARAMETERS.equals(method)) {
- return getObjectParameters();
- }
- else if (ReflectionUtils.isObjectMethod(method)) {
- return ReflectionUtils.invokeMethod(method, obj, args);
- }
-
- this.invocation = new SimpleRecordedMethodInvocation(method, args);
-
- Class<?> returnType = method.getReturnType();
- return returnType.cast(getProxyWithInterceptor(returnType, this));
- }
-
- /*
- * (non-Javadoc)
- *
- * @see
- * org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept
- * .MethodInvocation)
- */
- @Override
- public Object invoke(org.aopalliance.intercept.MethodInvocation invocation)
- throws Throwable {
- return intercept(invocation.getThis(), invocation.getMethod(),
- invocation.getArguments(), null);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.hateoas.core.DummyInvocationUtils.LastInvocationAware#
- * getLastInvocation()
- */
- @Override
- public RecordedMethodInvocation getLastInvocation() {
- return invocation;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.springframework.hateoas.core.DummyInvocationUtils.LastInvocationAware#
- * getObjectParameters()
- */
- @Override
- public Iterator<Object> getObjectParameters() {
- return Arrays.asList(objectParameters).iterator();
- }
- }
-
- /**
- * Returns a proxy of the given type, backed by an {@link EmptyTargetSource} to simply
- * drop method invocations but equips it with an
- * {@link InvocationRecordingMethodInterceptor}. The interceptor records the last
- * invocation and returns a proxy of the return type that also implements
- * {@link LastInvocationAware} so that the last method invocation can be inspected.
- * Parameters passed to the subsequent method invocation are generally neglected
- * except the ones that might be mapped into the URI translation eventually, e.g.
- * {@linke PathVariable} in the case of Spring MVC.
- *
- * @param type must not be {@literal null}.
- * @param parameters parameters to extend template variables in the type level
- * mapping.
- * @return
- */
- public static <T> T methodOn(Class<T> type, Object... parameters) {
-
- Assert.notNull(type, "Given type must not be null!");
-
- InvocationRecordingMethodInterceptor interceptor = new InvocationRecordingMethodInterceptor(
- parameters);
- return getProxyWithInterceptor(type, interceptor);
- }
-
- static RecordedMethodInvocation getInvocation(Method method, Object[] parameters) {
- return new SimpleRecordedMethodInvocation(method, parameters);
- }
-
- @SuppressWarnings("unchecked")
- private static <T> T getProxyWithInterceptor(Class<?> type,
- InvocationRecordingMethodInterceptor interceptor) {
-
- if (type.isInterface()) {
-
- ProxyFactory factory = new ProxyFactory(EmptyTargetSource.INSTANCE);
- factory.addInterface(type);
- factory.addInterface(LastInvocationAware.class);
- factory.addAdvice(interceptor);
-
- return (T) factory.getProxy();
- }
-
- Enhancer enhancer = new Enhancer();
- enhancer.setSuperclass(type);
- enhancer.setInterfaces(new Class<?>[] { LastInvocationAware.class });
- enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class);
-
- Factory factory = (Factory) OBJENESIS.newInstance(enhancer.createClass());
- factory.setCallbacks(new Callback[] { interceptor });
- return (T) factory;
- }
-
- public interface RecordedMethodInvocation {
-
- Object[] getArguments();
-
- Method getMethod();
- }
-
- static class SimpleRecordedMethodInvocation implements RecordedMethodInvocation {
-
- private final Method method;
-
- private final Object[] arguments;
-
- /**
- * Creates a new {@link SimpleRecordedMethodInvocation} for the given
- * {@link Method} and arguments.
- *
- * @param method must not be {@literal null}.
- * @param arguments must not be {@literal null}.
- */
- private SimpleRecordedMethodInvocation(Method method, Object[] arguments) {
-
- Assert.notNull(method, "Method must not be null!");
- Assert.notNull(arguments, "Arguments must not be null!");
-
- this.arguments = arguments;
- this.method = method;
- }
-
- @Override
- public Object[] getArguments() {
- return arguments;
- }
-
- @Override
- public Method getMethod() {
- return method;
- }
- }
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/hypermedia/UriComponentsContributor.java | @@ -1,51 +0,0 @@
-/*
- * Copyright 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.web.servlet.hypermedia;
-
-import org.springframework.core.MethodParameter;
-import org.springframework.web.method.support.HandlerMethodArgumentResolver;
-import org.springframework.web.util.UriComponentsBuilder;
-
-/**
- * SPI callback to enhance a {@link UriComponentsBuilder} when referring to a method
- * through a dummy method invocation. Will usually be implemented in implementations of
- * {@link HandlerMethodArgumentResolver} as they represent exactly the same functionality
- * inverted.
- *
- * @see MvcUriComponentsBuilderFactory#from(Object)
- * @author Oliver Gierke
- */
-public interface UriComponentsContributor {
-
- /**
- * Returns whether the {@link UriComponentsBuilder} supports the given
- * {@link MethodParameter}.
- *
- * @param parameter will never be {@literal null}.
- * @return
- */
- boolean supportsParameter(MethodParameter parameter);
-
- /**
- * Enhance the given {@link UriComponentsBuilder} with the given value.
- *
- * @param builder will never be {@literal null}.
- * @param parameter will never be {@literal null}.
- * @param value can be {@literal null}.
- */
- void enhance(UriComponentsBuilder builder, MethodParameter parameter, Object value);
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolver.java | @@ -21,6 +21,8 @@
import java.util.Map;
import org.springframework.core.MethodParameter;
+import org.springframework.core.convert.ConversionService;
+import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestBindingException;
@@ -32,8 +34,10 @@
import org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver;
import org.springframework.web.method.annotation.RequestParamMapMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
+import org.springframework.web.method.support.UriComponentsContributor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.View;
+import org.springframework.web.util.UriComponentsBuilder;
/**
* Resolves method arguments annotated with an @{@link PathVariable}.
@@ -59,7 +63,11 @@
* @author Arjen Poutsma
* @since 3.1
*/
-public class PathVariableMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver {
+public class PathVariableMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver
+ implements UriComponentsContributor {
+
+ private static final TypeDescriptor STRING_TYPE_DESCRIPTOR = TypeDescriptor.valueOf(String.class);
+
public PathVariableMethodArgumentResolver() {
super(null);
@@ -114,6 +122,25 @@ protected void handleResolvedValue(Object arg, String name, MethodParameter para
pathVars.put(name, arg);
}
+ @Override
+ public void contributeMethodArgument(MethodParameter parameter, Object value,
+ UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {
+
+ if (Map.class.isAssignableFrom(parameter.getParameterType())) {
+ return;
+ }
+
+ PathVariable annot = parameter.getParameterAnnotation(PathVariable.class);
+ String name = StringUtils.isEmpty(annot.value()) ? parameter.getParameterName() : annot.value();
+
+ if (conversionService != null) {
+ value = conversionService.convert(value, new TypeDescriptor(parameter), STRING_TYPE_DESCRIPTOR);
+ }
+
+ uriVariables.put(name, value);
+ }
+
+
private static class PathVariableNamedValueInfo extends NamedValueInfo {
private PathVariableNamedValueInfo(PathVariable annotation) { | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java | @@ -26,6 +26,7 @@
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
+
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@@ -219,7 +220,7 @@ public void setArgumentResolvers(List<HandlerMethodArgumentResolver> argumentRes
* not initialized yet via {@link #afterPropertiesSet()}.
*/
public List<HandlerMethodArgumentResolver> getArgumentResolvers() {
- return this.argumentResolvers.getResolvers();
+ return (this.argumentResolvers != null) ? this.argumentResolvers.getResolvers() : null;
}
/**
@@ -240,7 +241,7 @@ public void setInitBinderArgumentResolvers(List<HandlerMethodArgumentResolver> a
* {@code null} if not initialized yet via {@link #afterPropertiesSet()}.
*/
public List<HandlerMethodArgumentResolver> getInitBinderArgumentResolvers() {
- return this.initBinderArgumentResolvers.getResolvers();
+ return (this.initBinderArgumentResolvers != null) ? this.initBinderArgumentResolvers.getResolvers() : null;
}
/** | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/DefaultMvcUrls.java | @@ -0,0 +1,181 @@
+/*
+ * 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.web.servlet.mvc.support;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
+import org.springframework.core.MethodParameter;
+import org.springframework.core.ParameterNameDiscoverer;
+import org.springframework.core.convert.ConversionService;
+import org.springframework.format.support.DefaultFormattingConversionService;
+import org.springframework.util.Assert;
+import org.springframework.util.ObjectUtils;
+import org.springframework.web.method.support.HandlerMethodArgumentResolver;
+import org.springframework.web.method.support.UriComponentsContributor;
+import org.springframework.web.servlet.mvc.support.MvcUrlUtils.ControllerMethodValues;
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
+import org.springframework.web.util.UriComponents;
+import org.springframework.web.util.UriComponentsBuilder;
+import org.springframework.web.util.UriTemplate;
+
+/**
+ * A default {@link MvcUrls} implementation.
+ *
+ * @author Oliver Gierke
+ * @author Rossen Stoyanchev
+ *
+ * @since 4.0
+ */
+public class DefaultMvcUrls implements MvcUrls {
+
+ private static final ParameterNameDiscoverer parameterNameDiscoverer =
+ new LocalVariableTableParameterNameDiscoverer();
+
+
+ private final List<UriComponentsContributor> contributors = new ArrayList<UriComponentsContributor>();
+
+ private final ConversionService conversionService;
+
+
+ /**
+ * Create an instance providing a collection of {@link UriComponentsContributor}s or
+ * {@link HandlerMethodArgumentResolver}s. Since both of these tend to be implemented
+ * by the same class, the most convenient option is to obtain the configured
+ * {@code HandlerMethodArgumentResolvers} in the {@code RequestMappingHandlerAdapter}
+ * and provide that to this contstructor.
+ *
+ * @param uriComponentsContributors a collection of {@link UriComponentsContributor}
+ * or {@link HandlerMethodArgumentResolver}s.
+ */
+ public DefaultMvcUrls(Collection<?> uriComponentsContributors) {
+ this(uriComponentsContributors, null);
+ }
+
+ /**
+ * Create an instance providing a collection of {@link UriComponentsContributor}s or
+ * {@link HandlerMethodArgumentResolver}s. Since both of these tend to be implemented
+ * by the same class, the most convenient option is to obtain the configured
+ * {@code HandlerMethodArgumentResolvers} in the {@code RequestMappingHandlerAdapter}
+ * and provide that to this contstructor.
+ * <p>
+ * If the {@link ConversionService} argument is {@code null},
+ * {@link DefaultFormattingConversionService} will be used by default.
+ *
+ * @param uriComponentsContributors a collection of {@link UriComponentsContributor}
+ * or {@link HandlerMethodArgumentResolver}s.
+ * @param conversionService a ConversionService to use when method argument values
+ * need to be formatted as Strings before being added to the URI
+ */
+ public DefaultMvcUrls(Collection<?> uriComponentsContributors, ConversionService conversionService) {
+
+ Assert.notNull(uriComponentsContributors, "'uriComponentsContributors' must not be null");
+
+ for (Object contributor : uriComponentsContributors) {
+ if (contributor instanceof UriComponentsContributor) {
+ this.contributors.add((UriComponentsContributor) contributor);
+ }
+ }
+
+ this.conversionService = (conversionService != null) ?
+ conversionService : new DefaultFormattingConversionService();
+ }
+
+
+ @Override
+ public UriComponentsBuilder linkToController(Class<?> controllerClass) {
+ String mapping = MvcUrlUtils.getTypeLevelMapping(controllerClass);
+ return ServletUriComponentsBuilder.fromCurrentServletMapping().path(mapping);
+ }
+
+ @Override
+ public UriComponents linkToMethod(Method method, Object... argumentValues) {
+ String mapping = MvcUrlUtils.getMethodMapping(method);
+ UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentServletMapping().path(mapping);
+ Map<String, Object> uriVars = new HashMap<String, Object>();
+ return applyContributers(builder, method, argumentValues, uriVars);
+ }
+
+ private UriComponents applyContributers(UriComponentsBuilder builder, Method method,
+ Object[] argumentValues, Map<String, Object> uriVars) {
+
+ if (this.contributors.isEmpty()) {
+ return builder.buildAndExpand(uriVars);
+ }
+
+ int paramCount = method.getParameters().length;
+ int argCount = argumentValues.length;
+
+ Assert.isTrue(paramCount == argCount, "Number of method parameters " + paramCount +
+ " does not match number of argument values " + argCount);
+
+ for (int i=0; i < paramCount; i++) {
+ MethodParameter param = new MethodParameter(method, i);
+ param.initParameterNameDiscovery(parameterNameDiscoverer);
+ for (UriComponentsContributor c : this.contributors) {
+ if (c.supportsParameter(param)) {
+ c.contributeMethodArgument(param, argumentValues[i], builder, uriVars, this.conversionService);
+ break;
+ }
+ }
+ }
+
+ return builder.buildAndExpand(uriVars);
+ }
+
+ @Override
+ public UriComponents linkToMethodOn(Object mockController) {
+
+ Assert.isInstanceOf(ControllerMethodValues.class, mockController);
+ ControllerMethodValues controllerMethodValues = (ControllerMethodValues) mockController;
+
+ Method method = controllerMethodValues.getControllerMethod();
+ Object[] argumentValues = controllerMethodValues.getArgumentValues();
+
+ Map<String, Object> uriVars = new HashMap<String, Object>();
+ addTypeLevelUriVaris(controllerMethodValues, uriVars);
+
+ String mapping = MvcUrlUtils.getMethodMapping(method);
+ UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentServletMapping().path(mapping);
+
+ return applyContributers(builder, method, argumentValues, uriVars);
+ }
+
+ private void addTypeLevelUriVaris(ControllerMethodValues info, Map<String, Object> uriVariables) {
+
+ Object[] values = info.getTypeLevelUriVariables();
+ if (!ObjectUtils.isEmpty(values)) {
+
+ String mapping = MvcUrlUtils.getTypeLevelMapping(info.getControllerMethod().getDeclaringClass());
+
+ List<String> names = new UriTemplate(mapping).getVariableNames();
+ Assert.isTrue(names.size() == values.length, "The provided type-level URI template variables " +
+ Arrays.toString(values) + " do not match the template " + mapping);
+
+ for (int i=0; i < names.size(); i++) {
+ uriVariables.put(names.get(i), values[i]);
+ }
+ }
+ }
+
+} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/MvcUrlUtils.java | @@ -0,0 +1,207 @@
+/*
+ * Copyright 2012-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.web.servlet.mvc.support;
+
+import java.lang.reflect.Method;
+import java.util.Set;
+
+import org.aopalliance.intercept.MethodInterceptor;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.springframework.aop.framework.ProxyFactory;
+import org.springframework.aop.target.EmptyTargetSource;
+import org.springframework.cglib.proxy.Callback;
+import org.springframework.cglib.proxy.Enhancer;
+import org.springframework.cglib.proxy.Factory;
+import org.springframework.cglib.proxy.MethodProxy;
+import org.springframework.core.annotation.AnnotationUtils;
+import org.springframework.objenesis.ObjenesisStd;
+import org.springframework.util.Assert;
+import org.springframework.util.ObjectUtils;
+import org.springframework.util.ReflectionUtils;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
+import org.springframework.web.util.UriComponents;
+
+/**
+ * Utility methods to support the creation URLs to Spring MVC controllers and controller
+ * methods.
+ *
+ * @author Oliver Gierke
+ * @author Rossen Stoyanchev
+ *
+ * @since 4.0
+ */
+public class MvcUrlUtils {
+
+ private static Log logger = LogFactory.getLog(MvcUrlUtils.class);
+
+ private final static ObjenesisStd OBJENESIS = new ObjenesisStd(true);
+
+
+ /**
+ * Extract the type-level URL mapping or return an empty String. If multiple mappings
+ * are found, the first one is used.
+ */
+ public static String getTypeLevelMapping(Class<?> controllerType) {
+ Assert.notNull(controllerType, "'controllerType' must not be null");
+ RequestMapping annot = AnnotationUtils.findAnnotation(controllerType, RequestMapping.class);
+ if ((annot == null) || ObjectUtils.isEmpty(annot.value())) {
+ return "/";
+ }
+ if (annot.value().length > 1) {
+ logger.warn("Multiple class level mappings on " + controllerType.getName() + ", using the first one");
+ }
+ return annot.value()[0];
+
+ }
+
+ /**
+ * Extract the mapping from the given controller method, including both type and
+ * method-level mappings. If multiple mappings are found, the first one is used.
+ */
+ public static String getMethodMapping(Method method) {
+ RequestMapping methodAnnot = AnnotationUtils.findAnnotation(method, RequestMapping.class);
+ Assert.notNull(methodAnnot, "No mappings on " + method.toGenericString());
+ PatternsRequestCondition condition = new PatternsRequestCondition(methodAnnot.value());
+
+ RequestMapping typeAnnot = AnnotationUtils.findAnnotation(method.getDeclaringClass(), RequestMapping.class);
+ if (typeAnnot != null) {
+ condition = new PatternsRequestCondition(typeAnnot.value()).combine(condition);
+ }
+
+ Set<String> patterns = condition.getPatterns();
+ if (patterns.size() > 1) {
+ logger.warn("Multiple mappings on " + method.toGenericString() + ", using the first one");
+ }
+
+ return (patterns.size() == 0) ? "/" : patterns.iterator().next();
+ }
+
+ /**
+ * Return a "mock" controller instance. When a controller method is invoked, the
+ * invoked method and argument values are remembered, and a "mock" value is returned
+ * so it can be used to help prepare a {@link UriComponents} through
+ * {@link MvcUrls#linkToMethodOn(Object)}.
+ *
+ * @param controllerType the type of controller to mock, must not be {@literal null}.
+ * @param typeLevelUriVariables URI variables to expand into the type-level mapping
+ * @return the created controller instance
+ */
+ public static <T> T controller(Class<T> controllerType, Object... typeLevelUriVariables) {
+ Assert.notNull(controllerType, "'type' must not be null");
+ return initProxy(controllerType, new ControllerMethodInvocationInterceptor(typeLevelUriVariables));
+ }
+
+ @SuppressWarnings("unchecked")
+ private static <T> T initProxy(Class<?> type, ControllerMethodInvocationInterceptor interceptor) {
+
+ if (type.isInterface()) {
+ ProxyFactory factory = new ProxyFactory(EmptyTargetSource.INSTANCE);
+ factory.addInterface(type);
+ factory.addInterface(ControllerMethodValues.class);
+ factory.addAdvice(interceptor);
+ return (T) factory.getProxy();
+ }
+ else {
+ Enhancer enhancer = new Enhancer();
+ enhancer.setSuperclass(type);
+ enhancer.setInterfaces(new Class<?>[] { ControllerMethodValues.class });
+ enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class);
+
+ Factory factory = (Factory) OBJENESIS.newInstance(enhancer.createClass());
+ factory.setCallbacks(new Callback[] { interceptor });
+ return (T) factory;
+ }
+ }
+
+
+ private static class ControllerMethodInvocationInterceptor
+ implements org.springframework.cglib.proxy.MethodInterceptor, MethodInterceptor {
+
+ private static final Method getTypeLevelUriVariables =
+ ReflectionUtils.findMethod(ControllerMethodValues.class, "getTypeLevelUriVariables");
+
+ private static final Method getControllerMethod =
+ ReflectionUtils.findMethod(ControllerMethodValues.class, "getControllerMethod");
+
+ private static final Method getArgumentValues =
+ ReflectionUtils.findMethod(ControllerMethodValues.class, "getArgumentValues");
+
+
+ private final Object[] typeLevelUriVariables;
+
+ private Method controllerMethod;
+
+ private Object[] argumentValues;
+
+
+ public ControllerMethodInvocationInterceptor(Object... typeLevelUriVariables) {
+ this.typeLevelUriVariables = typeLevelUriVariables.clone();
+ }
+
+
+ @Override
+ public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) {
+
+ if (getTypeLevelUriVariables.equals(method)) {
+ return this.typeLevelUriVariables;
+ }
+ else if (getControllerMethod.equals(method)) {
+ return this.controllerMethod;
+ }
+ else if (getArgumentValues.equals(method)) {
+ return this.argumentValues;
+ }
+ else if (ReflectionUtils.isObjectMethod(method)) {
+ return ReflectionUtils.invokeMethod(method, obj, args);
+ }
+ else {
+ this.controllerMethod = method;
+ this.argumentValues = args;
+
+ Class<?> returnType = method.getReturnType();
+ return void.class.equals(returnType) ? null : returnType.cast(initProxy(returnType, this));
+ }
+ }
+
+ @Override
+ public Object invoke(org.aopalliance.intercept.MethodInvocation inv) throws Throwable {
+ return intercept(inv.getThis(), inv.getMethod(), inv.getArguments(), null);
+ }
+ }
+
+ /**
+ * Provides information about a controller method that can be used to prepare a URL
+ * including type-level URI template variables, a method reference, and argument
+ * values collected through the invocation of a "mock" controller.
+ * <p>
+ * Instances of this interface are returned from
+ * {@link MvcUrlUtils#controller(Class, Object...) controller(Class, Object...)} and
+ * are needed for {@link MvcUrls#linkToMethodOn(ControllerMethodValues)}.
+ */
+ public interface ControllerMethodValues {
+
+ Object[] getTypeLevelUriVariables();
+
+ Method getControllerMethod();
+
+ Object[] getArgumentValues();
+
+ }
+
+} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/MvcUrls.java | @@ -0,0 +1,121 @@
+/*
+ * 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.web.servlet.mvc.support;
+
+import java.lang.reflect.Method;
+
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.method.support.UriComponentsContributor;
+import org.springframework.web.servlet.config.DefaultMvcUrlsFactoryBean;
+import org.springframework.web.util.UriComponents;
+import org.springframework.web.util.UriComponentsBuilder;
+
+/**
+ * A contract for creating URLs by referencing Spring MVC controllers and methods.
+ * <p>
+ * The MVC Java config and the MVC namespace automatically create an instance of this
+ * contract for use in controllers and anywhere else during the processing of a request.
+ * The best way for access it is to have it autowired, or otherwise injected either by
+ * type or also qualified by name ("mvcUrls") if necessary.
+ * <p>
+ * If not using either option, with explicit configuration it's easy to create an instance
+ * of {@link DefaultMvcUrls} in Java config or in XML configuration, use
+ * {@link DefaultMvcUrlsFactoryBean}.
+ *
+ * @author Oliver Gierke
+ * @author Rossen Stoyanchev
+ *
+ * @since 4.0
+ */
+public interface MvcUrls {
+
+ /**
+ * Creates a new {@link UriComponentsBuilder} by pointing to a controller class. The
+ * resulting builder contains all the current request information up to and including
+ * the Servlet mapping as well as the portion of the path matching to the controller
+ * level request mapping. If the controller contains multiple mappings, the
+ * {@link DefaultMvcUrls} will use the first one.
+ *
+ * @param controllerType the controller type to create a URL to
+ *
+ * @return a builder that can be used to further build the {@link UriComponents}.
+ */
+ UriComponentsBuilder linkToController(Class<?> controllerType);
+
+ /**
+ * Create a {@link UriComponents} by pointing to a controller method along with method
+ * argument values.
+ * <p>
+ * Type and method-level mappings of the controller method are extracted and the
+ * resulting {@link UriComponents} is further enriched with method argument values from
+ * {@link PathVariable} and {@link RequestParam} parameters. Any other arguments not
+ * relevant to the building of the URL can be provided as {@literal null} and will be
+ * ignored. Support for additional custom arguments can be added through a
+ * {@link UriComponentsContributor}.
+ *
+ * FIXME Type-level URI template variables?
+ *
+ * @param method the target controller method
+ * @param argumentValues argument values matching to method parameters
+ *
+ * @return UriComponents instance, never {@literal null}
+ */
+ UriComponents linkToMethod(Method method, Object... argumentValues);
+
+ /**
+ * Create a {@link UriComponents} by invoking a method on a "mock" controller similar
+ * to how test frameworks provide mock objects and record method invocations. The
+ * static method {@link MvcUrlUtils#controller(Class, Object...)} can be used to
+ * create a "mock" controller:
+ *
+ * <pre class="code">
+ * @RequestMapping("/people/{id}/addresses")
+ * class AddressController {
+ *
+ * @RequestMapping("/{country}")
+ * public HttpEntity<Void> getAddressesForCountry(@PathVariable String country) { … }
+ *
+ * @RequestMapping(value="/", method=RequestMethod.POST)
+ * public void addAddress(Address address) { … }
+ * }
+ *
+ * // short-hand style with static import of MvcUrlUtils.controller
+ *
+ * mvcUrls.linkToMethodOn(controller(CustomerController.class, 1).showAddresses("US"));
+ *
+ * // longer style, required for void controller methods
+ *
+ * CustomerController controller = MvcUrlUtils.controller(CustomController.class, 1);
+ * controller.addAddress(null);
+ *
+ * mvcUrls.linkToMethodOn(controller);
+ *
+ * </pre>
+ *
+ * The above mechanism supports {@link PathVariable} and {@link RequestParam} method
+ * arguments. Any other arguments can be provided as {@literal null} and will be
+ * ignored. Additional custom arguments can be added through an implementation of
+ * {@link UriComponentsContributor}.
+ *
+ * @param mockController created via {@link MvcUrlUtils#controller(Class, Object...)}
+ *
+ * @return UriComponents instance, never {@literal null}
+ */
+ UriComponents linkToMethodOn(Object mockController);
+
+} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java | @@ -100,16 +100,18 @@ public static ServletUriComponentsBuilder fromRequest(HttpServletRequest request
int port = request.getServerPort();
String host = request.getServerName();
- String xForwardedHostHeader = request.getHeader("X-Forwarded-Host");
+ String header = request.getHeader("X-Forwarded-Host");
- if (StringUtils.hasText(xForwardedHostHeader)) {
- if (StringUtils.countOccurrencesOf(xForwardedHostHeader, ":") == 1) {
- String[] hostAndPort = StringUtils.split(xForwardedHostHeader, ":");
+ if (StringUtils.hasText(header)) {
+ String[] hosts = StringUtils.commaDelimitedListToStringArray(header);
+ String hostToUse = hosts[0];
+ if (hostToUse.contains(":")) {
+ String[] hostAndPort = StringUtils.split(hostToUse, ":");
host = hostAndPort[0];
port = Integer.parseInt(hostAndPort[1]);
}
else {
- host = xForwardedHostHeader;
+ host = hostToUse;
}
}
| true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java | @@ -56,6 +56,8 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.NativeWebRequest;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.async.CallableProcessingInterceptor;
import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter;
@@ -76,11 +78,14 @@
import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
+import org.springframework.web.servlet.mvc.support.MvcUrls;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
+import org.springframework.web.util.UriComponents;
import static org.junit.Assert.*;
+import static org.springframework.web.servlet.mvc.support.MvcUrlUtils.*;
/**
* @author Keith Donald
@@ -108,7 +113,7 @@ public void setUp() throws Exception {
@Test
public void testDefaultConfig() throws Exception {
- loadBeanDefinitions("mvc-config.xml", 12);
+ loadBeanDefinitions("mvc-config.xml", 13);
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
assertNotNull(mapping);
@@ -147,11 +152,26 @@ public void testDefaultConfig() throws Exception {
adapter.handle(request, response, handlerMethod);
assertTrue(handler.recordedValidationError);
+
+ // MvcUrls
+ RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest()));
+ try {
+ Date now = new Date();
+ TestController testController = controller(TestController.class);
+ testController.testBind(now, null, null);
+ MvcUrls mvcUrls = this.appContext.getBean(MvcUrls.class);
+ UriComponents uriComponents = mvcUrls.linkToMethodOn(testController);
+
+ assertEquals("http://localhost/?date=2013-10-21", uriComponents.toUriString());
+ }
+ finally {
+ RequestContextHolder.resetRequestAttributes();
+ }
}
@Test(expected=TypeMismatchException.class)
public void testCustomConversionService() throws Exception {
- loadBeanDefinitions("mvc-config-custom-conversion-service.xml", 12);
+ loadBeanDefinitions("mvc-config-custom-conversion-service.xml", 13);
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
assertNotNull(mapping);
@@ -177,7 +197,7 @@ public void testCustomConversionService() throws Exception {
@Test
public void testCustomValidator() throws Exception {
- loadBeanDefinitions("mvc-config-custom-validator.xml", 12);
+ loadBeanDefinitions("mvc-config-custom-validator.xml", 13);
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
assertNotNull(mapping);
@@ -199,7 +219,7 @@ public void testCustomValidator() throws Exception {
@Test
public void testInterceptors() throws Exception {
- loadBeanDefinitions("mvc-config-interceptors.xml", 17);
+ loadBeanDefinitions("mvc-config-interceptors.xml", 18);
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
assertNotNull(mapping);
@@ -328,7 +348,7 @@ public void testDefaultServletHandlerWithOptionalAttributes() throws Exception {
@Test
public void testBeanDecoration() throws Exception {
- loadBeanDefinitions("mvc-config-bean-decoration.xml", 14);
+ loadBeanDefinitions("mvc-config-bean-decoration.xml", 15);
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
assertNotNull(mapping);
@@ -349,7 +369,7 @@ public void testBeanDecoration() throws Exception {
@Test
public void testViewControllers() throws Exception {
- loadBeanDefinitions("mvc-config-view-controllers.xml", 15);
+ loadBeanDefinitions("mvc-config-view-controllers.xml", 16);
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
assertNotNull(mapping);
@@ -409,7 +429,7 @@ public void testViewControllers() throws Exception {
/** WebSphere gives trailing servlet path slashes by default!! */
@Test
public void testViewControllersOnWebSphere() throws Exception {
- loadBeanDefinitions("mvc-config-view-controllers.xml", 15);
+ loadBeanDefinitions("mvc-config-view-controllers.xml", 16);
SimpleUrlHandlerMapping mapping2 = appContext.getBean(SimpleUrlHandlerMapping.class);
SimpleControllerHandlerAdapter adapter = appContext.getBean(SimpleControllerHandlerAdapter.class);
@@ -462,7 +482,7 @@ public void testViewControllersDefaultConfig() {
@Test
public void testContentNegotiationManager() throws Exception {
- loadBeanDefinitions("mvc-config-content-negotiation-manager.xml", 12);
+ loadBeanDefinitions("mvc-config-content-negotiation-manager.xml", 13);
RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
ContentNegotiationManager manager = mapping.getContentNegotiationManager();
@@ -474,7 +494,7 @@ public void testContentNegotiationManager() throws Exception {
@Test
public void testAsyncSupportOptions() throws Exception {
- loadBeanDefinitions("mvc-config-async-support.xml", 13);
+ loadBeanDefinitions("mvc-config-async-support.xml", 14);
RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class);
assertNotNull(adapter); | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportTests.java | @@ -16,28 +16,33 @@
package org.springframework.web.servlet.config.annotation;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
+import org.joda.time.DateTime;
+import org.joda.time.format.ISODateTimeFormat;
import org.junit.Before;
import org.junit.Test;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
+import org.springframework.format.annotation.DateTimeFormat;
+import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.format.support.FormattingConversionService;
-import org.springframework.http.converter.HttpMessageConverter;
+import org.springframework.http.HttpEntity;
import org.springframework.mock.web.test.MockHttpServletRequest;
import org.springframework.mock.web.test.MockServletContext;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
+import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
-import org.springframework.web.context.support.StaticWebApplicationContext;
+import org.springframework.web.context.WebApplicationContext;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.handler.AbstractHandlerMapping;
@@ -49,6 +54,11 @@
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
+import org.springframework.web.servlet.mvc.support.MvcUrls;
+import org.springframework.web.util.UriComponents;
+
+import static org.junit.Assert.*;
+import static org.springframework.web.servlet.mvc.support.MvcUrlUtils.*;
/**
* A test fixture with an {@link WebMvcConfigurationSupport} instance.
@@ -57,82 +67,84 @@
*/
public class WebMvcConfigurationSupportTests {
- private WebMvcConfigurationSupport mvcConfiguration;
-
- private StaticWebApplicationContext wac;
+ private WebApplicationContext wac;
@Before
public void setUp() {
- this.wac = new StaticWebApplicationContext();
- this.mvcConfiguration = new WebMvcConfigurationSupport();
- this.mvcConfiguration.setApplicationContext(wac);
+
+ AnnotationConfigWebApplicationContext cxt = new AnnotationConfigWebApplicationContext();
+ cxt.setServletContext(new MockServletContext());
+ cxt.register(TestConfig.class);
+ cxt.refresh();
+
+ this.wac = cxt;
}
@Test
public void requestMappingHandlerMapping() throws Exception {
- this.wac.registerSingleton("controller", TestController.class);
- RequestMappingHandlerMapping handlerMapping = mvcConfiguration.requestMappingHandlerMapping();
+ RequestMappingHandlerMapping handlerMapping = this.wac.getBean(RequestMappingHandlerMapping.class);
assertEquals(0, handlerMapping.getOrder());
- handlerMapping.setApplicationContext(this.wac);
- handlerMapping.afterPropertiesSet();
HandlerExecutionChain chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
assertNotNull(chain.getInterceptors());
assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[0].getClass());
}
@Test
public void emptyViewControllerHandlerMapping() {
- AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) mvcConfiguration.viewControllerHandlerMapping();
+
+ AbstractHandlerMapping handlerMapping = this.wac.getBean(
+ "viewControllerHandlerMapping", AbstractHandlerMapping.class);
+
assertNotNull(handlerMapping);
assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
assertTrue(handlerMapping.getClass().getName().endsWith("EmptyHandlerMapping"));
}
@Test
public void beanNameHandlerMapping() throws Exception {
- StaticWebApplicationContext cxt = new StaticWebApplicationContext();
- cxt.registerSingleton("/controller", TestController.class);
- HttpServletRequest request = new MockHttpServletRequest("GET", "/controller");
-
- BeanNameUrlHandlerMapping handlerMapping = mvcConfiguration.beanNameHandlerMapping();
+ BeanNameUrlHandlerMapping handlerMapping = this.wac.getBean(BeanNameUrlHandlerMapping.class);
assertEquals(2, handlerMapping.getOrder());
- handlerMapping.setApplicationContext(cxt);
+ HttpServletRequest request = new MockHttpServletRequest("GET", "/testController");
HandlerExecutionChain chain = handlerMapping.getHandler(request);
+
assertNotNull(chain.getInterceptors());
assertEquals(2, chain.getInterceptors().length);
assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[1].getClass());
}
@Test
public void emptyResourceHandlerMapping() {
- mvcConfiguration.setApplicationContext(new StaticWebApplicationContext());
- AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) mvcConfiguration.resourceHandlerMapping();
+
+ AbstractHandlerMapping handlerMapping = this.wac.getBean(
+ "resourceHandlerMapping", AbstractHandlerMapping.class);
+
assertNotNull(handlerMapping);
assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
assertTrue(handlerMapping.getClass().getName().endsWith("EmptyHandlerMapping"));
}
@Test
public void emptyDefaultServletHandlerMapping() {
- mvcConfiguration.setServletContext(new MockServletContext());
- AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) mvcConfiguration.defaultServletHandlerMapping();
+
+ AbstractHandlerMapping handlerMapping = this.wac.getBean(
+ "defaultServletHandlerMapping", AbstractHandlerMapping.class);
+
assertNotNull(handlerMapping);
assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
assertTrue(handlerMapping.getClass().getName().endsWith("EmptyHandlerMapping"));
}
@Test
public void requestMappingHandlerAdapter() throws Exception {
- RequestMappingHandlerAdapter adapter = mvcConfiguration.requestMappingHandlerAdapter();
- List<HttpMessageConverter<?>> expectedConverters = new ArrayList<HttpMessageConverter<?>>();
- mvcConfiguration.addDefaultHttpMessageConverters(expectedConverters);
- assertEquals(expectedConverters.size(), adapter.getMessageConverters().size());
+ RequestMappingHandlerAdapter adapter = this.wac.getBean(RequestMappingHandlerAdapter.class);
+
+ assertEquals(9, adapter.getMessageConverters().size());
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
assertNotNull(initializer);
@@ -146,10 +158,27 @@ public void requestMappingHandlerAdapter() throws Exception {
assertTrue(validator instanceof LocalValidatorFactoryBean);
}
+ @Test
+ public void mvcUrls() throws Exception {
+ RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest()));
+ try {
+ DateTime now = DateTime.now();
+ MvcUrls mvcUrls = this.wac.getBean(MvcUrls.class);
+ UriComponents uriComponents = mvcUrls.linkToMethodOn(controller(
+ TestController.class).methodWithTwoPathVariables(1, now));
+
+ assertEquals("/foo/1/bar/" + ISODateTimeFormat.date().print(now), uriComponents.getPath());
+ }
+ finally {
+ RequestContextHolder.resetRequestAttributes();
+ }
+ }
+
@Test
public void handlerExceptionResolver() throws Exception {
+
HandlerExceptionResolverComposite compositeResolver =
- (HandlerExceptionResolverComposite) mvcConfiguration.handlerExceptionResolver();
+ this.wac.getBean("handlerExceptionResolver", HandlerExceptionResolverComposite.class);
assertEquals(0, compositeResolver.getOrder());
@@ -164,12 +193,28 @@ public void handlerExceptionResolver() throws Exception {
}
+ @EnableWebMvc
+ @Configuration
+ public static class TestConfig {
+
+ @Bean(name={"/testController"})
+ public TestController testController() {
+ return new TestController();
+ }
+ }
+
@Controller
private static class TestController {
@RequestMapping("/")
public void handle() {
}
+
+ @RequestMapping("/foo/{id}/bar/{date}")
+ public HttpEntity<Void> methodWithTwoPathVariables(@PathVariable Integer id,
+ @DateTimeFormat(iso = ISO.DATE) @PathVariable DateTime date) {
+ return null;
+ }
}
} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/test/java/org/springframework/web/servlet/hypermedia/AnnotationMappingDiscovererUnitTests.java | @@ -1,112 +0,0 @@
-/*
- * Copyright 2012-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.web.servlet.hypermedia;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-
-import org.junit.Test;
-import org.springframework.core.AnnotationAttribute;
-import org.springframework.web.bind.annotation.RequestMapping;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.*;
-
-/**
- * Unit tests for {@link AnnotationMappingDiscoverer}.
- *
- * @author Oliver Gierke
- */
-public class AnnotationMappingDiscovererUnitTests {
-
- AnnotationMappingDiscoverer discoverer = new AnnotationMappingDiscoverer(
- RequestMapping.class);
-
- @Test(expected = IllegalArgumentException.class)
- public void rejectsNullAnnotationType() {
- new AnnotationMappingDiscoverer((Class<? extends Annotation>) null);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void rejectsNullAnnotationAttribute() {
- new AnnotationMappingDiscoverer((AnnotationAttribute) null);
- }
-
- @Test
- public void discoversTypeLevelMapping() {
- assertThat(discoverer.getMapping(MyController.class), is("/type"));
- }
-
- @Test
- public void discoversMethodLevelMapping() throws Exception {
- Method method = MyController.class.getMethod("method");
- assertThat(discoverer.getMapping(method), is("/type/method"));
- }
-
- @Test
- public void returnsNullForNonExistentTypeLevelMapping() {
- assertThat(discoverer.getMapping(ControllerWithoutTypeLevelMapping.class),
- is(nullValue()));
- }
-
- @Test
- public void resolvesMethodLevelMappingWithoutTypeLevelMapping() throws Exception {
-
- Method method = ControllerWithoutTypeLevelMapping.class.getMethod("method");
- assertThat(discoverer.getMapping(method), is("/method"));
- }
-
- @Test
- public void resolvesMethodLevelMappingWithSlashRootMapping() throws Exception {
-
- Method method = SlashRootMapping.class.getMethod("method");
- assertThat(discoverer.getMapping(method), is("/method"));
- }
-
- /**
- * @see #46
- */
- @Test
- public void treatsMissingMethodMappingAsEmptyMapping() throws Exception {
-
- Method method = MyController.class.getMethod("noMethodMapping");
- assertThat(discoverer.getMapping(method), is("/type"));
- }
-
- @RequestMapping("/type")
- interface MyController {
-
- @RequestMapping("/method")
- void method();
-
- @RequestMapping
- void noMethodMapping();
- }
-
- interface ControllerWithoutTypeLevelMapping {
-
- @RequestMapping("/method")
- void method();
- }
-
- @RequestMapping("/")
- interface SlashRootMapping {
-
- @RequestMapping("/method")
- void method();
- }
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/test/java/org/springframework/web/servlet/hypermedia/MvcUriComponentsBuilderFactoryUnitTests.java | @@ -1,131 +0,0 @@
-/*
- * Copyright 2012-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.web.servlet.hypermedia;
-
-import java.net.URI;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import org.joda.time.DateTime;
-import org.joda.time.format.ISODateTimeFormat;
-import org.junit.Test;
-import org.springframework.core.MethodParameter;
-import org.springframework.format.annotation.DateTimeFormat;
-import org.springframework.format.annotation.DateTimeFormat.ISO;
-import org.springframework.http.HttpEntity;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.servlet.hypermedia.MvcUriComponentsBuilderUnitTests.PersonControllerImpl;
-import org.springframework.web.servlet.hypermedia.MvcUriComponentsBuilderUnitTests.PersonsAddressesController;
-import org.springframework.web.util.UriComponentsBuilder;
-
-import static org.hamcrest.Matchers.*;
-import static org.junit.Assert.*;
-import static org.springframework.web.servlet.hypermedia.MvcUriComponentsBuilder.*;
-
-/**
- * Unit tests for {@link MvcUriComponentsBuilderFactory}.
- *
- * @author Ricardo Gladwell
- * @author Oliver Gierke
- */
-public class MvcUriComponentsBuilderFactoryUnitTests extends TestUtils {
-
- List<UriComponentsContributor> contributors = Collections.emptyList();
-
- MvcUriComponentsBuilderFactory factory = new MvcUriComponentsBuilderFactory(
- contributors);
-
- @Test
- public void createsLinkToControllerRoot() {
-
- URI link = factory.from(PersonControllerImpl.class).build().toUri();
-
- assertPointsToMockServer(link);
- assertThat(link.toString(), endsWith("/people"));
- }
-
- @Test
- public void createsLinkToParameterizedControllerRoot() {
-
- URI link = factory.from(PersonsAddressesController.class, 15).build().toUri();
-
- assertPointsToMockServer(link);
- assertThat(link.toString(), endsWith("/people/15/addresses"));
- }
-
- @Test
- public void appliesParameterValueIfContributorConfigured() {
-
- List<? extends UriComponentsContributor> contributors = Arrays.asList(new SampleUriComponentsContributor());
- MvcUriComponentsBuilderFactory factory = new MvcUriComponentsBuilderFactory(
- contributors);
-
- SpecialType specialType = new SpecialType();
- specialType.parameterValue = "value";
-
- URI link = factory.from(
- methodOn(SampleController.class).sampleMethod(1L, specialType)).build().toUri();
- assertPointsToMockServer(link);
- assertThat(link.toString(), endsWith("/sample/1?foo=value"));
- }
-
- /**
- * @see #57
- */
- @Test
- public void usesDateTimeFormatForUriBinding() {
-
- DateTime now = DateTime.now();
-
- MvcUriComponentsBuilderFactory factory = new MvcUriComponentsBuilderFactory(
- contributors);
- URI link = factory.from(methodOn(SampleController.class).sampleMethod(now)).build().toUri();
- assertThat(link.toString(),
- endsWith("/sample/" + ISODateTimeFormat.date().print(now)));
- }
-
- static interface SampleController {
-
- @RequestMapping("/sample/{id}")
- HttpEntity<?> sampleMethod(@PathVariable("id") Long id, SpecialType parameter);
-
- @RequestMapping("/sample/{time}")
- HttpEntity<?> sampleMethod(
- @PathVariable("time") @DateTimeFormat(iso = ISO.DATE) DateTime time);
- }
-
- static class SampleUriComponentsContributor implements UriComponentsContributor {
-
- @Override
- public boolean supportsParameter(MethodParameter parameter) {
- return SpecialType.class.equals(parameter.getParameterType());
- }
-
- @Override
- public void enhance(UriComponentsBuilder builder, MethodParameter parameter,
- Object value) {
- builder.queryParam("foo", ((SpecialType) value).parameterValue);
- }
- }
-
- static class SpecialType {
-
- String parameterValue;
- }
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/test/java/org/springframework/web/servlet/hypermedia/MvcUriComponentsBuilderUnitTests.java | @@ -1,250 +0,0 @@
-/*
- * Copyright 2012-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.web.servlet.hypermedia;
-
-import java.net.URI;
-import java.util.Arrays;
-import java.util.List;
-
-import org.hamcrest.Matchers;
-import org.junit.Test;
-import org.springframework.http.HttpEntity;
-import org.springframework.util.MultiValueMap;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-import org.springframework.web.util.UriComponents;
-import org.springframework.web.util.UriComponentsBuilder;
-
-import static org.hamcrest.Matchers.*;
-import static org.junit.Assert.*;
-import static org.springframework.web.servlet.hypermedia.MvcUriComponentsBuilder.*;
-
-/**
- * Unit tests for {@link MvcUriComponentsBuilder}.
- *
- * @author Oliver Gierke
- * @author Dietrich Schulten
- */
-public class MvcUriComponentsBuilderUnitTests extends TestUtils {
-
- @Test
- public void createsLinkToControllerRoot() {
-
- URI link = from(PersonControllerImpl.class).build().toUri();
- assertThat(link.toString(), Matchers.endsWith("/people"));
- }
-
- @Test
- public void createsLinkToParameterizedControllerRoot() {
-
- URI link = from(PersonsAddressesController.class, 15).build().toUri();
- assertThat(link.toString(), endsWith("/people/15/addresses"));
- }
-
- /**
- * @see #70
- */
- @Test
- public void createsLinkToMethodOnParameterizedControllerRoot() {
-
- URI link = from(
- methodOn(PersonsAddressesController.class, 15).getAddressesForCountry(
- "DE")).build().toUri();
- assertThat(link.toString(), endsWith("/people/15/addresses/DE"));
- }
-
- @Test
- public void createsLinkToSubResource() {
-
- URI link = from(PersonControllerImpl.class).pathSegment("something").build().toUri();
- assertThat(link.toString(), endsWith("/people/something"));
- }
-
- @Test(expected = IllegalStateException.class)
- public void rejectsControllerWithMultipleMappings() {
- from(InvalidController.class);
- }
-
- @Test
- public void createsLinkToUnmappedController() {
-
- URI link = from(UnmappedController.class).build().toUri();
- assertThat(link.toString(), is("http://localhost/"));
- }
-
- @Test
- public void appendingNullIsANoOp() {
-
- URI link = from(PersonControllerImpl.class).path(null).build().toUri();
- assertThat(link.toString(), endsWith("/people"));
- }
-
- @Test
- public void linksToMethod() {
-
- URI link = from(methodOn(ControllerWithMethods.class).myMethod(null)).build().toUri();
- assertPointsToMockServer(link);
- assertThat(link.toString(), endsWith("/something/else"));
- }
-
- @Test
- public void linksToMethodWithPathVariable() {
-
- URI link = from(methodOn(ControllerWithMethods.class).methodWithPathVariable("1")).build().toUri();
- assertPointsToMockServer(link);
- assertThat(link.toString(), endsWith("/something/1/foo"));
- }
-
- /**
- * @see #33
- */
- @Test
- public void usesForwardedHostAsHostIfHeaderIsSet() {
-
- request.addHeader("X-Forwarded-Host", "somethingDifferent");
-
- URI link = from(PersonControllerImpl.class).build().toUri();
- assertThat(link.toString(), startsWith("http://somethingDifferent"));
- }
-
- /**
- * @see #26, #39
- */
- @Test
- public void linksToMethodWithPathVariableAndRequestParams() {
-
- URI link = from(
- methodOn(ControllerWithMethods.class).methodForNextPage("1", 10, 5)).build().toUri();
-
- UriComponents components = toComponents(link);
- assertThat(components.getPath(), is("/something/1/foo"));
-
- MultiValueMap<String, String> queryParams = components.getQueryParams();
- assertThat(queryParams.get("limit"), contains("5"));
- assertThat(queryParams.get("offset"), contains("10"));
- }
-
- /**
- * @see #26, #39
- */
- @Test
- public void linksToMethodWithPathVariableAndMultiValueRequestParams() {
-
- URI link = from(
- methodOn(ControllerWithMethods.class).methodWithMultiValueRequestParams(
- "1", Arrays.asList(3, 7), 5)).build().toUri();
-
- UriComponents components = toComponents(link);
- assertThat(components.getPath(), is("/something/1/foo"));
-
- MultiValueMap<String, String> queryParams = components.getQueryParams();
- assertThat(queryParams.get("limit"), contains("5"));
- assertThat(queryParams.get("items"), containsInAnyOrder("3", "7"));
- }
-
- /**
- * @see #90
- */
- @Test
- public void usesForwardedHostAndPortFromHeader() {
-
- request.addHeader("X-Forwarded-Host", "foobar:8088");
-
- URI link = from(PersonControllerImpl.class).build().toUri();
- assertThat(link.toString(), startsWith("http://foobar:8088"));
- }
-
- /**
- * @see #90
- */
- @Test
- public void usesFirstHostOfXForwardedHost() {
-
- request.addHeader("X-Forwarded-Host", "barfoo:8888, localhost:8088");
-
- URI link = from(PersonControllerImpl.class).build().toUri();
- assertThat(link.toString(), startsWith("http://barfoo:8888"));
- }
-
- private static UriComponents toComponents(URI link) {
- return UriComponentsBuilder.fromUri(link).build();
- }
-
- static class Person {
-
- Long id;
-
- public Long getId() {
- return id;
- }
- }
-
- @RequestMapping("/people")
- interface PersonController {
-
- }
-
- class PersonControllerImpl implements PersonController {
-
- }
-
- @RequestMapping("/people/{id}/addresses")
- static class PersonsAddressesController {
-
- @RequestMapping("/{country}")
- public HttpEntity<Void> getAddressesForCountry(@PathVariable String country) {
- return null;
- }
- }
-
- @RequestMapping({ "/persons", "/people" })
- class InvalidController {
-
- }
-
- class UnmappedController {
-
- }
-
- @RequestMapping("/something")
- static class ControllerWithMethods {
-
- @RequestMapping("/else")
- HttpEntity<Void> myMethod(@RequestBody Object payload) {
- return null;
- }
-
- @RequestMapping("/{id}/foo")
- HttpEntity<Void> methodWithPathVariable(@PathVariable String id) {
- return null;
- }
-
- @RequestMapping(value = "/{id}/foo")
- HttpEntity<Void> methodForNextPage(@PathVariable String id,
- @RequestParam Integer offset, @RequestParam Integer limit) {
- return null;
- }
-
- @RequestMapping(value = "/{id}/foo")
- HttpEntity<Void> methodWithMultiValueRequestParams(@PathVariable String id,
- @RequestParam List<Integer> items, @RequestParam Integer limit) {
- return null;
- }
- }
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/test/java/org/springframework/web/servlet/hypermedia/RecordedInvocationUtilsUnitTests.java | @@ -1,47 +0,0 @@
-/*
- * Copyright 2012 the original author or authors.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.springframework.web.servlet.hypermedia;
-
-import org.junit.Test;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.RequestMapping;
-
-/**
- * @author Oliver Gierke
- */
-public class RecordedInvocationUtilsUnitTests extends TestUtils {
-
- @Test
- public void test() {
-
- MvcUriComponentsBuilder.from(RecordedInvocationUtils.methodOn(SampleController.class).someMethod(
- 1L));
-
- }
-
- @RequestMapping("/sample")
- static class SampleController {
-
- @RequestMapping("/{id}/foo")
- HttpEntity<Void> someMethod(@PathVariable("id") Long id) {
- return new ResponseEntity<Void>(HttpStatus.OK);
- }
- }
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/test/java/org/springframework/web/servlet/hypermedia/TestUtils.java | @@ -1,49 +0,0 @@
-/*
- * Copyright 2012-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.web.servlet.hypermedia;
-
-import java.net.URI;
-
-import org.junit.Before;
-import org.springframework.mock.web.test.MockHttpServletRequest;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
-
-import static org.hamcrest.Matchers.*;
-import static org.junit.Assert.*;
-
-/**
- * Utility class to ease tesing.
- *
- * @author Oliver Gierke
- */
-public class TestUtils {
-
- protected MockHttpServletRequest request;
-
- @Before
- public void setUp() {
-
- request = new MockHttpServletRequest();
- ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
- RequestContextHolder.setRequestAttributes(requestAttributes);
- }
-
- protected void assertPointsToMockServer(URI link) {
- assertThat(link.toString(), startsWith("http://localhost"));
- }
-} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/DefaultMvcUrlsTests.java | @@ -0,0 +1,290 @@
+/*
+ * Copyright 2012-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.web.servlet.mvc.support;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.hamcrest.Matchers;
+import org.joda.time.DateTime;
+import org.joda.time.format.ISODateTimeFormat;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.springframework.format.annotation.DateTimeFormat;
+import org.springframework.format.annotation.DateTimeFormat.ISO;
+import org.springframework.http.HttpEntity;
+import org.springframework.mock.web.test.MockHttpServletRequest;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import org.springframework.web.method.annotation.RequestParamMethodArgumentResolver;
+import org.springframework.web.method.support.HandlerMethodArgumentResolver;
+import org.springframework.web.servlet.mvc.method.annotation.PathVariableMethodArgumentResolver;
+import org.springframework.web.util.UriComponents;
+
+import static org.hamcrest.Matchers.*;
+import static org.junit.Assert.*;
+import static org.springframework.web.servlet.mvc.support.MvcUrlUtils.*;
+
+/**
+ * Unit tests for {@link DefaultMvcUrls}.
+ *
+ * @author Oliver Gierke
+ * @author Dietrich Schulten
+ * @author Rossen Stoyanchev
+ */
+public class DefaultMvcUrlsTests {
+
+ private MockHttpServletRequest request;
+
+ private MvcUrls mvcUrls;
+
+
+ @Before
+ public void setUp() {
+ this.request = new MockHttpServletRequest();
+ ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
+ RequestContextHolder.setRequestAttributes(requestAttributes);
+
+ List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>();
+ resolvers.add(new PathVariableMethodArgumentResolver());
+ resolvers.add(new RequestParamMethodArgumentResolver(null, false));
+
+ this.mvcUrls = new DefaultMvcUrls(resolvers, null);
+ }
+
+ @After
+ public void teardown() {
+ RequestContextHolder.resetRequestAttributes();
+ }
+
+
+ @Test
+ public void linkToControllerRoot() {
+ UriComponents uriComponents = this.mvcUrls.linkToController(PersonControllerImpl.class).build();
+ assertThat(uriComponents.toUriString(), Matchers.endsWith("/people"));
+ }
+
+ @Test
+ public void linkToParameterizedControllerRoot() {
+ UriComponents uriComponents = this.mvcUrls.linkToController(
+ PersonsAddressesController.class).buildAndExpand(15);
+
+ assertThat(uriComponents.toUriString(), endsWith("/people/15/addresses"));
+ }
+
+ @Test
+ public void linkToMethodOnParameterizedControllerRoot() {
+ UriComponents uriComponents = this.mvcUrls.linkToMethodOn(
+ controller(PersonsAddressesController.class, 15).getAddressesForCountry("DE"));
+
+ assertThat(uriComponents.toUriString(), endsWith("/people/15/addresses/DE"));
+ }
+
+ @Test
+ public void linkToSubResource() {
+ UriComponents uriComponents =
+ this.mvcUrls.linkToController(PersonControllerImpl.class).pathSegment("something").build();
+
+ assertThat(uriComponents.toUriString(), endsWith("/people/something"));
+ }
+
+ @Test
+ public void linkToControllerWithMultipleMappings() {
+ UriComponents uriComponents = this.mvcUrls.linkToController(InvalidController.class).build();
+ assertThat(uriComponents.toUriString(), is("http://localhost/persons"));
+ }
+
+ @Test
+ public void linkToControllerNotMapped() {
+ UriComponents uriComponents = this.mvcUrls.linkToController(UnmappedController.class).build();
+ assertThat(uriComponents.toUriString(), is("http://localhost/"));
+ }
+
+ @Test
+ public void linkToMethodRefWithPathVar() throws Exception {
+ Method method = ControllerWithMethods.class.getDeclaredMethod("methodWithPathVariable", String.class);
+ UriComponents uriComponents = this.mvcUrls.linkToMethod(method, new Object[] { "1" });
+
+ assertThat(uriComponents.toUriString(), is("http://localhost/something/1/foo"));
+ }
+
+ @Test
+ public void linkToMethodRefWithTwoPathVars() throws Exception {
+ DateTime now = DateTime.now();
+ Method method = ControllerWithMethods.class.getDeclaredMethod(
+ "methodWithTwoPathVariables", Integer.class, DateTime.class);
+ UriComponents uriComponents = this.mvcUrls.linkToMethod(method, new Object[] { 1, now });
+
+ assertThat(uriComponents.getPath(), is("/something/1/foo/" + ISODateTimeFormat.date().print(now)));
+ }
+
+ @Test
+ public void linkToMethodRefWithPathVarAndRequestParam() throws Exception {
+ Method method = ControllerWithMethods.class.getDeclaredMethod("methodForNextPage", String.class, Integer.class, Integer.class);
+ UriComponents uriComponents = this.mvcUrls.linkToMethod(method, new Object[] {"1", 10, 5});
+
+ assertThat(uriComponents.getPath(), is("/something/1/foo"));
+
+ MultiValueMap<String, String> queryParams = uriComponents.getQueryParams();
+ assertThat(queryParams.get("limit"), contains("5"));
+ assertThat(queryParams.get("offset"), contains("10"));
+ }
+
+ @Test
+ public void linkToMethod() {
+ UriComponents uriComponents = this.mvcUrls.linkToMethodOn(
+ controller(ControllerWithMethods.class).myMethod(null));
+
+ assertThat(uriComponents.toUriString(), startsWith("http://localhost"));
+ assertThat(uriComponents.toUriString(), endsWith("/something/else"));
+ }
+
+ @Test
+ public void linkToMethodWithPathVar() {
+ UriComponents uriComponents = this.mvcUrls.linkToMethodOn(
+ controller(ControllerWithMethods.class).methodWithPathVariable("1"));
+
+ assertThat(uriComponents.toUriString(), startsWith("http://localhost"));
+ assertThat(uriComponents.toUriString(), endsWith("/something/1/foo"));
+ }
+
+ @Test
+ public void linkToMethodWithPathVarAndRequestParams() {
+ UriComponents uriComponents = this.mvcUrls.linkToMethodOn(
+ controller(ControllerWithMethods.class).methodForNextPage("1", 10, 5));
+
+ assertThat(uriComponents.getPath(), is("/something/1/foo"));
+
+ MultiValueMap<String, String> queryParams = uriComponents.getQueryParams();
+ assertThat(queryParams.get("limit"), contains("5"));
+ assertThat(queryParams.get("offset"), contains("10"));
+ }
+
+ @Test
+ public void linkToMethodWithPathVarAndMultiValueRequestParams() {
+ UriComponents uriComponents = this.mvcUrls.linkToMethodOn(
+ controller(ControllerWithMethods.class).methodWithMultiValueRequestParams(
+ "1", Arrays.asList(3, 7), 5));
+
+ assertThat(uriComponents.getPath(), is("/something/1/foo"));
+
+ MultiValueMap<String, String> queryParams = uriComponents.getQueryParams();
+ assertThat(queryParams.get("limit"), contains("5"));
+ assertThat(queryParams.get("items"), containsInAnyOrder("3", "7"));
+ }
+
+ @Test
+ public void usesForwardedHostAsHostIfHeaderIsSet() {
+ this.request.addHeader("X-Forwarded-Host", "somethingDifferent");
+ UriComponents uriComponents = this.mvcUrls.linkToController(PersonControllerImpl.class).build();
+
+ assertThat(uriComponents.toUriString(), startsWith("http://somethingDifferent"));
+ }
+
+ @Test
+ public void usesForwardedHostAndPortFromHeader() {
+ request.addHeader("X-Forwarded-Host", "foobar:8088");
+ UriComponents uriComponents = this.mvcUrls.linkToController(PersonControllerImpl.class).build();
+
+ assertThat(uriComponents.toUriString(), startsWith("http://foobar:8088"));
+ }
+
+ @Test
+ public void usesFirstHostOfXForwardedHost() {
+ request.addHeader("X-Forwarded-Host", "barfoo:8888, localhost:8088");
+ UriComponents uriComponents = this.mvcUrls.linkToController(PersonControllerImpl.class).build();
+
+ assertThat(uriComponents.toUriString(), startsWith("http://barfoo:8888"));
+ }
+
+
+ static class Person {
+
+ Long id;
+
+ public Long getId() {
+ return id;
+ }
+ }
+
+ @RequestMapping("/people")
+ interface PersonController {
+
+ }
+
+ class PersonControllerImpl implements PersonController {
+
+ }
+
+ @RequestMapping("/people/{id}/addresses")
+ static class PersonsAddressesController {
+
+ @RequestMapping("/{country}")
+ public HttpEntity<Void> getAddressesForCountry(@PathVariable String country) {
+ return null;
+ }
+ }
+
+ @RequestMapping({ "/persons", "/people" })
+ class InvalidController {
+
+ }
+
+ class UnmappedController {
+
+ }
+
+ @RequestMapping("/something")
+ static class ControllerWithMethods {
+
+ @RequestMapping("/else")
+ HttpEntity<Void> myMethod(@RequestBody Object payload) {
+ return null;
+ }
+
+ @RequestMapping("/{id}/foo")
+ HttpEntity<Void> methodWithPathVariable(@PathVariable String id) {
+ return null;
+ }
+
+ @RequestMapping("/{id}/foo/{date}")
+ HttpEntity<Void> methodWithTwoPathVariables(
+ @PathVariable Integer id, @DateTimeFormat(iso = ISO.DATE) @PathVariable DateTime date) {
+ return null;
+ }
+
+ @RequestMapping(value = "/{id}/foo")
+ HttpEntity<Void> methodForNextPage(@PathVariable String id,
+ @RequestParam Integer offset, @RequestParam Integer limit) {
+ return null;
+ }
+
+ @RequestMapping(value = "/{id}/foo")
+ HttpEntity<Void> methodWithMultiValueRequestParams(@PathVariable String id,
+ @RequestParam List<Integer> items, @RequestParam Integer limit) {
+ return null;
+ }
+ }
+} | true |
Other | spring-projects | spring-framework | bafc73f1477330ef1bdb292608deea6e06ef2bed.json | Integrate suggested support for creating MVC URLs
The key contract is MvcUrls. An instance is automatically created with
the Spring MVC namespace and the MVC Java config but can also be easily
created in any configuration.
Some example tests can be found in DefaultMvcUrlsTests.
Issue: SPR-10665, SPR-8826 | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/MvcUrlUtilsTests.java | @@ -0,0 +1,122 @@
+/*
+ * Copyright 2012-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.web.servlet.mvc.support;
+
+import java.lang.reflect.Method;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.mock.web.test.MockHttpServletRequest;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+import org.springframework.web.servlet.mvc.support.MvcUrlUtils.ControllerMethodValues;
+
+import static org.hamcrest.CoreMatchers.*;
+import static org.junit.Assert.*;
+
+/**
+ * Test fixture for {@link MvcUrlUtils}.
+ *
+ * @author Oliver Gierke
+ * @author Rossen Stoyanchev
+ */
+public class MvcUrlUtilsTests {
+
+ private MockHttpServletRequest request;
+
+
+ @Before
+ public void setUp() {
+ this.request = new MockHttpServletRequest();
+ ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
+ RequestContextHolder.setRequestAttributes(requestAttributes);
+ }
+
+ @After
+ public void teardown() {
+ RequestContextHolder.resetRequestAttributes();
+ }
+
+ @Test
+ public void methodOn() {
+ HttpEntity<Void> result = MvcUrlUtils.controller(SampleController.class).someMethod(1L);
+
+ assertTrue(result instanceof ControllerMethodValues);
+ assertEquals("someMethod", ((ControllerMethodValues) result).getControllerMethod().getName());
+ }
+
+ @Test
+ public void typeLevelMapping() {
+ assertThat(MvcUrlUtils.getTypeLevelMapping(MyController.class), is("/type"));
+ }
+
+ @Test
+ public void typeLevelMappingNone() {
+ assertThat(MvcUrlUtils.getTypeLevelMapping(ControllerWithoutTypeLevelMapping.class), is("/"));
+ }
+
+ @Test
+ public void methodLevelMapping() throws Exception {
+ Method method = MyController.class.getMethod("method");
+ assertThat(MvcUrlUtils.getMethodMapping(method), is("/type/method"));
+ }
+
+ @Test
+ public void methodLevelMappingWithoutTypeLevelMapping() throws Exception {
+ Method method = ControllerWithoutTypeLevelMapping.class.getMethod("method");
+ assertThat(MvcUrlUtils.getMethodMapping(method), is("/method"));
+ }
+
+ @Test
+ public void methodMappingWithControllerMappingOnly() throws Exception {
+ Method method = MyController.class.getMethod("noMethodMapping");
+ assertThat(MvcUrlUtils.getMethodMapping(method), is("/type"));
+ }
+
+
+ @RequestMapping("/sample")
+ static class SampleController {
+
+ @RequestMapping("/{id}/foo")
+ HttpEntity<Void> someMethod(@PathVariable("id") Long id) {
+ return new ResponseEntity<Void>(HttpStatus.OK);
+ }
+ }
+
+ @RequestMapping("/type")
+ interface MyController {
+
+ @RequestMapping("/method")
+ void method();
+
+ @RequestMapping
+ void noMethodMapping();
+ }
+
+ interface ControllerWithoutTypeLevelMapping {
+
+ @RequestMapping("/method")
+ void method();
+ }
+
+} | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.