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
5b147bfba8d5d5837b96357a52867e433137f64b.json
Improve speed of spring-test build - Now excluding *TestSuite classes from the JUnit test task. - Renamed SpringJUnit4SuiteTests to SpringJUnit4TestSuite so that it is no longer executed in the build. - Reduced sleep time in various timing related tests.
spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4TestSuite.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,15 +42,16 @@ /** * JUnit test suite for tests involving {@link SpringJUnit4ClassRunner} and the - * <em>Spring TestContext Framework</em>. + * <em>Spring TestContext Framework</em>; only intended to be run manually as a + * convenience. * * <p>This test suite serves a dual purpose of verifying that tests run with * {@link SpringJUnit4ClassRunner} can be used in conjunction with JUnit's * {@link Suite} runner. * * <p>Note that tests included in this suite will be executed at least twice if - * run from an automated build process, test runner, etc. that is configured to - * run tests based on a &quot;*Tests.class&quot; pattern match. + * run from an automated build process, test runner, etc. that is not configured + * to exclude tests based on a &quot;*TestSuite.class&quot; pattern match. * * @author Sam Brannen * @since 2.5 @@ -104,6 +105,6 @@ TimedTransactionalSpringRunnerTests.class,// HibernateSessionFlushingTests.class // }) -public class SpringJUnit4SuiteTests { +public class SpringJUnit4TestSuite { /* this test case consists entirely of tests loaded as a suite. */ }
true
Other
spring-projects
spring-framework
5b147bfba8d5d5837b96357a52867e433137f64b.json
Improve speed of spring-test build - Now excluding *TestSuite classes from the JUnit test task. - Renamed SpringJUnit4SuiteTests to SpringJUnit4TestSuite so that it is no longer executed in the build. - Reduced sleep time in various timing related tests.
spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java
@@ -76,16 +76,16 @@ public void testSpringTimeoutWithNoOp() { } // Should Fail due to timeout. - @Test(timeout = 200) + @Test(timeout = 10) public void testJUnitTimeoutWithOneSecondWait() throws Exception { - Thread.sleep(1000); + Thread.sleep(20); } // Should Fail due to timeout. @Test - @Timed(millis = 200) + @Timed(millis = 10) public void testSpringTimeoutWithOneSecondWait() throws Exception { - Thread.sleep(1000); + Thread.sleep(20); } // Should Fail due to duplicate configuration.
true
Other
spring-projects
spring-framework
b8f408ed5faae1bf266331063bc2ea575962bead.json
Replace space indentation with tabs Issue: SPR-9990
build.gradle
@@ -753,18 +753,18 @@ configure(rootProject) { apply plugin: "docbook-reference" apply plugin: "groovy" apply from: "${gradleScriptDir}/jdiff.gradle" - apply plugin: org.springframework.build.gradle.SplitPackageDetectorPlugin + apply plugin: org.springframework.build.gradle.SplitPackageDetectorPlugin - reference { + reference { sourceDir = file("src/reference/docbook") pdfFilename = "spring-framework-reference.pdf" } - diagnoseSplitPackages { - projectsToScan = project.subprojects - project(":spring-instrument-tomcat") // SPR-10150 - } + diagnoseSplitPackages { + projectsToScan = project.subprojects - project(":spring-instrument-tomcat") // SPR-10150 + } - // don"t publish the default jar for the root project + // don"t publish the default jar for the root project configurations.archives.artifacts.clear() dependencies { // for integration tests @@ -788,7 +788,7 @@ configure(rootProject) { testCompile("hsqldb:hsqldb:${hsqldbVersion}") } - check.dependsOn diagnoseSplitPackages + check.dependsOn diagnoseSplitPackages task api(type: Javadoc) { group = "Documentation"
true
Other
spring-projects
spring-framework
b8f408ed5faae1bf266331063bc2ea575962bead.json
Replace space indentation with tabs Issue: SPR-9990
buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy
@@ -31,101 +31,101 @@ import org.gradle.plugins.ide.eclipse.model.EclipseClasspath import org.gradle.plugins.ide.idea.IdeaPlugin class SplitPackageDetectorPlugin implements Plugin<Project> { - public void apply(Project project) { - Task diagnoseSplitPackages = project.tasks.add('diagnoseSplitPackages', SplitPackageDetectorTask.class) - diagnoseSplitPackages.setDescription('Detects packages which will be split across JARs') - } + public void apply(Project project) { + Task diagnoseSplitPackages = project.tasks.add('diagnoseSplitPackages', SplitPackageDetectorTask.class) + diagnoseSplitPackages.setDescription('Detects packages which will be split across JARs') + } } public class SplitPackageDetectorTask extends DefaultTask { - @Input - Set<Project> projectsToScan - - @TaskAction - public final void diagnoseSplitPackages() { - def Map<Project, Project> mergeMap = [:] - def projects = projectsToScan.findAll { it.plugins.findPlugin(org.springframework.build.gradle.MergePlugin) }.findAll { it.merge.into } - projects.each { p -> - mergeMap.put(p, p.merge.into) - } - def splitFound = new org.springframework.build.gradle.SplitPackageDetector(projectsToScan, mergeMap, project.logger).diagnoseSplitPackages(); - assert !splitFound // see error log messages for details of split packages - } + @Input + Set<Project> projectsToScan + + @TaskAction + public final void diagnoseSplitPackages() { + def Map<Project, Project> mergeMap = [:] + def projects = projectsToScan.findAll { it.plugins.findPlugin(org.springframework.build.gradle.MergePlugin) }.findAll { it.merge.into } + projects.each { p -> + mergeMap.put(p, p.merge.into) + } + def splitFound = new org.springframework.build.gradle.SplitPackageDetector(projectsToScan, mergeMap, project.logger).diagnoseSplitPackages(); + assert !splitFound // see error log messages for details of split packages + } } class SplitPackageDetector { - private static final String HIDDEN_DIRECTORY_PREFIX = "." - - private static final String JAVA_FILE_SUFFIX = ".java" - - private static final String SRC_MAIN_JAVA = "src" + File.separator + "main" + File.separator + "java" - - private static final String PACKAGE_SEPARATOR = "." - - private final Map<Project, Project> mergeMap - - private final Map<Project, Set<String>> pkgMap = [:] - - private final logger - - SplitPackageDetector(projectsToScan, mergeMap, logger) { - this.mergeMap = mergeMap - this.logger = logger - projectsToScan.each { Project p -> - def dir = p.projectDir - def packages = getPackagesInDirectory(dir) - if (!packages.isEmpty()) { - pkgMap.put(p, packages) - } - } - } - - private File[] dirList(String dir) { - dirList(new File(dir)) - } - - private File[] dirList(File dir) { - dir.listFiles({ file -> file.isDirectory() && !file.getName().startsWith(HIDDEN_DIRECTORY_PREFIX) } as FileFilter) - } - - private Set<String> getPackagesInDirectory(File dir) { - def pkgs = new HashSet<String>() - addPackagesInDirectory(pkgs, new File(dir, SRC_MAIN_JAVA), "") - return pkgs; - } - - boolean diagnoseSplitPackages() { - def splitFound = false; - def projs = pkgMap.keySet().toArray() - def numProjects = projs.length - for (int i = 0; i < numProjects - 1; i++) { - for (int j = i + 1; j < numProjects - 1; j++) { - def pi = projs[i] - def pkgi = new HashSet(pkgMap.get(pi)) - def pj = projs[j] - def pkgj = pkgMap.get(pj) - pkgi.retainAll(pkgj) - if (!pkgi.isEmpty() && mergeMap.get(pi) != pj && mergeMap.get(pj) != pi) { - pkgi.each { pkg -> - def readablePkg = pkg.substring(1).replaceAll(File.separator, PACKAGE_SEPARATOR) - logger.error("Package '$readablePkg' is split between $pi and $pj") - } - splitFound = true - } - } - } - return splitFound - } - - private void addPackagesInDirectory(HashSet<String> packages, File dir, String pkg) { - def scanDir = new File(dir, pkg) - def File[] javaFiles = scanDir.listFiles({ file -> !file.isDirectory() && file.getName().endsWith(JAVA_FILE_SUFFIX) } as FileFilter) - if (javaFiles != null && javaFiles.length != 0) { - packages.add(pkg) - } - dirList(scanDir).each { File subDir -> - addPackagesInDirectory(packages, dir, pkg + File.separator + subDir.getName()) - } - } -} \ No newline at end of file + private static final String HIDDEN_DIRECTORY_PREFIX = "." + + private static final String JAVA_FILE_SUFFIX = ".java" + + private static final String SRC_MAIN_JAVA = "src" + File.separator + "main" + File.separator + "java" + + private static final String PACKAGE_SEPARATOR = "." + + private final Map<Project, Project> mergeMap + + private final Map<Project, Set<String>> pkgMap = [:] + + private final logger + + SplitPackageDetector(projectsToScan, mergeMap, logger) { + this.mergeMap = mergeMap + this.logger = logger + projectsToScan.each { Project p -> + def dir = p.projectDir + def packages = getPackagesInDirectory(dir) + if (!packages.isEmpty()) { + pkgMap.put(p, packages) + } + } + } + + private File[] dirList(String dir) { + dirList(new File(dir)) + } + + private File[] dirList(File dir) { + dir.listFiles({ file -> file.isDirectory() && !file.getName().startsWith(HIDDEN_DIRECTORY_PREFIX) } as FileFilter) + } + + private Set<String> getPackagesInDirectory(File dir) { + def pkgs = new HashSet<String>() + addPackagesInDirectory(pkgs, new File(dir, SRC_MAIN_JAVA), "") + return pkgs; + } + + boolean diagnoseSplitPackages() { + def splitFound = false; + def projs = pkgMap.keySet().toArray() + def numProjects = projs.length + for (int i = 0; i < numProjects - 1; i++) { + for (int j = i + 1; j < numProjects - 1; j++) { + def pi = projs[i] + def pkgi = new HashSet(pkgMap.get(pi)) + def pj = projs[j] + def pkgj = pkgMap.get(pj) + pkgi.retainAll(pkgj) + if (!pkgi.isEmpty() && mergeMap.get(pi) != pj && mergeMap.get(pj) != pi) { + pkgi.each { pkg -> + def readablePkg = pkg.substring(1).replaceAll(File.separator, PACKAGE_SEPARATOR) + logger.error("Package '$readablePkg' is split between $pi and $pj") + } + splitFound = true + } + } + } + return splitFound + } + + private void addPackagesInDirectory(HashSet<String> packages, File dir, String pkg) { + def scanDir = new File(dir, pkg) + def File[] javaFiles = scanDir.listFiles({ file -> !file.isDirectory() && file.getName().endsWith(JAVA_FILE_SUFFIX) } as FileFilter) + if (javaFiles != null && javaFiles.length != 0) { + packages.add(pkg) + } + dirList(scanDir).each { File subDir -> + addPackagesInDirectory(packages, dir, pkg + File.separator + subDir.getName()) + } + } +}
true
Other
spring-projects
spring-framework
a0e5394203d3f485c592c2d05d7d1a6b3cff6ced.json
Exclude stax test dependency Exclude transitive stax 1.0 dependency to prevent compile time eclipse errors.
build.gradle
@@ -235,7 +235,9 @@ project("spring-core") { optional("net.sf.jopt-simple:jopt-simple:3.0") optional("log4j:log4j:1.2.17") testCompile("xmlunit:xmlunit:1.3") - testCompile("org.codehaus.woodstox:wstx-asl:3.2.7") + testCompile("org.codehaus.woodstox:wstx-asl:3.2.7") { + exclude group: "stax", module: "stax-api" + } } jar {
false
Other
spring-projects
spring-framework
18bf860c273179f95719d80b14d17c0c9ba99c38.json
Update Javadoc for MockMvc Deleted reference to the obsolete configureWarRootDir() method from the stand-alone spring-test-mvc project.
spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvc.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ * * WebApplicationContext wac = ...; * - * MockMvc mockMvc = webAppContextSetup(wac).configureWarRootDir("src/main/webapp", false).build() + * MockMvc mockMvc = webAppContextSetup(wac).build(); * * mockMvc.perform(get("/form")) * .andExpect(status().isOk())
false
Other
spring-projects
spring-framework
91da1383143bc15f945935960a79bc253bd1ce16.json
Use explicit JDK versions in aspects.gradle Previously aspects.gradle used the Gradle conventions for the source and target compatibility. This means that unless the conventions were updated the current JDK would be used for both source and target compatibilty. Since an update to build.gradle changed to configure the compileJava and compileTestJava tasks explicitly spring-aspects has been compiled with JDK 7 compatibility. This commit explicitly uses the source and target compatibility from spring-core to ensure that aspects.gradle is kept up to date. Issue: SPR-10161
spring-aspects/aspects.gradle
@@ -21,6 +21,9 @@ task compileJava(overwrite: true) { inputs.files(project.sourceSets.main.allSource + project.sourceSets.main.compileClasspath) outputs.dir outputDir + ext.sourceCompatibility = project(":spring-core").compileJava.sourceCompatibility + ext.targetCompatibility = project(":spring-core").compileJava.targetCompatibility + doLast{ ant.taskdef(resource: "org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath) @@ -51,6 +54,9 @@ task compileTestJava(overwrite: true) { inputs.files(project.sourceSets.test.allSource + project.sourceSets.test.compileClasspath) outputs.dir outputDir + ext.sourceCompatibility = project(":spring-core").compileTestJava.sourceCompatibility + ext.targetCompatibility = project(":spring-core").compileTestJava.targetCompatibility + doLast{ ant.taskdef(resource: "org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath)
false
Other
spring-projects
spring-framework
68d4a70f8e7315d227b7727b087a65e64f4b0f9e.json
Add option to always append 'must-revalidate' Issue: SPR-9248
spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,9 @@ import org.springframework.util.StringUtils; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.HttpSessionRequiredException; +import org.springframework.web.context.request.WebRequest; import org.springframework.web.context.support.WebApplicationObjectSupport; +import org.springframework.web.servlet.mvc.LastModified; /** * Convenient superclass for any kind of web content generator, @@ -79,6 +81,8 @@ public abstract class WebContentGenerator extends WebApplicationObjectSupport { private int cacheSeconds = -1; + private boolean alwaysMustRevalidate = false; + /** * Create a new WebContentGenerator which supports @@ -194,6 +198,25 @@ public final boolean isUseCacheControlNoStore() { return this.useCacheControlNoStore; } + /** + * An option to add 'must-revalidate' to every Cache-Control header. This + * may be useful with annotated controller methods, which can + * programmatically do a lastModified calculation as described in + * {@link WebRequest#checkNotModified(long)}. Default is "false", + * effectively relying on whether the handler implements + * {@link LastModified} or not. + */ + public void setAlwaysMustRevalidate(boolean mustRevalidate) { + this.alwaysMustRevalidate = mustRevalidate; + } + + /** + * Return whether 'must-revaliate' is added to every Cache-Control header. + */ + public boolean isAlwaysMustRevalidate() { + return alwaysMustRevalidate; + } + /** * Cache content for the given number of seconds. Default is -1, * indicating no generation of cache-related headers. @@ -313,7 +336,7 @@ protected final void cacheForSeconds(HttpServletResponse response, int seconds, if (this.useCacheControlHeader) { // HTTP 1.1 header String headerValue = "max-age=" + seconds; - if (mustRevalidate) { + if (mustRevalidate || this.alwaysMustRevalidate) { headerValue += ", must-revalidate"; } response.setHeader(HEADER_CACHE_CONTROL, headerValue);
false
Other
spring-projects
spring-framework
0829cbfdd3adc4459e47b6c4e1411dba796f964a.json
Update license header for recently modified files Issue: SPR-7763, SPR-10140, SPR-10132, SPR-10093, SPR-10103
spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
true
Other
spring-projects
spring-framework
0829cbfdd3adc4459e47b6c4e1411dba796f964a.json
Update license header for recently modified files Issue: SPR-7763, SPR-10140, SPR-10132, SPR-10093, SPR-10103
spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
true
Other
spring-projects
spring-framework
0829cbfdd3adc4459e47b6c4e1411dba796f964a.json
Update license header for recently modified files Issue: SPR-7763, SPR-10140, SPR-10132, SPR-10093, SPR-10103
spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
true
Other
spring-projects
spring-framework
0829cbfdd3adc4459e47b6c4e1411dba796f964a.json
Update license header for recently modified files Issue: SPR-7763, SPR-10140, SPR-10132, SPR-10093, SPR-10103
spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 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.
true
Other
spring-projects
spring-framework
0829cbfdd3adc4459e47b6c4e1411dba796f964a.json
Update license header for recently modified files Issue: SPR-7763, SPR-10140, SPR-10132, SPR-10093, SPR-10103
spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
true
Other
spring-projects
spring-framework
0829cbfdd3adc4459e47b6c4e1411dba796f964a.json
Update license header for recently modified files Issue: SPR-7763, SPR-10140, SPR-10132, SPR-10093, SPR-10103
spring-web/src/test/java/org/springframework/http/converter/BufferedImageHttpMessageConverterTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
true
Other
spring-projects
spring-framework
0829cbfdd3adc4459e47b6c4e1411dba796f964a.json
Update license header for recently modified files Issue: SPR-7763, SPR-10140, SPR-10132, SPR-10093, SPR-10103
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
true
Other
spring-projects
spring-framework
0829cbfdd3adc4459e47b6c4e1411dba796f964a.json
Update license header for recently modified files Issue: SPR-7763, SPR-10140, SPR-10132, SPR-10093, SPR-10103
spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
true
Other
spring-projects
spring-framework
0829cbfdd3adc4459e47b6c4e1411dba796f964a.json
Update license header for recently modified files Issue: SPR-7763, SPR-10140, SPR-10132, SPR-10093, SPR-10103
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
true
Other
spring-projects
spring-framework
0829cbfdd3adc4459e47b6c4e1411dba796f964a.json
Update license header for recently modified files Issue: SPR-7763, SPR-10140, SPR-10132, SPR-10093, SPR-10103
spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.
true
Other
spring-projects
spring-framework
a56d8f28fe3c434d04d92ec6cd7ff60848cf8a2e.json
Add support for HTTP OPTIONS in Spring MVC Test Issue: SPR-10093
spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java
@@ -43,11 +43,12 @@ public abstract class MockMvcBuilderSupport { protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig, WebApplicationContext webAppContext, RequestBuilder defaultRequestBuilder, - List<ResultMatcher> globalResultMatchers, List<ResultHandler> globalResultHandlers) { + List<ResultMatcher> globalResultMatchers, List<ResultHandler> globalResultHandlers, Boolean dispatchOptions) { ServletContext servletContext = webAppContext.getServletContext(); TestDispatcherServlet dispatcherServlet = new TestDispatcherServlet(webAppContext); + dispatcherServlet.setDispatchOptionsRequest(dispatchOptions); try { dispatcherServlet.init(servletConfig); }
true
Other
spring-projects
spring-framework
a56d8f28fe3c434d04d92ec6cd7ff60848cf8a2e.json
Add support for HTTP OPTIONS in Spring MVC Test Issue: SPR-10093
spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java
@@ -80,6 +80,17 @@ public static MockHttpServletRequestBuilder delete(String urlTemplate, Object... return new MockHttpServletRequestBuilder(HttpMethod.DELETE, urlTemplate, urlVariables); } + /** + * Create a {@link MockHttpServletRequestBuilder} for an OPTIONS request. + * + * @param urlTemplate a URL template; the resulting URL will be encoded + * @param urlVariables zero or more URL variables + */ + public static MockHttpServletRequestBuilder options(String urlTemplate, Object... urlVariables) { + return new MockHttpServletRequestBuilder(HttpMethod.OPTIONS, urlTemplate, urlVariables); + } + + /** * Create a {@link MockHttpServletRequestBuilder} for a request with the given HTTP method. *
true
Other
spring-projects
spring-framework
a56d8f28fe3c434d04d92ec6cd7ff60848cf8a2e.json
Add support for HTTP OPTIONS in Spring MVC Test Issue: SPR-10093
spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java
@@ -31,6 +31,7 @@ import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.util.Assert; import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; /** * An concrete implementation of {@link MockMvcBuilder} with methods for @@ -53,6 +54,8 @@ private final List<ResultMatcher> globalResultMatchers = new ArrayList<ResultMatcher>(); private final List<ResultHandler> globalResultHandlers = new ArrayList<ResultHandler>(); + + private Boolean dispatchOptions = Boolean.FALSE; /** @@ -177,6 +180,17 @@ public final <T extends Self> T alwaysDo(ResultHandler resultHandler) { this.globalResultHandlers.add(resultHandler); return (T) this; } + + /** + * Should the {@link DispatcherServlet} dispatch OPTIONS request to controllers. + * @param dispatchOptions + * @see {@link DispatcherServlet#setDispatchOptionsRequest(boolean)} + */ + @SuppressWarnings("unchecked") + public final <T extends Self> T dispatchOptions(boolean dispatchOptions) { + this.dispatchOptions = dispatchOptions; + return (T) this; + } /** * Build a {@link MockMvc} instance. @@ -191,7 +205,7 @@ public final MockMvc build() { Filter[] filterArray = this.filters.toArray(new Filter[this.filters.size()]); return super.createMockMvc(filterArray, mockServletConfig, this.webAppContext, - this.defaultRequestBuilder, this.globalResultMatchers, this.globalResultHandlers); + this.defaultRequestBuilder, this.globalResultMatchers, this.globalResultHandlers,this.dispatchOptions); } /**
true
Other
spring-projects
spring-framework
a56d8f28fe3c434d04d92ec6cd7ff60848cf8a2e.json
Add support for HTTP OPTIONS in Spring MVC Test Issue: SPR-10093
spring-test-mvc/src/test/java/org/springframework/test/web/servlet/Spr10093Tests.java
@@ -0,0 +1,94 @@ +/* + * 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.test.web.servlet; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Controller; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +/** + * Tests for SPR-10093 (support for OPTIONS requests). + * @author Arnaud Cogoluègnes + */ +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration +public class Spr10093Tests { + + @Autowired + private WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = webAppContextSetup(this.wac).dispatchOptions(true).build(); + } + + @Test + public void test() throws Exception { + MyController controller = this.wac.getBean(MyController.class); + int initialCount = controller.counter.get(); + this.mockMvc.perform(options("/myUrl")).andExpect(status().isOk()); + + Assert.assertEquals(initialCount+1,controller.counter.get()); + } + + + @Configuration + @EnableWebMvc + static class WebConfig extends WebMvcConfigurerAdapter { + + @Bean + public MyController myController() { + return new MyController(); + } + } + + @Controller + private static class MyController { + + private AtomicInteger counter = new AtomicInteger(0); + + @RequestMapping(value="/myUrl",method=RequestMethod.OPTIONS) + @ResponseBody + public void handle() { + counter.incrementAndGet(); + } + } + + +}
true
Other
spring-projects
spring-framework
2ac4a8c5411f8642ac2c40503678e5d7a4b56dbf.json
Update mvc chapter on annotations and proxies Issue: SPR-10132
src/reference/docbook/mvc.xml
@@ -867,7 +867,10 @@ public class ClinicController { <interfacename>@Transactional</interfacename> methods). Usually you will introduce an interface for the controller in order to use JDK dynamic proxies. To make this work you must move the - <interfacename>@RequestMapping</interfacename> annotations to the + <interfacename>@RequestMapping</interfacename> annotations, as well as + any other type and method-level annotations (e.g. + <interfacename>@ModelAttribute</interfacename>, + <interfacename>@InitBinder</interfacename>) to the interface as well as the mapping mechanism can only "see" the interface exposed by the proxy. Alternatively, you could activate <code>proxy-target-class="true"</code> in the configuration for the @@ -876,6 +879,10 @@ public class ClinicController { that CGLIB-based subclass proxies should be used instead of interface-based JDK proxies. For more information on various proxying mechanisms see <xref linkend="aop-proxying" />.</para> + + <para>Note however that method argument annotations, e.g. + <interfacename>@RequestParam</interfacename>, must be present in + the method signatures of the controller class.</para> </tip> <section xml:id="mvc-ann-requestmapping-31-vs-30">
false
Other
spring-projects
spring-framework
b8f223c404db419927d4f9763d71e10ca38d37dd.json
Add 3.1 migration section to reference docs Address error raised when using component-scan against the unqualified "org" base package. Issue: SPR-9843
src/reference/docbook/index.xml
@@ -471,6 +471,9 @@ <xi:include href="classic-aop-spring.xml" xmlns:xi="http://www.w3.org/2001/XInclude" /> + <xi:include href="migration-3.1.xml" + xmlns:xi="http://www.w3.org/2001/XInclude" /> + <xi:include href="migration-3.2.xml" xmlns:xi="http://www.w3.org/2001/XInclude" />
true
Other
spring-projects
spring-framework
b8f223c404db419927d4f9763d71e10ca38d37dd.json
Add 3.1 migration section to reference docs Address error raised when using component-scan against the unqualified "org" base package. Issue: SPR-9843
src/reference/docbook/migration-3.1.xml
@@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="UTF-8"?> +<appendix xml:id="migration-3.1" + 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>Migrating to Spring Framework 3.1</title> + + <para>In this appendix we discuss what users will want to know when upgrading to + Spring Framework 3.1. For a general overview of features, please see + <xref linkend="new-in-3.1"/></para> + + <section xml:id="migration-3.1-component-scan"> + <title>Component scanning against the "org" base package</title> + <para>Spring Framework 3.1 introduces a number of <literal>@Configuration</literal> + classes such as <literal>org.springframework.cache.annotation.ProxyCachingConfiguration + </literal> and + <literal>org.springframework.scheduling.annotation.ProxyAsyncConfiguration</literal>. + Because <literal>@Configuration</literal> is ultimately meta-annotated with Spring's + <literal>@Component</literal> annotation, these classes will inadvertently be scanned + and processed by the container for any component-scanning directive against the + unqualified "org" package, e.g.: + <programlisting language="xml"> + &lt;context:component-scan base-package="org"/&gt;</programlisting> + Therefore, in order to avoid errors like the one reported in <link + xl:href="https://jira.springsource.org/browse/SPR-9843">SPR-9843</link>, + any such directives should be updated to at least one more level of qualification e.g.: + <programlisting language="xml"> + &lt;context:component-scan base-package="org.xyz"/&gt;</programlisting> + Alternatively, an <literal>exclude-filter</literal> may be used. See + <link linkend="beans-scanning-filters"><literal>context:component-scan</literal></link> + documentation for details.</para> + </section> +</appendix>
true
Other
spring-projects
spring-framework
b8f223c404db419927d4f9763d71e10ca38d37dd.json
Add 3.1 migration section to reference docs Address error raised when using component-scan against the unqualified "org" base package. Issue: SPR-9843
src/reference/docbook/new-in-3.1.xml
@@ -11,7 +11,8 @@ <para>This is a list of new features for Spring Framework 3.1. A number of features do not have dedicated reference documentation but do have complete Javadoc. In such - cases, fully-qualified class names are given.</para> + cases, fully-qualified class names are given. See also <xref linkend="migration-3.1"/> + </para> <section xml:id="new-in-3.1-cache-abstraction"> <title>Cache Abstraction</title>
true
Other
spring-projects
spring-framework
7bc9667913571d17c38f2c1854af9eebadffa832.json
Add support for placeholders in @RequestMapping @RequestMapping annotations now support ${...} placeholders. Issue: SPR-9935
spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java
@@ -266,6 +266,7 @@ * Ant-style path patterns are also supported (e.g. "/myPath/*.do"). * At the method level, relative paths (e.g. "edit.do") are supported * within the primary mapping expressed at the type level. + * Path mapping URIs may contain placeholders (e.g. "/${connect}") * <p>In a Portlet environment: the mapped portlet modes * (i.e. "EDIT", "VIEW", "HELP" or any custom modes). * <p><b>Supported at the type level as well as at the method level!</b>
true
Other
spring-projects
spring-framework
7bc9667913571d17c38f2c1854af9eebadffa832.json
Add support for placeholders in @RequestMapping @RequestMapping annotations now support ${...} placeholders. Issue: SPR-9935
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,9 +20,11 @@ import java.util.ArrayList; import java.util.List; +import org.springframework.context.EmbeddedValueResolverAware; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; +import org.springframework.util.StringValueResolver; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.condition.AbstractRequestCondition; @@ -46,7 +48,8 @@ * @author Rossen Stoyanchev * @since 3.1 */ -public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMapping { +public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMapping + implements EmbeddedValueResolverAware { private boolean useSuffixPatternMatch = true; @@ -58,6 +61,8 @@ public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi private final List<String> fileExtensions = new ArrayList<String>(); + private StringValueResolver embeddedValueResolver; + /** * Whether to use suffix pattern match (".*") when matching patterns to @@ -101,6 +106,11 @@ public void setUseTrailingSlashMatch(boolean useTrailingSlashMatch) { this.useTrailingSlashMatch = useTrailingSlashMatch; } + @Override + public void setEmbeddedValueResolver(StringValueResolver resolver) { + this.embeddedValueResolver = resolver; + } + /** * Set the {@link ContentNegotiationManager} to use to determine requested media types. * If not set, the default constructor is used. @@ -142,7 +152,7 @@ public ContentNegotiationManager getContentNegotiationManager() { * Return the file extensions to use for suffix pattern matching. */ public List<String> getFileExtensions() { - return fileExtensions; + return this.fileExtensions; } @Override @@ -227,8 +237,9 @@ protected RequestCondition<?> getCustomMethodCondition(Method method) { * Created a RequestMappingInfo from a RequestMapping annotation. */ private RequestMappingInfo createRequestMappingInfo(RequestMapping annotation, RequestCondition<?> customCondition) { + String[] patterns = resolveEmbeddedValuesInPatterns(annotation.value()); return new RequestMappingInfo( - new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), + new PatternsRequestCondition(patterns, getUrlPathHelper(), getPathMatcher(), this.useSuffixPatternMatch, this.useTrailingSlashMatch, this.fileExtensions), new RequestMethodsRequestCondition(annotation.method()), new ParamsRequestCondition(annotation.params()), @@ -238,4 +249,21 @@ private RequestMappingInfo createRequestMappingInfo(RequestMapping annotation, R customCondition); } + /** + * Resolve placeholder values in the given array of patterns. + * @return a new array with updated patterns + */ + protected String[] resolveEmbeddedValuesInPatterns(String[] patterns) { + if (this.embeddedValueResolver == null) { + return patterns; + } + else { + String[] resolvedPatterns = new String[patterns.length]; + for (int i=0; i < patterns.length; i++) { + resolvedPatterns[i] = this.embeddedValueResolver.resolveStringValue(patterns[i]); + } + return resolvedPatterns; + } + } + }
true
Other
spring-projects
spring-framework
7bc9667913571d17c38f2c1854af9eebadffa832.json
Add support for placeholders in @RequestMapping @RequestMapping annotations now support ${...} placeholders. Issue: SPR-9935
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import org.junit.Before; import org.junit.Test; import org.springframework.http.MediaType; +import org.springframework.util.StringValueResolver; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.accept.PathExtensionContentNegotiationStrategy; import org.springframework.web.context.support.StaticWebApplicationContext; @@ -78,4 +79,18 @@ public void useSuffixPatternMatch() { this.handlerMapping.useSuffixPatternMatch()); } + @Test + public void resolveEmbeddedValuesInPatterns() { + this.handlerMapping.setEmbeddedValueResolver(new StringValueResolver() { + public String resolveStringValue(String value) { + return "/${pattern}/bar".equals(value) ? "/foo/bar" : value; + } + }); + + String[] patterns = new String[] { "/foo", "/${pattern}/bar" }; + String[] result = this.handlerMapping.resolveEmbeddedValuesInPatterns(patterns); + + assertArrayEquals(new String[] { "/foo", "/foo/bar" }, result); + } + }
true
Other
spring-projects
spring-framework
7bc9667913571d17c38f2c1854af9eebadffa832.json
Add support for placeholders in @RequestMapping @RequestMapping annotations now support ${...} placeholders. Issue: SPR-9935
src/reference/docbook/mvc.xml
@@ -1073,6 +1073,18 @@ public class RelativePathUriTemplateController { <filename>/owners/*/pets/{petId}</filename>).</para> </section> + <section xml:id="mvc-ann-requestmapping-placeholders"> + <title>Patterns with Placeholders</title> + + <para>Patterns in <interfacename>@RequestMapping</interfacename> annotations + support ${...} placeholders against local properties and/or system properties + and environment variables. This may be useful in cases where the path a + controller is mapped to may need to be customized through configuration. + For more information on placeholders see the Javadoc for + <classname>PropertyPlaceholderConfigurer</classname>.</para> + + </section> + <section xml:id="mvc-ann-matrix-variables"> <title>Matrix Variables</title>
true
Other
spring-projects
spring-framework
dc6b2abe46bc3edfaaf7020d2c95427412bed74c.json
Verify scope support for 'lite' @Beans in the TCF Introduced AtBeanLiteModeScopeTests integration tests to verify proper scoping of beans created in 'lite' mode. Updated comments in TACCWithoutACTests to better reflect the runtime behavior for 'lite' @Bean methods. Issue: SPR-9401
spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AtBeanLiteModeScopeTests.java
@@ -0,0 +1,104 @@ +/* + * 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.test.context.junit4.spr9051; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Scope; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +/** + * Integration tests that verify proper scoping of beans created in + * <em>{@code @Bean} Lite Mode</em>. + * + * @author Sam Brannen + * @since 3.2 + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = AtBeanLiteModeScopeTests.LiteBeans.class) +public class AtBeanLiteModeScopeTests { + + /** + * This is intentionally <b>not</b> annotated with {@code @Configuration}. + */ + static class LiteBeans { + + @Bean + public LifecycleBean singleton() { + LifecycleBean bean = new LifecycleBean("singleton"); + assertFalse(bean.isInitialized()); + return bean; + } + + @Bean + @Scope("prototype") + public LifecycleBean prototype() { + LifecycleBean bean = new LifecycleBean("prototype"); + assertFalse(bean.isInitialized()); + return bean; + } + } + + + @Autowired + private ApplicationContext applicationContext; + + @Autowired + @Qualifier("singleton") + private LifecycleBean injectedSingletonBean; + + @Autowired + @Qualifier("prototype") + private LifecycleBean injectedPrototypeBean; + + + @Test + public void singletonLiteBean() { + assertNotNull(injectedSingletonBean); + assertTrue(injectedSingletonBean.isInitialized()); + + LifecycleBean retrievedSingletonBean = applicationContext.getBean("singleton", LifecycleBean.class); + assertNotNull(retrievedSingletonBean); + assertTrue(retrievedSingletonBean.isInitialized()); + + assertSame(injectedSingletonBean, retrievedSingletonBean); + } + + @Test + public void prototypeLiteBean() { + assertNotNull(injectedPrototypeBean); + assertTrue(injectedPrototypeBean.isInitialized()); + + LifecycleBean retrievedPrototypeBean = applicationContext.getBean("prototype", LifecycleBean.class); + assertNotNull(retrievedPrototypeBean); + assertTrue(retrievedPrototypeBean.isInitialized()); + + assertNotSame(injectedPrototypeBean, retrievedPrototypeBean); + } + +}
true
Other
spring-projects
spring-framework
dc6b2abe46bc3edfaaf7020d2c95427412bed74c.json
Verify scope support for 'lite' @Beans in the TCF Introduced AtBeanLiteModeScopeTests integration tests to verify proper scoping of beans created in 'lite' mode. Updated comments in TACCWithoutACTests to better reflect the runtime behavior for 'lite' @Bean methods. Issue: SPR-9401
spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassesWithoutAtConfigurationTests.java
@@ -73,21 +73,23 @@ public PlatformTransactionManager transactionManager() { /** * Since this method does not reside in a true {@code @Configuration class}, - * it acts as a factory method instead of a singleton bean. The result is - * that this method will be called at least twice: + * it acts as a factory method when invoked directly (e.g., from + * {@link #transactionManager()}) and as a singleton bean when retrieved + * through the application context (e.g., when injected into the test + * instance). The result is that this method will be called twice: * - * <ul> + * <ol> * <li>once <em>indirectly</em> by the {@link TransactionalTestExecutionListener} * when it retrieves the {@link PlatformTransactionManager} from the * application context</li> * <li>and again when the {@link DataSource} is injected into the test * instance in {@link AbstractTransactionalAnnotatedConfigClassTests#setDataSource(DataSource)}.</li> - *</ul> + *</ol> * * Consequently, the {@link JdbcTemplate} used by this test instance and * the {@link PlatformTransactionManager} used by the Spring TestContext * Framework will operate on two different {@code DataSource} instances, - * which is most certainly not the desired or intended behavior. + * which is almost certainly not the desired or intended behavior. */ @Bean public DataSource dataSource() {
true
Other
spring-projects
spring-framework
49966258f1230950e31f717750b67787742826aa.json
Polish doc for 'annotated class' support in TCF Revised the content in the @ContextConfiguration annotation section. Issue: SPR-9401
src/reference/docbook/testing.xml
@@ -453,11 +453,7 @@ located in the classpath; whereas, annotated classes are typically <interfacename>@Configuration</interfacename> classes. However, resource locations could also refer to files in the file system, - and annotated classes could be component classes, etc. See <link - linkend="testcontext-ctx-management-xml">Context configuration - with XML resources</link> and the Javadoc for - <interfacename>@ContextConfiguration</interfacename> for further - details.</para> + and annotated classes could be component classes, etc.</para> <programlisting language="java"><emphasis role="bold">@ContextConfiguration</emphasis>("/test-config.xml") public class XmlApplicationContextTests { @@ -493,7 +489,8 @@ public class CustomLoaderXmlApplicationContextTests { </note> <para>See <link linkend="testcontext-ctx-management">Context - management and caching</link> and Javadoc for examples and further + management and caching</link> and the Javadoc for + <interfacename>@ContextConfiguration</interfacename> for further details.</para> </listitem>
false
Other
spring-projects
spring-framework
f3bcb6e2e413d48355771de7164730beeed80dad.json
Update spring.schemas to reflect 3.2 schemas Commit 180c5b2ef6c16f66145a4250b597a093e566d922 introduced 3.2 versions of all spring-* schemas; this commit updates spring.schemas mapping files to include these new versions.
spring-aop/src/main/resources/META-INF/spring.schemas
@@ -2,4 +2,5 @@ http\://www.springframework.org/schema/aop/spring-aop-2.0.xsd=org/springframewor http\://www.springframework.org/schema/aop/spring-aop-2.5.xsd=org/springframework/aop/config/spring-aop-2.5.xsd http\://www.springframework.org/schema/aop/spring-aop-3.0.xsd=org/springframework/aop/config/spring-aop-3.0.xsd http\://www.springframework.org/schema/aop/spring-aop-3.1.xsd=org/springframework/aop/config/spring-aop-3.1.xsd -http\://www.springframework.org/schema/aop/spring-aop.xsd=org/springframework/aop/config/spring-aop-3.1.xsd +http\://www.springframework.org/schema/aop/spring-aop-3.2.xsd=org/springframework/aop/config/spring-aop-3.2.xsd +http\://www.springframework.org/schema/aop/spring-aop.xsd=org/springframework/aop/config/spring-aop-3.2.xsd
true
Other
spring-projects
spring-framework
f3bcb6e2e413d48355771de7164730beeed80dad.json
Update spring.schemas to reflect 3.2 schemas Commit 180c5b2ef6c16f66145a4250b597a093e566d922 introduced 3.2 versions of all spring-* schemas; this commit updates spring.schemas mapping files to include these new versions.
spring-beans/src/main/resources/META-INF/spring.schemas
@@ -2,14 +2,17 @@ http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springfram http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd -http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd +http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd +http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd -http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd +http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd +http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd -http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd +http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd +http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd
true
Other
spring-projects
spring-framework
f3bcb6e2e413d48355771de7164730beeed80dad.json
Update spring.schemas to reflect 3.2 schemas Commit 180c5b2ef6c16f66145a4250b597a093e566d922 introduced 3.2 versions of all spring-* schemas; this commit updates spring.schemas mapping files to include these new versions.
spring-context/src/main/resources/META-INF/spring.schemas
@@ -1,19 +1,24 @@ http\://www.springframework.org/schema/context/spring-context-2.5.xsd=org/springframework/context/config/spring-context-2.5.xsd http\://www.springframework.org/schema/context/spring-context-3.0.xsd=org/springframework/context/config/spring-context-3.0.xsd http\://www.springframework.org/schema/context/spring-context-3.1.xsd=org/springframework/context/config/spring-context-3.1.xsd -http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.1.xsd +http\://www.springframework.org/schema/context/spring-context-3.2.xsd=org/springframework/context/config/spring-context-3.2.xsd +http\://www.springframework.org/schema/context/spring-context.xsd=org/springframework/context/config/spring-context-3.2.xsd http\://www.springframework.org/schema/jee/spring-jee-2.0.xsd=org/springframework/ejb/config/spring-jee-2.0.xsd http\://www.springframework.org/schema/jee/spring-jee-2.5.xsd=org/springframework/ejb/config/spring-jee-2.5.xsd http\://www.springframework.org/schema/jee/spring-jee-3.0.xsd=org/springframework/ejb/config/spring-jee-3.0.xsd http\://www.springframework.org/schema/jee/spring-jee-3.1.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd -http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.1.xsd +http\://www.springframework.org/schema/jee/spring-jee-3.2.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd +http\://www.springframework.org/schema/jee/spring-jee.xsd=org/springframework/ejb/config/spring-jee-3.2.xsd http\://www.springframework.org/schema/lang/spring-lang-2.0.xsd=org/springframework/scripting/config/spring-lang-2.0.xsd http\://www.springframework.org/schema/lang/spring-lang-2.5.xsd=org/springframework/scripting/config/spring-lang-2.5.xsd http\://www.springframework.org/schema/lang/spring-lang-3.0.xsd=org/springframework/scripting/config/spring-lang-3.0.xsd http\://www.springframework.org/schema/lang/spring-lang-3.1.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd -http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.1.xsd +http\://www.springframework.org/schema/lang/spring-lang-3.2.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd +http\://www.springframework.org/schema/lang/spring-lang.xsd=org/springframework/scripting/config/spring-lang-3.2.xsd http\://www.springframework.org/schema/task/spring-task-3.0.xsd=org/springframework/scheduling/config/spring-task-3.0.xsd http\://www.springframework.org/schema/task/spring-task-3.1.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd -http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.1.xsd +http\://www.springframework.org/schema/task/spring-task-3.2.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd +http\://www.springframework.org/schema/task/spring-task.xsd=org/springframework/scheduling/config/spring-task-3.2.xsd http\://www.springframework.org/schema/cache/spring-cache-3.1.xsd=org/springframework/cache/config/spring-cache-3.1.xsd -http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.1.xsd +http\://www.springframework.org/schema/cache/spring-cache-3.2.xsd=org/springframework/cache/config/spring-cache-3.2.xsd +http\://www.springframework.org/schema/cache/spring-cache.xsd=org/springframework/cache/config/spring-cache-3.2.xsd
true
Other
spring-projects
spring-framework
f3bcb6e2e413d48355771de7164730beeed80dad.json
Update spring.schemas to reflect 3.2 schemas Commit 180c5b2ef6c16f66145a4250b597a093e566d922 introduced 3.2 versions of all spring-* schemas; this commit updates spring.schemas mapping files to include these new versions.
spring-jdbc/src/main/resources/META-INF/spring.schemas
@@ -1,3 +1,4 @@ http\://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd=org/springframework/jdbc/config/spring-jdbc-3.0.xsd http\://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd=org/springframework/jdbc/config/spring-jdbc-3.1.xsd -http\://www.springframework.org/schema/jdbc/spring-jdbc.xsd=org/springframework/jdbc/config/spring-jdbc-3.1.xsd +http\://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd=org/springframework/jdbc/config/spring-jdbc-3.2.xsd +http\://www.springframework.org/schema/jdbc/spring-jdbc.xsd=org/springframework/jdbc/config/spring-jdbc-3.2.xsd
true
Other
spring-projects
spring-framework
f3bcb6e2e413d48355771de7164730beeed80dad.json
Update spring.schemas to reflect 3.2 schemas Commit 180c5b2ef6c16f66145a4250b597a093e566d922 introduced 3.2 versions of all spring-* schemas; this commit updates spring.schemas mapping files to include these new versions.
spring-jms/src/main/resources/META-INF/spring.schemas
@@ -1,4 +1,5 @@ http\://www.springframework.org/schema/jms/spring-jms-2.5.xsd=org/springframework/jms/config/spring-jms-2.5.xsd http\://www.springframework.org/schema/jms/spring-jms-3.0.xsd=org/springframework/jms/config/spring-jms-3.0.xsd http\://www.springframework.org/schema/jms/spring-jms-3.1.xsd=org/springframework/jms/config/spring-jms-3.1.xsd -http\://www.springframework.org/schema/jms/spring-jms.xsd=org/springframework/jms/config/spring-jms-3.1.xsd +http\://www.springframework.org/schema/jms/spring-jms-3.2.xsd=org/springframework/jms/config/spring-jms-3.2.xsd +http\://www.springframework.org/schema/jms/spring-jms.xsd=org/springframework/jms/config/spring-jms-3.2.xsd
true
Other
spring-projects
spring-framework
f3bcb6e2e413d48355771de7164730beeed80dad.json
Update spring.schemas to reflect 3.2 schemas Commit 180c5b2ef6c16f66145a4250b597a093e566d922 introduced 3.2 versions of all spring-* schemas; this commit updates spring.schemas mapping files to include these new versions.
spring-oxm/src/main/resources/META-INF/spring.schemas
@@ -1,3 +1,4 @@ http\://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd=org/springframework/oxm/config/spring-oxm-3.0.xsd http\://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd=org/springframework/oxm/config/spring-oxm-3.1.xsd -http\://www.springframework.org/schema/oxm/spring-oxm.xsd=org/springframework/oxm/config/spring-oxm-3.1.xsd +http\://www.springframework.org/schema/oxm/spring-oxm-3.2.xsd=org/springframework/oxm/config/spring-oxm-3.2.xsd +http\://www.springframework.org/schema/oxm/spring-oxm.xsd=org/springframework/oxm/config/spring-oxm-3.2.xsd
true
Other
spring-projects
spring-framework
f3bcb6e2e413d48355771de7164730beeed80dad.json
Update spring.schemas to reflect 3.2 schemas Commit 180c5b2ef6c16f66145a4250b597a093e566d922 introduced 3.2 versions of all spring-* schemas; this commit updates spring.schemas mapping files to include these new versions.
spring-tx/src/main/resources/META-INF/spring.schemas
@@ -2,4 +2,5 @@ http\://www.springframework.org/schema/tx/spring-tx-2.0.xsd=org/springframework/ http\://www.springframework.org/schema/tx/spring-tx-2.5.xsd=org/springframework/transaction/config/spring-tx-2.5.xsd http\://www.springframework.org/schema/tx/spring-tx-3.0.xsd=org/springframework/transaction/config/spring-tx-3.0.xsd http\://www.springframework.org/schema/tx/spring-tx-3.1.xsd=org/springframework/transaction/config/spring-tx-3.1.xsd -http\://www.springframework.org/schema/tx/spring-tx.xsd=org/springframework/transaction/config/spring-tx-3.1.xsd +http\://www.springframework.org/schema/tx/spring-tx-3.2.xsd=org/springframework/transaction/config/spring-tx-3.2.xsd +http\://www.springframework.org/schema/tx/spring-tx.xsd=org/springframework/transaction/config/spring-tx-3.2.xsd
true
Other
spring-projects
spring-framework
f3bcb6e2e413d48355771de7164730beeed80dad.json
Update spring.schemas to reflect 3.2 schemas Commit 180c5b2ef6c16f66145a4250b597a093e566d922 introduced 3.2 versions of all spring-* schemas; this commit updates spring.schemas mapping files to include these new versions.
spring-webmvc/src/main/resources/META-INF/spring.schemas
@@ -1,3 +1,4 @@ http\://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd=org/springframework/web/servlet/config/spring-mvc-3.0.xsd http\://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd -http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.1.xsd +http\://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd +http\://www.springframework.org/schema/mvc/spring-mvc.xsd=org/springframework/web/servlet/config/spring-mvc-3.2.xsd
true
Other
spring-projects
spring-framework
77ae101402d07b4a59bc9e52b3fe045f1a0e2e7d.json
Add required flag to @RequestBody If true and there is no body => HttpMessageNotReadableException If false and there is no body, the argument resolves to null. Issue: SPR-9239
spring-web/src/main/java/org/springframework/web/bind/annotation/RequestBody.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. @@ -44,4 +44,12 @@ @Documented public @interface RequestBody { + /** + * Whether body content is required. + * <p>Default is <code>true</code>, leading to an exception thrown in case + * there is no body content. Switch this to <code>false</code> if you prefer + * <code>null</value> to be passed when the body content is <code>null</code>. + */ + boolean required() default true; + }
true
Other
spring-projects
spring-framework
77ae101402d07b4a59bc9e52b3fe045f1a0e2e7d.json
Add required flag to @RequestBody If true and there is no body => HttpMessageNotReadableException If false and there is no body, the argument resolves to null. Issue: SPR-9239
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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,9 +23,12 @@ import org.springframework.core.Conventions; import org.springframework.core.MethodParameter; import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.http.HttpInputMessage; import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.validation.BindingResult; import org.springframework.web.HttpMediaTypeNotAcceptableException; +import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.RequestBody; @@ -36,17 +39,17 @@ import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; /** - * Resolves method arguments annotated with {@code @RequestBody} and handles + * Resolves method arguments annotated with {@code @RequestBody} and handles * return values from methods annotated with {@code @ResponseBody} by reading - * and writing to the body of the request or response with an + * and writing to the body of the request or response with an * {@link HttpMessageConverter}. - * - * <p>An {@code @RequestBody} method argument is also validated if it is - * annotated with {@code @javax.validation.Valid}. In case of validation - * failure, {@link MethodArgumentNotValidException} is raised and results + * + * <p>An {@code @RequestBody} method argument is also validated if it is + * annotated with {@code @javax.validation.Valid}. In case of validation + * failure, {@link MethodArgumentNotValidException} is raised and results * in a 400 response status code if {@link DefaultHandlerExceptionResolver} - * is configured. - * + * is configured. + * * @author Arjen Poutsma * @author Rossen Stoyanchev * @since 3.1 @@ -65,24 +68,56 @@ public boolean supportsReturnType(MethodParameter returnType) { return returnType.getMethodAnnotation(ResponseBody.class) != null; } + /** + * {@inheritDoc} + * @throws MethodArgumentNotValidException if validation fails + * @throws HttpMessageNotReadableException if {@link RequestBody#required()} + * is {@code true} and there is no body content or if there is no suitable + * converter to read the content with. + */ public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { Object arg = readWithMessageConverters(webRequest, parameter, parameter.getParameterType()); + validate(parameter, webRequest, binderFactory, arg); + return arg; + } + + private void validate(MethodParameter parameter, NativeWebRequest webRequest, + WebDataBinderFactory binderFactory, Object arg) throws Exception, MethodArgumentNotValidException { + + if (arg == null) { + return; + } Annotation[] annotations = parameter.getParameterAnnotations(); for (Annotation annot : annotations) { - if (annot.annotationType().getSimpleName().startsWith("Valid")) { - String name = Conventions.getVariableNameForParameter(parameter); - WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name); - Object hints = AnnotationUtils.getValue(annot); - binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[] {hints}); - BindingResult bindingResult = binder.getBindingResult(); - if (bindingResult.hasErrors()) { - throw new MethodArgumentNotValidException(parameter, bindingResult); - } + if (!annot.annotationType().getSimpleName().startsWith("Valid")) { + continue; + } + String name = Conventions.getVariableNameForParameter(parameter); + WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name); + Object hints = AnnotationUtils.getValue(annot); + binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[] {hints}); + BindingResult bindingResult = binder.getBindingResult(); + if (bindingResult.hasErrors()) { + throw new MethodArgumentNotValidException(parameter, bindingResult); } } - return arg; + } + + @Override + protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, + MethodParameter methodParam, Class<T> paramType) throws IOException, HttpMediaTypeNotSupportedException { + + if (inputMessage.getBody() != null) { + return super.readWithMessageConverters(inputMessage, methodParam, paramType); + } + + RequestBody annot = methodParam.getParameterAnnotation(RequestBody.class); + if (!annot.required()) { + return null; + } + throw new HttpMessageNotReadableException("Required request body content is missing: " + methodParam.toString()); } public void handleReturnValue(Object returnValue, MethodParameter returnType,
true
Other
spring-projects
spring-framework
77ae101402d07b4a59bc9e52b3fe045f1a0e2e7d.json
Add required flag to @RequestBody If true and there is no body => HttpMessageNotReadableException If false and there is no body, the argument resolves to null. Issue: SPR-9239
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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. @@ -26,6 +26,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -47,6 +48,7 @@ import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.mock.web.MockHttpServletRequest; @@ -79,6 +81,7 @@ public class RequestResponseBodyMethodProcessorTests { private MethodParameter paramRequestBodyString; private MethodParameter paramInt; private MethodParameter paramValidBean; + private MethodParameter paramStringNotRequired; private MethodParameter returnTypeString; private MethodParameter returnTypeInt; private MethodParameter returnTypeStringProduces; @@ -108,6 +111,7 @@ public void setUp() throws Exception { returnTypeInt = new MethodParameter(getClass().getMethod("handle2"), -1); returnTypeStringProduces = new MethodParameter(getClass().getMethod("handle3"), -1); paramValidBean = new MethodParameter(getClass().getMethod("handle4", SimpleBean.class), 0); + paramStringNotRequired = new MethodParameter(getClass().getMethod("handle5", String.class), 0); mavContainer = new ModelAndViewContainer(); @@ -134,6 +138,8 @@ public void resolveArgument() throws Exception { servletRequest.addHeader("Content-Type", contentType.toString()); String body = "Foo"; + servletRequest.setContent(body.getBytes()); + expect(messageConverter.canRead(String.class, contentType)).andReturn(true); expect(messageConverter.read(eq(String.class), isA(HttpInputMessage.class))).andReturn(body); replay(messageConverter); @@ -165,6 +171,7 @@ public void resolveArgumentValid() throws Exception { private void testResolveArgumentWithValidation(SimpleBean simpleBean) throws IOException, Exception { MediaType contentType = MediaType.TEXT_PLAIN; servletRequest.addHeader("Content-Type", contentType.toString()); + servletRequest.setContent(new byte[] {}); @SuppressWarnings("unchecked") HttpMessageConverter<SimpleBean> beanConverter = createMock(HttpMessageConverter.class); @@ -183,6 +190,7 @@ private void testResolveArgumentWithValidation(SimpleBean simpleBean) throws IOE public void resolveArgumentNotReadable() throws Exception { MediaType contentType = MediaType.TEXT_PLAIN; servletRequest.addHeader("Content-Type", contentType.toString()); + servletRequest.setContent(new byte[] {}); expect(messageConverter.canRead(String.class, contentType)).andReturn(false); replay(messageConverter); @@ -194,10 +202,22 @@ public void resolveArgumentNotReadable() throws Exception { @Test(expected = HttpMediaTypeNotSupportedException.class) public void resolveArgumentNoContentType() throws Exception { + servletRequest.setContent(new byte[] {}); + processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); + fail("Expected exception"); + } + + @Test(expected = HttpMessageNotReadableException.class) + public void resolveArgumentRequiredNoContent() throws Exception { processor.resolveArgument(paramRequestBodyString, mavContainer, webRequest, null); fail("Expected exception"); } + @Test + public void resolveArgumentNotRequiredNoContent() throws Exception { + assertNull(processor.resolveArgument(paramStringNotRequired, mavContainer, webRequest, null)); + } + @Test public void handleReturnValue() throws Exception { MediaType accepted = MediaType.TEXT_PLAIN; @@ -310,6 +330,9 @@ public String handle3() { public void handle4(@Valid @RequestBody SimpleBean b) { } + public void handle5(@RequestBody(required=false) String s) { + } + private final class ValidatingBinderFactory implements WebDataBinderFactory { public WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName) throws Exception { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
true
Other
spring-projects
spring-framework
77ae101402d07b4a59bc9e52b3fe045f1a0e2e7d.json
Add required flag to @RequestBody If true and there is no body => HttpMessageNotReadableException If false and there is no body, the argument resolves to null. Issue: SPR-9239
src/dist/changelog.txt
@@ -28,6 +28,7 @@ Changes in version 3.2 M1 * add ability to configure custom MessageCodesResolver through the MVC Java config * add option in MappingJacksonJsonView for setting the Content-Length header * decode path variables when url decoding is turned off in AbstractHandlerMapping +* add required flag to @RequestBody annotation Changes in version 3.1.1 (2012-02-16) -------------------------------------
true
Other
spring-projects
spring-framework
59e3223c849fd04c1415f5ddd9bfb9acb9a17b60.json
Polish recent changes to Log4jWebConfigurer Reordered inline comments so that they now apply to current state of the code. Added logger entry in testlog4j.properties to avoid console warning. Issue: SPR-9417
spring-web/src/main/java/org/springframework/web/util/Log4jWebConfigurer.java
@@ -122,11 +122,14 @@ public static void initLogging(ServletContext servletContext) { if (location != null) { // Perform actual log4j initialization; else rely on log4j's default initialization. try { - // Return a URL (e.g. "classpath:" or "file:") as-is; - // consider a plain file path as relative to the web application root directory. + // Resolve system property placeholders before potentially + // resolving a real path. location = SystemPropertyUtils.resolvePlaceholders(location); + + // Leave a URL (e.g. "classpath:" or "file:") as-is. if (!ResourceUtils.isUrl(location)) { - // Resolve system property placeholders before resolving real path. + // Consider a plain file path as relative to the web + // application root directory. location = WebUtils.getRealPath(servletContext, location); }
true
Other
spring-projects
spring-framework
59e3223c849fd04c1415f5ddd9bfb9acb9a17b60.json
Polish recent changes to Log4jWebConfigurer Reordered inline comments so that they now apply to current state of the code. Added logger entry in testlog4j.properties to avoid console warning. Issue: SPR-9417
spring-web/src/test/resources/org/springframework/web/util/testlog4j.properties
@@ -1,2 +1,5 @@ log4j.rootCategory=DEBUG, mock -log4j.appender.mock=org.springframework.web.util.MockLog4jAppender \ No newline at end of file + +log4j.appender.mock=org.springframework.web.util.MockLog4jAppender + +log4j.logger.org.springframework.mock.web=WARN
true
Other
spring-projects
spring-framework
18006c72b014246946fd487159de7e133d173a17.json
Fix circular placeholder prevention A set of resolved placeholder references is used for circular placeholder prevention. For complex property definitions this mechanism would put property values with unresolved inner placeholder references in the set, but would try to remove property values with placeholders resolved, leaving the set in an invalid state and the mechanism broken. This fix makes sure that the value that is put in the set is same one that is removed from it, and by doing so avoids false positives in reporting circular placeholders. Issue: SPR-5369
spring-core/src/main/java/org/springframework/util/PropertyPlaceholderHelper.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. @@ -135,9 +135,10 @@ protected String parseStringValue( int endIndex = findPlaceholderEndIndex(buf, startIndex); if (endIndex != -1) { String placeholder = buf.substring(startIndex + this.placeholderPrefix.length(), endIndex); - if (!visitedPlaceholders.add(placeholder)) { + String originalPlaceholder = placeholder; + if (!visitedPlaceholders.add(originalPlaceholder)) { throw new IllegalArgumentException( - "Circular placeholder reference '" + placeholder + "' in property definitions"); + "Circular placeholder reference '" + originalPlaceholder + "' in property definitions"); } // Recursive invocation, parsing placeholders contained in the placeholder key. placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders); @@ -173,7 +174,7 @@ else if (this.ignoreUnresolvablePlaceholders) { throw new IllegalArgumentException("Could not resolve placeholder '" + placeholder + "'"); } - visitedPlaceholders.remove(placeholder); + visitedPlaceholders.remove(originalPlaceholder); } else { startIndex = -1;
true
Other
spring-projects
spring-framework
18006c72b014246946fd487159de7e133d173a17.json
Fix circular placeholder prevention A set of resolved placeholder references is used for circular placeholder prevention. For complex property definitions this mechanism would put property values with unresolved inner placeholder references in the set, but would try to remove property values with placeholders resolved, leaving the set in an invalid state and the mechanism broken. This fix makes sure that the value that is put in the set is same one that is removed from it, and by doing so avoids false positives in reporting circular placeholders. Issue: SPR-5369
spring-core/src/test/java/org/springframework/util/PropertyPlaceholderHelperTests.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. @@ -65,6 +65,15 @@ public void testRecurseInPlaceholder() { props.setProperty("inner", "ar"); assertEquals("foo=bar", this.helper.replacePlaceholders(text, props)); + + text = "${top}"; + props = new Properties(); + props.setProperty("top", "${child}+${child}"); + props.setProperty("child", "${${differentiator}.grandchild}"); + props.setProperty("differentiator", "first"); + props.setProperty("first.grandchild", "actualValue"); + + assertEquals("actualValue+actualValue", this.helper.replacePlaceholders(text, props)); } @Test
true
Other
spring-projects
spring-framework
13239a0c3d5bf226998f2da9eb66014118972a26.json
Fix compiler warnings This patch fixes several compiler warnings that do not point to code problems. Two kinds of warnings are fixed. First in a lot of cases @SuppressWarnings("unchecked") is used although there are no unchecked casts happening. This seems to be a leftover from when the code base was on Java 1.4, now that the code base was moved to Java 1.5 these are no longer necessary. Secondly there some places where the raw types of List and Class are used where there wildcard types (List<?> and Class<?>) would work just as well without causing any raw type warnings. These changes are beneficial particularly when working in Eclipse or other IDEs because it reduces 'noise', helping to isolate actual potential problems in the code. The following changes have been made: - remove @SuppressWarnings where no longer needed - use wildcard types instead of raw types where possible
spring-aop/src/main/java/org/springframework/aop/framework/ProxyFactory.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. @@ -93,7 +93,6 @@ public ProxyFactory(Class proxyInterface, TargetSource targetSource) { * (if necessary for proxy creation). * @return the proxy object */ - @SuppressWarnings("unchecked") public Object getProxy() { return createAopProxy().getProxy(); } @@ -107,7 +106,6 @@ public Object getProxy() { * (or <code>null</code> for the low-level proxy facility's default) * @return the proxy object */ - @SuppressWarnings("unchecked") public Object getProxy(ClassLoader classLoader) { return createAopProxy().getProxy(classLoader); }
true
Other
spring-projects
spring-framework
13239a0c3d5bf226998f2da9eb66014118972a26.json
Fix compiler warnings This patch fixes several compiler warnings that do not point to code problems. Two kinds of warnings are fixed. First in a lot of cases @SuppressWarnings("unchecked") is used although there are no unchecked casts happening. This seems to be a leftover from when the code base was on Java 1.4, now that the code base was moved to Java 1.5 these are no longer necessary. Secondly there some places where the raw types of List and Class are used where there wildcard types (List<?> and Class<?>) would work just as well without causing any raw type warnings. These changes are beneficial particularly when working in Eclipse or other IDEs because it reduces 'noise', helping to isolate actual potential problems in the code. The following changes have been made: - remove @SuppressWarnings where no longer needed - use wildcard types instead of raw types where possible
spring-beans/src/main/java/org/springframework/beans/factory/config/DestructionAwareAttributeHolder.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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. @@ -59,7 +59,6 @@ public Map<String, Object> getAttributeMap() { * the name of the attribute to be returned * @return the attribute value or <code>null</code> if not available */ - @SuppressWarnings("unchecked") public Object getAttribute(String name) { return attributes.get(name); } @@ -75,7 +74,6 @@ public Object getAttribute(String name) { * @return any previously object stored under the same name, if any, * <code>null</code> otherwise */ - @SuppressWarnings("unchecked") public Object setAttribute(String name, Object value) { return attributes.put(name, value); } @@ -101,7 +99,6 @@ public Object setAttribute(String name, Object value) { * @return the removed object, or <code>null</code> if no object was present * @see #registerDestructionCallback */ - @SuppressWarnings("unchecked") public Object removeAttribute(String name) { Object value = attributes.remove(name);
true
Other
spring-projects
spring-framework
13239a0c3d5bf226998f2da9eb66014118972a26.json
Fix compiler warnings This patch fixes several compiler warnings that do not point to code problems. Two kinds of warnings are fixed. First in a lot of cases @SuppressWarnings("unchecked") is used although there are no unchecked casts happening. This seems to be a leftover from when the code base was on Java 1.4, now that the code base was moved to Java 1.5 these are no longer necessary. Secondly there some places where the raw types of List and Class are used where there wildcard types (List<?> and Class<?>) would work just as well without causing any raw type warnings. These changes are beneficial particularly when working in Eclipse or other IDEs because it reduces 'noise', helping to isolate actual potential problems in the code. The following changes have been made: - remove @SuppressWarnings where no longer needed - use wildcard types instead of raw types where possible
spring-context-support/src/main/java/org/springframework/scheduling/quartz/JobDetailFactoryBean.java
@@ -168,7 +168,6 @@ public void setApplicationContextJobDataKey(String applicationContextJobDataKey) } - @SuppressWarnings("unchecked") public void afterPropertiesSet() { if (this.name == null) { this.name = this.beanName; @@ -196,7 +195,7 @@ public void afterPropertiesSet() { this.jobDetail = jdi; */ - Class jobDetailClass; + Class<?> jobDetailClass; try { jobDetailClass = getClass().getClassLoader().loadClass("org.quartz.impl.JobDetailImpl"); }
true
Other
spring-projects
spring-framework
13239a0c3d5bf226998f2da9eb66014118972a26.json
Fix compiler warnings This patch fixes several compiler warnings that do not point to code problems. Two kinds of warnings are fixed. First in a lot of cases @SuppressWarnings("unchecked") is used although there are no unchecked casts happening. This seems to be a leftover from when the code base was on Java 1.4, now that the code base was moved to Java 1.5 these are no longer necessary. Secondly there some places where the raw types of List and Class are used where there wildcard types (List<?> and Class<?>) would work just as well without causing any raw type warnings. These changes are beneficial particularly when working in Eclipse or other IDEs because it reduces 'noise', helping to isolate actual potential problems in the code. The following changes have been made: - remove @SuppressWarnings where no longer needed - use wildcard types instead of raw types where possible
spring-context/src/main/java/org/springframework/context/event/SourceFilteringListener.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. @@ -88,7 +88,6 @@ public int getOrder() { * <p>The default implementation invokes the specified delegate, if any. * @param event the event to process (matching the specified source) */ - @SuppressWarnings("unchecked") protected void onApplicationEventInternal(ApplicationEvent event) { if (this.delegate == null) { throw new IllegalStateException(
true
Other
spring-projects
spring-framework
13239a0c3d5bf226998f2da9eb66014118972a26.json
Fix compiler warnings This patch fixes several compiler warnings that do not point to code problems. Two kinds of warnings are fixed. First in a lot of cases @SuppressWarnings("unchecked") is used although there are no unchecked casts happening. This seems to be a leftover from when the code base was on Java 1.4, now that the code base was moved to Java 1.5 these are no longer necessary. Secondly there some places where the raw types of List and Class are used where there wildcard types (List<?> and Class<?>) would work just as well without causing any raw type warnings. These changes are beneficial particularly when working in Eclipse or other IDEs because it reduces 'noise', helping to isolate actual potential problems in the code. The following changes have been made: - remove @SuppressWarnings where no longer needed - use wildcard types instead of raw types where possible
spring-context/src/main/java/org/springframework/instrument/classloading/websphere/WebSphereClassLoaderAdapter.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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. @@ -91,12 +91,11 @@ public void addTransformer(ClassFileTransformer transformer) { } } - @SuppressWarnings("unchecked") public ClassLoader getThrowawayClassLoader() { try { ClassLoader loader = (ClassLoader) cloneConstructor.newInstance(getClassLoader()); // clear out the transformers (copied as well) - List list = (List) transformerList.get(loader); + List<?> list = (List<?>) transformerList.get(loader); list.clear(); return loader; }
true
Other
spring-projects
spring-framework
13239a0c3d5bf226998f2da9eb66014118972a26.json
Fix compiler warnings This patch fixes several compiler warnings that do not point to code problems. Two kinds of warnings are fixed. First in a lot of cases @SuppressWarnings("unchecked") is used although there are no unchecked casts happening. This seems to be a leftover from when the code base was on Java 1.4, now that the code base was moved to Java 1.5 these are no longer necessary. Secondly there some places where the raw types of List and Class are used where there wildcard types (List<?> and Class<?>) would work just as well without causing any raw type warnings. These changes are beneficial particularly when working in Eclipse or other IDEs because it reduces 'noise', helping to isolate actual potential problems in the code. The following changes have been made: - remove @SuppressWarnings where no longer needed - use wildcard types instead of raw types where possible
spring-context/src/test/java/org/springframework/context/support/TestProxyFactoryBean.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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. @@ -20,7 +20,7 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; -@SuppressWarnings({ "serial", "deprecation" }) +@SuppressWarnings("serial") public class TestProxyFactoryBean extends AbstractSingletonProxyFactoryBean implements BeanFactoryAware { @Override
true
Other
spring-projects
spring-framework
13239a0c3d5bf226998f2da9eb66014118972a26.json
Fix compiler warnings This patch fixes several compiler warnings that do not point to code problems. Two kinds of warnings are fixed. First in a lot of cases @SuppressWarnings("unchecked") is used although there are no unchecked casts happening. This seems to be a leftover from when the code base was on Java 1.4, now that the code base was moved to Java 1.5 these are no longer necessary. Secondly there some places where the raw types of List and Class are used where there wildcard types (List<?> and Class<?>) would work just as well without causing any raw type warnings. These changes are beneficial particularly when working in Eclipse or other IDEs because it reduces 'noise', helping to isolate actual potential problems in the code. The following changes have been made: - remove @SuppressWarnings where no longer needed - use wildcard types instead of raw types where possible
spring-core/src/main/java/org/springframework/core/LocalVariableTableParameterNameDiscoverer.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. @@ -77,7 +77,6 @@ public String[] getParameterNames(Method method) { return null; } - @SuppressWarnings("unchecked") public String[] getParameterNames(Constructor ctor) { Class<?> declaringClass = ctor.getDeclaringClass(); Map<Member, String[]> map = this.parameterNamesCache.get(declaringClass);
true
Other
spring-projects
spring-framework
13239a0c3d5bf226998f2da9eb66014118972a26.json
Fix compiler warnings This patch fixes several compiler warnings that do not point to code problems. Two kinds of warnings are fixed. First in a lot of cases @SuppressWarnings("unchecked") is used although there are no unchecked casts happening. This seems to be a leftover from when the code base was on Java 1.4, now that the code base was moved to Java 1.5 these are no longer necessary. Secondly there some places where the raw types of List and Class are used where there wildcard types (List<?> and Class<?>) would work just as well without causing any raw type warnings. These changes are beneficial particularly when working in Eclipse or other IDEs because it reduces 'noise', helping to isolate actual potential problems in the code. The following changes have been made: - remove @SuppressWarnings where no longer needed - use wildcard types instead of raw types where possible
spring-core/src/main/java/org/springframework/core/MethodParameter.java
@@ -281,7 +281,6 @@ public Annotation[] getMethodAnnotations() { * @param annotationType the annotation type to look for * @return the annotation object, or <code>null</code> if not found */ - @SuppressWarnings("unchecked") public <T extends Annotation> T getMethodAnnotation(Class<T> annotationType) { return getAnnotatedElement().getAnnotation(annotationType); }
true
Other
spring-projects
spring-framework
13239a0c3d5bf226998f2da9eb66014118972a26.json
Fix compiler warnings This patch fixes several compiler warnings that do not point to code problems. Two kinds of warnings are fixed. First in a lot of cases @SuppressWarnings("unchecked") is used although there are no unchecked casts happening. This seems to be a leftover from when the code base was on Java 1.4, now that the code base was moved to Java 1.5 these are no longer necessary. Secondly there some places where the raw types of List and Class are used where there wildcard types (List<?> and Class<?>) would work just as well without causing any raw type warnings. These changes are beneficial particularly when working in Eclipse or other IDEs because it reduces 'noise', helping to isolate actual potential problems in the code. The following changes have been made: - remove @SuppressWarnings where no longer needed - use wildcard types instead of raw types where possible
spring-jdbc/src/main/java/org/springframework/jdbc/core/ColumnMapRowMapper.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. @@ -67,7 +67,6 @@ public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException * @return the new Map instance * @see org.springframework.util.LinkedCaseInsensitiveMap */ - @SuppressWarnings("unchecked") protected Map<String, Object> createColumnMap(int columnCount) { return new LinkedCaseInsensitiveMap<Object>(columnCount); }
true
Other
spring-projects
spring-framework
13239a0c3d5bf226998f2da9eb66014118972a26.json
Fix compiler warnings This patch fixes several compiler warnings that do not point to code problems. Two kinds of warnings are fixed. First in a lot of cases @SuppressWarnings("unchecked") is used although there are no unchecked casts happening. This seems to be a leftover from when the code base was on Java 1.4, now that the code base was moved to Java 1.5 these are no longer necessary. Secondly there some places where the raw types of List and Class are used where there wildcard types (List<?> and Class<?>) would work just as well without causing any raw type warnings. These changes are beneficial particularly when working in Eclipse or other IDEs because it reduces 'noise', helping to isolate actual potential problems in the code. The following changes have been made: - remove @SuppressWarnings where no longer needed - use wildcard types instead of raw types where possible
spring-web/src/main/java/org/springframework/web/context/request/ServletRequestAttributes.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. @@ -159,7 +159,6 @@ public void removeAttribute(String name, int scope) { } } - @SuppressWarnings("unchecked") public String[] getAttributeNames(int scope) { if (scope == SCOPE_REQUEST) { if (!isRequestActive()) {
true
Other
spring-projects
spring-framework
13239a0c3d5bf226998f2da9eb66014118972a26.json
Fix compiler warnings This patch fixes several compiler warnings that do not point to code problems. Two kinds of warnings are fixed. First in a lot of cases @SuppressWarnings("unchecked") is used although there are no unchecked casts happening. This seems to be a leftover from when the code base was on Java 1.4, now that the code base was moved to Java 1.5 these are no longer necessary. Secondly there some places where the raw types of List and Class are used where there wildcard types (List<?> and Class<?>) would work just as well without causing any raw type warnings. These changes are beneficial particularly when working in Eclipse or other IDEs because it reduces 'noise', helping to isolate actual potential problems in the code. The following changes have been made: - remove @SuppressWarnings where no longer needed - use wildcard types instead of raw types where possible
spring-web/src/main/java/org/springframework/web/context/request/ServletWebRequest.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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. @@ -87,12 +87,10 @@ public Object getNativeResponse() { return getResponse(); } - @SuppressWarnings("unchecked") public <T> T getNativeRequest(Class<T> requiredType) { return WebUtils.getNativeRequest(getRequest(), requiredType); } - @SuppressWarnings("unchecked") public <T> T getNativeResponse(Class<T> requiredType) { return WebUtils.getNativeResponse(getResponse(), requiredType); } @@ -102,13 +100,11 @@ public String getHeader(String headerName) { return getRequest().getHeader(headerName); } - @SuppressWarnings("unchecked") public String[] getHeaderValues(String headerName) { String[] headerValues = StringUtils.toStringArray(getRequest().getHeaders(headerName)); return (!ObjectUtils.isEmpty(headerValues) ? headerValues : null); } - @SuppressWarnings("unchecked") public Iterator<String> getHeaderNames() { return CollectionUtils.toIterator(getRequest().getHeaderNames()); } @@ -121,12 +117,10 @@ public String[] getParameterValues(String paramName) { return getRequest().getParameterValues(paramName); } - @SuppressWarnings("unchecked") public Iterator<String> getParameterNames() { return CollectionUtils.toIterator(getRequest().getParameterNames()); } - @SuppressWarnings("unchecked") public Map<String, String[]> getParameterMap() { return getRequest().getParameterMap(); }
true
Other
spring-projects
spring-framework
de2d8082121d3c2187b5555eb1e3a77f7128ba25.json
Eliminate trailing whitespace in SpEL classes
spring-expression/src/main/java/org/springframework/expression/spel/ast/TypeReference.java
@@ -24,7 +24,7 @@ /** * Represents a reference to a type, for example "T(String)" or "T(com.somewhere.Foo)" - * + * * @author Andy Clement */ public class TypeReference extends SpelNodeImpl { @@ -79,5 +79,5 @@ public String toStringAST() { sb.append(")"); return sb.toString(); } - + }
true
Other
spring-projects
spring-framework
de2d8082121d3c2187b5555eb1e3a77f7128ba25.json
Eliminate trailing whitespace in SpEL classes
spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java
@@ -70,7 +70,7 @@ /** * Hand written SpEL parser. Instances are reusable but are not thread safe. - * + * * @author Andy Clement * @since 3.0 */ @@ -81,16 +81,16 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { // The token stream constructed from that expression string private List<Token> tokenStream; - + // length of a populated token stream private int tokenStreamLength; - + // Current location in the token stream when processing tokens private int tokenStreamPointer; - + // For rules that build nodes, they are stacked here for return private Stack<SpelNodeImpl> constructedNodes = new Stack<SpelNodeImpl>(); - + private SpelParserConfiguration configuration; @@ -118,17 +118,17 @@ protected SpelExpression doParseExpression(String expressionString, ParserContex throw new SpelParseException(peekToken().startpos,SpelMessage.MORE_INPUT,toString(nextToken())); } Assert.isTrue(constructedNodes.isEmpty()); - return new SpelExpression(expressionString, ast, configuration); + return new SpelExpression(expressionString, ast, configuration); } catch (InternalParseException ipe) { throw ipe.getCause(); } } - + // expression // : logicalOrExpression - // ( (ASSIGN^ logicalOrExpression) - // | (DEFAULT^ logicalOrExpression) + // ( (ASSIGN^ logicalOrExpression) + // | (DEFAULT^ logicalOrExpression) // | (QMARK^ expression COLON! expression) // | (ELVIS^ expression))?; private SpelNodeImpl eatExpression() { @@ -157,15 +157,15 @@ private SpelNodeImpl eatExpression() { expr = new NullLiteral(toPos(t.startpos-1,t.endpos-1)); } nextToken(); - SpelNodeImpl ifTrueExprValue = eatExpression(); + SpelNodeImpl ifTrueExprValue = eatExpression(); eatToken(TokenKind.COLON); - SpelNodeImpl ifFalseExprValue = eatExpression(); + SpelNodeImpl ifFalseExprValue = eatExpression(); return new Ternary(toPos(t),expr,ifTrueExprValue,ifFalseExprValue); } } return expr; } - + //logicalOrExpression : logicalAndExpression (OR^ logicalAndExpression)*; private SpelNodeImpl eatLogicalOrExpression() { SpelNodeImpl expr = eatLogicalAndExpression(); @@ -189,7 +189,7 @@ private SpelNodeImpl eatLogicalAndExpression() { } return expr; } - + // relationalExpression : sumExpression (relationalOperator^ sumExpression)?; private SpelNodeImpl eatRelationalExpression() { SpelNodeImpl expr = eatSumExpression(); @@ -227,10 +227,10 @@ private SpelNodeImpl eatRelationalExpression() { } return expr; } - + //sumExpression: productExpression ( (PLUS^ | MINUS^) productExpression)*; private SpelNodeImpl eatSumExpression() { - SpelNodeImpl expr = eatProductExpression(); + SpelNodeImpl expr = eatProductExpression(); while (peekToken(TokenKind.PLUS,TokenKind.MINUS)) { Token t = nextToken();//consume PLUS or MINUS SpelNodeImpl rhExpr = eatProductExpression(); @@ -244,7 +244,7 @@ private SpelNodeImpl eatSumExpression() { } return expr; } - + // productExpression: powerExpr ((STAR^ | DIV^| MOD^) powerExpr)* ; private SpelNodeImpl eatProductExpression() { SpelNodeImpl expr = eatPowerExpression(); @@ -263,7 +263,7 @@ private SpelNodeImpl eatProductExpression() { } return expr; } - + // powerExpr : unaryExpression (POWER^ unaryExpression)? ; private SpelNodeImpl eatPowerExpression() { SpelNodeImpl expr = eatUnaryExpression(); @@ -293,7 +293,7 @@ private SpelNodeImpl eatUnaryExpression() { return eatPrimaryExpression(); } } - + // primaryExpression : startNode (node)? -> ^(EXPRESSION startNode (node)?); private SpelNodeImpl eatPrimaryExpression() { List<SpelNodeImpl> nodes = new ArrayList<SpelNodeImpl>(); @@ -308,7 +308,7 @@ private SpelNodeImpl eatPrimaryExpression() { return new CompoundExpression(toPos(start.getStartPosition(),nodes.get(nodes.size()-1).getEndPosition()),nodes.toArray(new SpelNodeImpl[nodes.size()])); } } - + // node : ((DOT dottedNode) | (SAFE_NAVI dottedNode) | nonDottedNode)+; private boolean maybeEatNode() { SpelNodeImpl expr = null; @@ -324,7 +324,7 @@ private boolean maybeEatNode() { return true; } } - + // nonDottedNode: indexer; private SpelNodeImpl maybeEatNonDottedNode() { if (peekToken(TokenKind.LSQUARE)) { @@ -334,14 +334,14 @@ private SpelNodeImpl maybeEatNonDottedNode() { } return null; } - + //dottedNode // : ((methodOrProperty // | functionOrVar - // | projection - // | selection - // | firstSelection - // | lastSelection + // | projection + // | selection + // | firstSelection + // | lastSelection // )) // ; private SpelNodeImpl eatDottedNode() { @@ -351,20 +351,20 @@ private SpelNodeImpl eatDottedNode() { return pop(); } if (peekToken()==null) { - // unexpectedly ran out of data + // unexpectedly ran out of data raiseInternalException(t.startpos,SpelMessage.OOD); } else { raiseInternalException(t.startpos,SpelMessage.UNEXPECTED_DATA_AFTER_DOT,toString(peekToken())); } return null; } - - // functionOrVar + + // functionOrVar // : (POUND ID LPAREN) => function // | var - // - // function : POUND id=ID methodArgs -> ^(FUNCTIONREF[$id] methodArgs); - // var : POUND id=ID -> ^(VARIABLEREF[$id]); + // + // function : POUND id=ID methodArgs -> ^(FUNCTIONREF[$id] methodArgs); + // var : POUND id=ID -> ^(VARIABLEREF[$id]); private boolean maybeEatFunctionOrVar() { if (!peekToken(TokenKind.HASH)) { return false; @@ -380,7 +380,7 @@ private boolean maybeEatFunctionOrVar() { return true; } } - + // methodArgs : LPAREN! (argument (COMMA! argument)* (COMMA!)?)? RPAREN!; private SpelNodeImpl[] maybeEatMethodArgs() { if (!peekToken(TokenKind.LPAREN)) { @@ -391,15 +391,15 @@ private SpelNodeImpl[] maybeEatMethodArgs() { eatToken(TokenKind.RPAREN); return args.toArray(new SpelNodeImpl[args.size()]); } - + private void eatConstructorArgs(List<SpelNodeImpl> accumulatedArguments) { if (!peekToken(TokenKind.LPAREN)) { throw new InternalParseException(new SpelParseException(expressionString,positionOf(peekToken()),SpelMessage.MISSING_CONSTRUCTOR_ARGS)); } consumeArguments(accumulatedArguments); eatToken(TokenKind.RPAREN); } - + /** * Used for consuming arguments for either a method or a constructor call */ @@ -421,25 +421,25 @@ private void consumeArguments(List<SpelNodeImpl> accumulatedArguments) { raiseInternalException(pos,SpelMessage.RUN_OUT_OF_ARGUMENTS); } } - + private int positionOf(Token t) { if (t==null) { - // if null assume the problem is because the right token was + // if null assume the problem is because the right token was // not found at the end of the expression return expressionString.length(); } else { return t.startpos; } } - - //startNode + + //startNode // : parenExpr | literal // | type - // | methodOrProperty + // | methodOrProperty // | functionOrVar - // | projection - // | selection + // | projection + // | selection // | firstSelection // | lastSelection // | indexer @@ -461,7 +461,7 @@ private SpelNodeImpl eatStartNode() { return null; } } - + // parse: @beanname @'bean.name' // quoted if dotted private boolean maybeEatBeanReference() { @@ -479,7 +479,7 @@ private boolean maybeEatBeanReference() { } else { raiseInternalException(beanRefToken.startpos,SpelMessage.INVALID_BEAN_REFERENCE); } - + BeanReference beanReference = new BeanReference(toPos(beanNameToken),beanname); constructedNodes.push(beanReference); return true; @@ -534,7 +534,7 @@ private boolean maybeEatProjection(boolean nullSafeNavigation) { constructedNodes.push(new Projection(nullSafeNavigation, toPos(t), expr)); return true; } - + // list = LCURLY (element (COMMA element)*) RCURLY private boolean maybeEatInlineList() { Token t = peekToken(); @@ -550,14 +550,14 @@ private boolean maybeEatInlineList() { List<SpelNodeImpl> listElements = new ArrayList<SpelNodeImpl>(); do { listElements.add(eatExpression()); - } while (peekToken(TokenKind.COMMA,true)); + } while (peekToken(TokenKind.COMMA,true)); closingCurly = eatToken(TokenKind.RCURLY); expr = new InlineList(toPos(t.startpos,closingCurly.endpos),listElements.toArray(new SpelNodeImpl[listElements.size()])); } constructedNodes.push(expr); return true; } - + private boolean maybeEatIndexer() { Token t = peekToken(); if (!peekToken(TokenKind.LSQUARE,true)) { @@ -568,7 +568,7 @@ private boolean maybeEatIndexer() { constructedNodes.push(new Indexer(toPos(t),expr)); return true; } - + private boolean maybeEatSelection(boolean nullSafeNavigation) { Token t = peekToken(); if (!peekSelectToken()) { @@ -577,7 +577,7 @@ private boolean maybeEatSelection(boolean nullSafeNavigation) { nextToken(); SpelNodeImpl expr = eatExpression(); eatToken(TokenKind.RSQUARE); - if (t.kind==TokenKind.SELECT_FIRST) { + if (t.kind==TokenKind.SELECT_FIRST) { constructedNodes.push(new Selection(nullSafeNavigation,Selection.FIRST,toPos(t),expr)); } else if (t.kind==TokenKind.SELECT_LAST) { constructedNodes.push(new Selection(nullSafeNavigation,Selection.LAST,toPos(t),expr)); @@ -597,11 +597,11 @@ private SpelNodeImpl eatPossiblyQualifiedId() { qualifiedIdPieces.add(new Identifier(startnode.stringValue(),toPos(startnode))); while (peekToken(TokenKind.DOT,true)) { Token node = eatToken(TokenKind.IDENTIFIER); - qualifiedIdPieces.add(new Identifier(node.stringValue(),toPos(node))); + qualifiedIdPieces.add(new Identifier(node.stringValue(),toPos(node))); } return new QualifiedIdentifier(toPos(startnode.startpos,qualifiedIdPieces.get(qualifiedIdPieces.size()-1).getEndPosition()),qualifiedIdPieces.toArray(new SpelNodeImpl[qualifiedIdPieces.size()])); } - + // This is complicated due to the support for dollars in identifiers. Dollars are normally separate tokens but // there we want to combine a series of identifiers and dollars into a single identifier private boolean maybeEatMethodOrProperty(boolean nullSafeNavigation) { @@ -622,8 +622,8 @@ private boolean maybeEatMethodOrProperty(boolean nullSafeNavigation) { return false; } - - //constructor + + //constructor //: ('new' qualifiedId LPAREN) => 'new' qualifiedId ctorArgs -> ^(CONSTRUCTOR qualifiedId ctorArgs) private boolean maybeEatConstructorReference() { if (peekIdentifierToken("new")) { @@ -665,12 +665,12 @@ private void push(SpelNodeImpl newNode) { private SpelNodeImpl pop() { return constructedNodes.pop(); } - - // literal - // : INTEGER_LITERAL + + // literal + // : INTEGER_LITERAL // | boolLiteral - // | STRING_LITERAL - // | HEXADECIMAL_INTEGER_LITERAL + // | STRING_LITERAL + // | HEXADECIMAL_INTEGER_LITERAL // | REAL_LITERAL // | DQ_STRING_LITERAL // | NULL_LITERAL @@ -691,14 +691,14 @@ private boolean maybeEatLiteral() { push(Literal.getRealLiteral(t.data, toPos(t),false)); } else if (t.kind==TokenKind.LITERAL_REAL_FLOAT) { push(Literal.getRealLiteral(t.data, toPos(t), true)); - } else if (peekIdentifierToken("true")) { + } else if (peekIdentifierToken("true")) { push(new BooleanLiteral(t.data,toPos(t),true)); } else if (peekIdentifierToken("false")) { push(new BooleanLiteral(t.data,toPos(t),false)); } else if (t.kind==TokenKind.LITERAL_STRING) { push(new StringLiteral(t.data,toPos(t),t.data)); } else { - return false; + return false; } nextToken(); return true; @@ -719,11 +719,11 @@ private boolean maybeEatParenExpression() { // relationalOperator // : EQUAL | NOT_EQUAL | LESS_THAN | LESS_THAN_OR_EQUAL | GREATER_THAN - // | GREATER_THAN_OR_EQUAL | INSTANCEOF | BETWEEN | MATCHES + // | GREATER_THAN_OR_EQUAL | INSTANCEOF | BETWEEN | MATCHES private Token maybeEatRelationalOperator() { Token t = peekToken(); if (t==null) { - return null; + return null; } if (t.isNumericRelationalOperator()) { return t; @@ -736,7 +736,7 @@ private Token maybeEatRelationalOperator() { return t.asMatchesToken(); } else if (idString.equalsIgnoreCase("between")) { return t.asBetweenToken(); - } + } } return null; } @@ -746,7 +746,7 @@ private Token eatToken(TokenKind expectedKind) { if (t==null) { raiseInternalException( expressionString.length(), SpelMessage.OOD); } - if (t.kind!=expectedKind) { + if (t.kind!=expectedKind) { raiseInternalException(t.startpos,SpelMessage.NOT_EXPECTED_TOKEN, expectedKind.toString().toLowerCase(),t.getKind().toString().toLowerCase()); } return t; @@ -798,18 +798,18 @@ private boolean peekIdentifierToken(String identifierString) { Token t = peekToken(); return t.kind==TokenKind.IDENTIFIER && t.stringValue().equalsIgnoreCase(identifierString); } - + private boolean peekSelectToken() { if (!moreTokens()) return false; Token t = peekToken(); return t.kind==TokenKind.SELECT || t.kind==TokenKind.SELECT_FIRST || t.kind==TokenKind.SELECT_LAST; } - - + + private boolean moreTokens() { return tokenStreamPointer<tokenStream.size(); } - + private Token nextToken() { if (tokenStreamPointer>=tokenStreamLength) { return null; @@ -825,17 +825,17 @@ private Token peekToken() { } private void raiseInternalException(int pos, SpelMessage message,Object... inserts) { - throw new InternalParseException(new SpelParseException(expressionString,pos,message,inserts)); + throw new InternalParseException(new SpelParseException(expressionString,pos,message,inserts)); } - + public String toString(Token t) { if (t.getKind().hasPayload()) { return t.stringValue(); } else { return t.kind.toString().toLowerCase(); } } - + private void checkRightOperand(Token token, SpelNodeImpl operandExpression) { if (operandExpression==null) { raiseInternalException(token.startpos,SpelMessage.RIGHT_OPERAND_PROBLEM); @@ -852,5 +852,5 @@ private int toPos(Token t) { private int toPos(int start,int end) { return (start<<16)+end; } - + }
true
Other
spring-projects
spring-framework
1f4b33c4ad72c0760bfc40867ce09a859c02f7aa.json
Fix compiler warnings in Constants/ConstantsTests
spring-core/src/main/java/org/springframework/core/Constants.java
@@ -58,7 +58,7 @@ public class Constants { * @param clazz the class to analyze * @throws IllegalArgumentException if the supplied <code>clazz</code> is <code>null</code> */ - public Constants(Class clazz) { + public Constants(Class<?> clazz) { Assert.notNull(clazz); this.className = clazz.getName(); Field[] fields = clazz.getFields(); @@ -189,7 +189,7 @@ public Set<String> getNamesForProperty(String propertyName) { * @param nameSuffix suffix of the constant names to search (may be <code>null</code>) * @return the set of constant names */ - public Set getNamesForSuffix(String nameSuffix) { + public Set<String> getNamesForSuffix(String nameSuffix) { String suffixToUse = (nameSuffix != null ? nameSuffix.trim().toUpperCase(Locale.ENGLISH) : ""); Set<String> names = new HashSet<String>(); for (String code : this.fieldCache.keySet()) {
true
Other
spring-projects
spring-framework
1f4b33c4ad72c0760bfc40867ce09a859c02f7aa.json
Fix compiler warnings in Constants/ConstantsTests
spring-core/src/test/java/org/springframework/core/ConstantsTests.java
@@ -57,7 +57,7 @@ public void testConstants() { public void testGetNames() { Constants c = new Constants(A.class); - Set names = c.getNames(""); + Set<?> names = c.getNames(""); assertEquals(c.getSize(), names.size()); assertTrue(names.contains("DOG")); assertTrue(names.contains("CAT")); @@ -75,7 +75,7 @@ public void testGetNames() { public void testGetValues() { Constants c = new Constants(A.class); - Set values = c.getValues(""); + Set<?> values = c.getValues(""); assertEquals(7, values.size()); assertTrue(values.contains(new Integer(0))); assertTrue(values.contains(new Integer(66))); @@ -102,7 +102,7 @@ public void testGetValuesInTurkey() { try { Constants c = new Constants(A.class); - Set values = c.getValues(""); + Set<?> values = c.getValues(""); assertEquals(7, values.size()); assertTrue(values.contains(new Integer(0))); assertTrue(values.contains(new Integer(66))); @@ -130,12 +130,12 @@ public void testGetValuesInTurkey() { public void testSuffixAccess() { Constants c = new Constants(A.class); - Set names = c.getNamesForSuffix("_PROPERTY"); + Set<?> names = c.getNamesForSuffix("_PROPERTY"); assertEquals(2, names.size()); assertTrue(names.contains("NO_PROPERTY")); assertTrue(names.contains("YES_PROPERTY")); - Set values = c.getValuesForSuffix("_PROPERTY"); + Set<?> values = c.getValuesForSuffix("_PROPERTY"); assertEquals(2, values.size()); assertTrue(values.contains(new Integer(3))); assertTrue(values.contains(new Integer(4))); @@ -210,26 +210,26 @@ public void testToCode() { public void testGetValuesWithNullPrefix() throws Exception { Constants c = new Constants(A.class); - Set values = c.getValues(null); + Set<?> values = c.getValues(null); assertEquals("Must have returned *all* public static final values", 7, values.size()); } public void testGetValuesWithEmptyStringPrefix() throws Exception { Constants c = new Constants(A.class); - Set values = c.getValues(""); + Set<Object> values = c.getValues(""); assertEquals("Must have returned *all* public static final values", 7, values.size()); } public void testGetValuesWithWhitespacedStringPrefix() throws Exception { Constants c = new Constants(A.class); - Set values = c.getValues(" "); + Set<?> values = c.getValues(" "); assertEquals("Must have returned *all* public static final values", 7, values.size()); } public void testWithClassThatExposesNoConstants() throws Exception { Constants c = new Constants(NoConstants.class); assertEquals(0, c.getSize()); - final Set values = c.getValues(""); + final Set<?> values = c.getValues(""); assertNotNull(values); assertEquals(0, values.size()); } @@ -245,10 +245,11 @@ public void testCtorWithNullClass() throws Exception { private static final class NoConstants { } - + + @SuppressWarnings("unused") private static final class A { - + public static final int DOG = 0; public static final int CAT = 66; public static final String S1 = "";
true
Other
spring-projects
spring-framework
1f28bdfbfa7f6f7025dac18bd5cdf4fdefb32950.json
Fix SpEL JavaBean compliance Before this fix ReflectivePropertyAccessor was not able to find write method for valid property name that has first character in lower case and second character in upper case. Write method lookup would always convert first character of property name to upper case which is not compliant with JavaBean specification. As consequence this caused an unwanted behavior in SpEL when obtaining values of expressions that reference such JavaBean properties. As of this change, write method lookup skips conversion of property name first character to upper case when property name is longer than one character and second character is in upper case. This also fixes mentioned bug in SpEL value resolution. Issue: SPR-9123
spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java
@@ -282,21 +282,27 @@ else if (canWrite(context, target, name)) { } /** - * Find a getter method for the specified property. A getter is defined as a method whose name start with the prefix - * 'get' and the rest of the name is the same as the property name (with the first character uppercased). + * Find a getter method for the specified property. */ protected Method findGetterForProperty(String propertyName, Class<?> clazz, boolean mustBeStatic) { Method[] ms = clazz.getMethods(); + String propertyWriteMethodSuffix; + if (propertyName.length() > 1 && Character.isUpperCase(propertyName.charAt(1))) { + propertyWriteMethodSuffix = propertyName; + } + else { + propertyWriteMethodSuffix = StringUtils.capitalize(propertyName); + } // Try "get*" method... - String getterName = "get" + StringUtils.capitalize(propertyName); + String getterName = "get" + propertyWriteMethodSuffix; for (Method method : ms) { if (method.getName().equals(getterName) && method.getParameterTypes().length == 0 && (!mustBeStatic || Modifier.isStatic(method.getModifiers()))) { return method; } } // Try "is*" method... - getterName = "is" + StringUtils.capitalize(propertyName); + getterName = "is" + propertyWriteMethodSuffix; for (Method method : ms) { if (method.getName().equals(getterName) && method.getParameterTypes().length == 0 && boolean.class.equals(method.getReturnType()) &&
true
Other
spring-projects
spring-framework
1f28bdfbfa7f6f7025dac18bd5cdf4fdefb32950.json
Fix SpEL JavaBean compliance Before this fix ReflectivePropertyAccessor was not able to find write method for valid property name that has first character in lower case and second character in upper case. Write method lookup would always convert first character of property name to upper case which is not compliant with JavaBean specification. As consequence this caused an unwanted behavior in SpEL when obtaining values of expressions that reference such JavaBean properties. As of this change, write method lookup skips conversion of property name first character to upper case when property name is longer than one character and second character is in upper case. This also fixes mentioned bug in SpEL value resolution. Issue: SPR-9123
spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java
@@ -318,7 +318,17 @@ public void testReflectivePropertyResolver() throws Exception { // Assert.assertEquals(0,rpr.read(ctx,t,"field3").getValue()); Assert.assertEquals(false,rpr.read(ctx,t,"property4").getValue()); Assert.assertTrue(rpr.canRead(ctx,t,"property4")); - + + // repro SPR-9123, ReflectivePropertyAccessor JavaBean property names compliance tests + Assert.assertEquals("iD",rpr.read(ctx,t,"iD").getValue()); + Assert.assertTrue(rpr.canRead(ctx,t,"iD")); + Assert.assertEquals("id",rpr.read(ctx,t,"id").getValue()); + Assert.assertTrue(rpr.canRead(ctx,t,"id")); + Assert.assertEquals("ID",rpr.read(ctx,t,"ID").getValue()); + Assert.assertTrue(rpr.canRead(ctx,t,"ID")); + // note: "Id" is not a valid JavaBean name, nevertheless it is treated as "id" + Assert.assertEquals("id",rpr.read(ctx,t,"Id").getValue()); + Assert.assertTrue(rpr.canRead(ctx,t,"Id")); } @Test @@ -406,6 +416,9 @@ static class Tester { String property2; String property3 = "doodoo"; boolean property4 = false; + String iD = "iD"; + String id = "id"; + String ID = "ID"; public String getProperty() { return property; } public void setProperty(String value) { property = value; } @@ -415,6 +428,12 @@ static class Tester { public String getProperty3() { return property3; } public boolean isProperty4() { return property4; } + + public String getiD() { return iD; } + + public String getId() { return id; } + + public String getID() { return ID; } } static class Super {
true
Other
spring-projects
spring-framework
e8f8559a2e1c5fa5c559f887756cdc085c90f26b.json
Improve documentation of @Bean 'lite' mode Removed misleading mention of "configuration classes" in the "@Bean Lite Mode" section. Issue: SPR-9401
spring-context/src/main/java/org/springframework/context/annotation/Bean.java
@@ -103,16 +103,15 @@ * <p>{@code @Bean} methods may also be declared within classes that are <em>not</em> * annotated with {@code @Configuration}. For example, bean methods may be declared * in a {@code @Component} class or even in a <em>plain old class</em>. In such cases, - * a {@code @Bean} method will get processed in a configuration class <em>'lite'</em> - * mode. - * - * <p>In contrast to bean methods in {@code @Configuration} classes as described - * above, bean methods in <em>lite</em> mode will be called as plain <em>factory - * methods</em> from the container (similar to {@code factory-method} declarations - * in XML) but with <b><em>prototype</em></b> semantics. The containing class remains - * unmodified in this case, and there are no unusual constraints for factory methods; - * however, scoping semantics are <b>not</b> respected as described above for - * 'inter-bean method invocations in this mode. For example: + * a {@code @Bean} method will get processed in a so-called <em>'lite'</em> mode. + * + * <p>In contrast to the semantics for bean methods in {@code @Configuration} classes + * as described above, bean methods in <em>lite</em> mode will be called as plain + * <em>factory methods</em> from the container (similar to {@code factory-method} + * declarations in XML) but with <b><em>prototype</em></b> semantics. The containing + * class remains unmodified in this case, and there are no unusual constraints for + * factory methods; however, scoping semantics are <b>not</b> respected as described + * above for 'inter-bean method' invocations in this mode. For example: * * <pre class="code"> * &#064;Component
false
Other
spring-projects
spring-framework
94c9f96449960a94e49edd7709d49b243de4a5f1.json
Improve documentation of @Bean 'lite' mode Updated the class-level JavaDoc for @Bean to better explain the semantics of 'lite' mode. Renamed "Configuration Class Lite Mode" to "@Bean Lite Mode". Added discussion of @DependsOn to the class-level JavaDoc. Issue: SPR-9401
spring-context/src/main/java/org/springframework/context/annotation/Bean.java
@@ -28,6 +28,8 @@ /** * Indicates that a method produces a bean to be managed by the Spring container. * + * <h3>Overview</h3> + * * <p>The names and semantics of the attributes to this annotation are intentionally * similar to those of the {@code <bean/>} element in the Spring XML schema. For * example: @@ -55,12 +57,12 @@ * return obj; * }</pre> * - * <h3>Scope, Primary, and Lazy</h3> + * <h3>Scope, DependsOn, Primary, and Lazy</h3> * * <p>Note that the {@code @Bean} annotation does not provide attributes for scope, - * primary, or lazy. Rather, it should be used in conjunction with {@link Scope @Scope}, - * {@link Primary @Primary}, and {@link Lazy @Lazy} annotations to achieve those - * semantics. For example: + * depends-on, primary, or lazy. Rather, it should be used in conjunction with + * {@link Scope @Scope}, {@link DependsOn @DependsOn}, {@link Primary @Primary}, + * and {@link Lazy @Lazy} annotations to achieve those semantics. For example: * * <pre class="code"> * &#064;Bean @@ -96,15 +98,21 @@ * // ... * }</pre> * - * <h3>Configuration Class <i>Lite</i> Mode</h3> + * <h3>{@code @Bean} <em>Lite</em> Mode</h3> + * + * <p>{@code @Bean} methods may also be declared within classes that are <em>not</em> + * annotated with {@code @Configuration}. For example, bean methods may be declared + * in a {@code @Component} class or even in a <em>plain old class</em>. In such cases, + * a {@code @Bean} method will get processed in a configuration class <em>'lite'</em> + * mode. * - * <p>{@code @Bean} methods may also be declared within any {@code @Component} class, in - * which case they will get processed in a configuration class <em>'lite'</em> mode in which - * they will simply be called as plain factory methods from the container (similar to - * {@code factory-method} declarations in XML) but with <b><i>prototype</i></b> semantics. - * The containing component classes remain unmodified in this case, and there are no - * unusual constraints for factory methods; however, scoping semantics are <b>not</b> - * respected as described above for inter-bean method invocations in this mode. For example: + * <p>In contrast to bean methods in {@code @Configuration} classes as described + * above, bean methods in <em>lite</em> mode will be called as plain <em>factory + * methods</em> from the container (similar to {@code factory-method} declarations + * in XML) but with <b><em>prototype</em></b> semantics. The containing class remains + * unmodified in this case, and there are no unusual constraints for factory methods; + * however, scoping semantics are <b>not</b> respected as described above for + * 'inter-bean method invocations in this mode. For example: * * <pre class="code"> * &#064;Component @@ -214,4 +222,4 @@ */ String destroyMethod() default AbstractBeanDefinition.INFER_METHOD; -} +} \ No newline at end of file
false
Other
spring-projects
spring-framework
2624b909060e0967e16771de7a35261decd5a4a9.json
Avoid NPE in AutowiredAnnotationBeanPostProcessor Prior to this change, AABPP#determineRequiredStatus never checked the return value of ReflectionUtils#findMethod when searching for a '#required' attribute. This call returns null for annotations such as @Inject, @Value and @Resource, and subsequently causes a NullPointerException to be thrown when ReflectionUtils#invokeMethod is called. The NPE is caught immediately and #determineRequiredStatus returns defaulting to true, but this this approach is inefficient. It is also problematic for users who have set breakpoints on NPE -- they end up debugging into Spring internals, which is a false positive. This commit checks the return value of of ReflectionUtils#findMethod, and in the case of null, eagerly returns true. There is no change to external behavior, simply a more efficient and debugging-friendly implementation. Existing test cases already cover this change, given that it is purely a refactoring. Issue: SPR-9316
spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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. @@ -405,10 +405,16 @@ protected <T> Map<String, T> findAutowireCandidates(Class<T> type) throws BeansE protected boolean determineRequiredStatus(Annotation annotation) { try { Method method = ReflectionUtils.findMethod(annotation.annotationType(), this.requiredParameterName); + if (method == null) { + // annotations like @Inject, @Value and @Resource don't have a method + // (attribute) named "required" -> default to required status + return true; + } return (this.requiredParameterValue == (Boolean) ReflectionUtils.invokeMethod(method, annotation)); } catch (Exception ex) { - // required by default + // an exception was thrown during reflective invocation of the required + // attribute -> default to required status return true; } }
false
Other
spring-projects
spring-framework
b50f6e19a6820a8e735a89dfee1a85077e804ec5.json
Fix regression in ClassPathResource descriptions ClassPathResource.getDescription() now returns consistent, meaningful results for all variants of ClassPathResource's constructors. Issue: SPR-9413
spring-core/src/main/java/org/springframework/core/io/ClassPathResource.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. @@ -35,6 +35,7 @@ * Always supports resolution as URL. * * @author Juergen Hoeller + * @author Sam Brannen * @since 28.12.2003 * @see java.lang.ClassLoader#getResourceAsStream(String) * @see java.lang.Class#getResourceAsStream(String) @@ -108,7 +109,6 @@ protected ClassPathResource(String path, ClassLoader classLoader, Class<?> clazz this.clazz = clazz; } - /** * Return the path for this resource (as resource path within the class path). */ @@ -123,7 +123,6 @@ public final ClassLoader getClassLoader() { return (this.classLoader != null ? this.classLoader : this.clazz.getClassLoader()); } - /** * This implementation checks for the resolution of a resource URL. * @see java.lang.ClassLoader#getResource(String) @@ -155,8 +154,7 @@ public InputStream getInputStream() throws IOException { is = this.classLoader.getResourceAsStream(this.path); } if (is == null) { - throw new FileNotFoundException( - getDescription() + " cannot be opened because it does not exist"); + throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist"); } return is; } @@ -176,8 +174,7 @@ public URL getURL() throws IOException { url = this.classLoader.getResource(this.path); } if (url == null) { - throw new FileNotFoundException( - getDescription() + " cannot be resolved to URL because it does not exist"); + throw new FileNotFoundException(getDescription() + " cannot be resolved to URL because it does not exist"); } return url; } @@ -209,17 +206,22 @@ public String getFilename() { public String getDescription() { StringBuilder builder = new StringBuilder("class path resource ["); - if (this.clazz != null) { + String pathToUse = path; + + if (this.clazz != null && !pathToUse.startsWith("/")) { builder.append(ClassUtils.classPackageAsResourcePath(this.clazz)); builder.append('/'); } - builder.append(this.path); + if (pathToUse.startsWith("/")) { + pathToUse = pathToUse.substring(1); + } + + builder.append(pathToUse); builder.append(']'); return builder.toString(); } - /** * This implementation compares the underlying class path locations. */ @@ -230,9 +232,9 @@ public boolean equals(Object obj) { } if (obj instanceof ClassPathResource) { ClassPathResource otherRes = (ClassPathResource) obj; - return (this.path.equals(otherRes.path) && - ObjectUtils.nullSafeEquals(this.classLoader, otherRes.classLoader) && - ObjectUtils.nullSafeEquals(this.clazz, otherRes.clazz)); + return (this.path.equals(otherRes.path) + && ObjectUtils.nullSafeEquals(this.classLoader, otherRes.classLoader) && ObjectUtils.nullSafeEquals( + this.clazz, otherRes.clazz)); } return false; }
true
Other
spring-projects
spring-framework
b50f6e19a6820a8e735a89dfee1a85077e804ec5.json
Fix regression in ClassPathResource descriptions ClassPathResource.getDescription() now returns consistent, meaningful results for all variants of ClassPathResource's constructors. Issue: SPR-9413
spring-core/src/test/java/org/springframework/core/io/ClassPathResourceTests.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. @@ -17,24 +17,59 @@ package org.springframework.core.io; import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.internal.matchers.StringContains.containsString; import java.io.FileNotFoundException; import java.io.IOException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.junit.Test; /** - * Unit tests cornering bug SPR-6888. + * Unit tests that serve as regression tests for the bugs described in SPR-6888 + * and SPR-9413. * * @author Chris Beams + * @author Sam Brannen */ public class ClassPathResourceTests { + private static final String PACKAGE_PATH = "org/springframework/core/io"; - private static final String RESOURCE_NAME = "notexist.xml"; - private static final String FQ_RESOURCE_PATH = PACKAGE_PATH + '/' + RESOURCE_NAME; + private static final String NONEXISTENT_RESOURCE_NAME = "nonexistent.xml"; + private static final String FQ_RESOURCE_PATH = PACKAGE_PATH + '/' + NONEXISTENT_RESOURCE_NAME; + + /** + * Absolute path version of {@link #FQ_RESOURCE_PATH}. + */ + private static final String FQ_RESOURCE_PATH_WITH_LEADING_SLASH = '/' + FQ_RESOURCE_PATH; + + private static final Pattern DESCRIPTION_PATTERN = Pattern.compile("^class path resource \\[(.+?)\\]$"); + + + private void assertDescriptionContainsExpectedPath(ClassPathResource resource, String expectedPath) { + Matcher matcher = DESCRIPTION_PATTERN.matcher(resource.getDescription()); + assertTrue(matcher.matches()); + assertEquals(1, matcher.groupCount()); + String match = matcher.group(1); + + assertEquals(expectedPath, match); + } + + private void assertExceptionContainsFullyQualifiedPath(ClassPathResource resource) { + try { + resource.getInputStream(); + fail("FileNotFoundException expected for resource: " + resource); + } + catch (IOException ex) { + assertThat(ex, instanceOf(FileNotFoundException.class)); + assertThat(ex.getMessage(), containsString(FQ_RESOURCE_PATH)); + } + } @Test public void stringConstructorRaisesExceptionWithFullyQualifiedPath() { @@ -43,21 +78,48 @@ public void stringConstructorRaisesExceptionWithFullyQualifiedPath() { @Test public void classLiteralConstructorRaisesExceptionWithFullyQualifiedPath() { - assertExceptionContainsFullyQualifiedPath(new ClassPathResource(RESOURCE_NAME, this.getClass())); + assertExceptionContainsFullyQualifiedPath(new ClassPathResource(NONEXISTENT_RESOURCE_NAME, this.getClass())); } @Test public void classLoaderConstructorRaisesExceptionWithFullyQualifiedPath() { - assertExceptionContainsFullyQualifiedPath(new ClassPathResource(FQ_RESOURCE_PATH, this.getClass().getClassLoader())); + assertExceptionContainsFullyQualifiedPath(new ClassPathResource(FQ_RESOURCE_PATH, + this.getClass().getClassLoader())); } - private void assertExceptionContainsFullyQualifiedPath(ClassPathResource resource) { - try { - resource.getInputStream(); - fail("FileNotFoundException expected for resource: " + resource); - } catch (IOException ex) { - assertThat(ex, instanceOf(FileNotFoundException.class)); - assertThat(ex.getMessage(), containsString(FQ_RESOURCE_PATH)); - } + @Test + public void getDescriptionWithStringConstructor() { + assertDescriptionContainsExpectedPath(new ClassPathResource(FQ_RESOURCE_PATH), FQ_RESOURCE_PATH); + } + + @Test + public void getDescriptionWithStringConstructorAndLeadingSlash() { + assertDescriptionContainsExpectedPath(new ClassPathResource(FQ_RESOURCE_PATH_WITH_LEADING_SLASH), + FQ_RESOURCE_PATH); + } + + @Test + public void getDescriptionWithClassLiteralConstructor() { + assertDescriptionContainsExpectedPath(new ClassPathResource(NONEXISTENT_RESOURCE_NAME, this.getClass()), + FQ_RESOURCE_PATH); } + + @Test + public void getDescriptionWithClassLiteralConstructorAndLeadingSlash() { + assertDescriptionContainsExpectedPath( + new ClassPathResource(FQ_RESOURCE_PATH_WITH_LEADING_SLASH, this.getClass()), FQ_RESOURCE_PATH); + } + + @Test + public void getDescriptionWithClassLoaderConstructor() { + assertDescriptionContainsExpectedPath( + new ClassPathResource(FQ_RESOURCE_PATH, this.getClass().getClassLoader()), FQ_RESOURCE_PATH); + } + + @Test + public void getDescriptionWithClassLoaderConstructorAndLeadingSlash() { + assertDescriptionContainsExpectedPath(new ClassPathResource(FQ_RESOURCE_PATH_WITH_LEADING_SLASH, + this.getClass().getClassLoader()), FQ_RESOURCE_PATH); + } + }
true
Other
spring-projects
spring-framework
01a9dd97721c93fe80d8fd35bd5dc8de649b3595.json
Add option to set Content-Length in JSON Views MappingJackson2JsonView and MappingJacksonJsonView now provide an option that will set the Content-Length header of JSON responses. Use of the option implies buffering of the response and it must be enabled explicitly. Issue: SPR-7866
spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/MappingJackson2JsonView.java
@@ -16,6 +16,8 @@ package org.springframework.web.servlet.view.json; +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -71,6 +73,7 @@ public class MappingJackson2JsonView extends AbstractView { private boolean disableCaching = true; + private boolean updateContentLength = false; /** * Construct a new {@code JacksonJsonView}, setting the content type to {@code application/json}. @@ -199,6 +202,15 @@ public void setDisableCaching(boolean disableCaching) { this.disableCaching = disableCaching; } + /** + * Whether to update the 'Content-Length' header of the response. When set to + * {@code true}, the response is buffered in order to determine the content + * length and set the 'Content-Length' header of the response. + * <p>The default setting is {@code false}. + */ + public void setUpdateContentLength(boolean updateContentLength) { + this.updateContentLength = updateContentLength; + } @Override protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) { @@ -215,9 +227,10 @@ protected void prepareResponse(HttpServletRequest request, HttpServletResponse r protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { + OutputStream stream = this.updateContentLength ? createTemporaryOutputStream() : response.getOutputStream(); + Object value = filterModel(model); - JsonGenerator generator = - this.objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), this.encoding); + JsonGenerator generator = this.objectMapper.getJsonFactory().createJsonGenerator(stream, this.encoding); // A workaround for JsonGenerators not applying serialization features // https://github.com/FasterXML/jackson-databind/issues/12 @@ -229,6 +242,10 @@ protected void renderMergedOutputModel(Map<String, Object> model, HttpServletReq generator.writeRaw("{} && "); } this.objectMapper.writeValue(generator, value); + + if (this.updateContentLength) { + writeToResponse(response, (ByteArrayOutputStream) stream); + } } /**
true
Other
spring-projects
spring-framework
01a9dd97721c93fe80d8fd35bd5dc8de649b3595.json
Add option to set Content-Length in JSON Views MappingJackson2JsonView and MappingJacksonJsonView now provide an option that will set the Content-Length header of JSON responses. Use of the option implies buffering of the response and it must be enabled explicitly. Issue: SPR-7866
spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/MappingJacksonJsonView.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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,6 +16,8 @@ package org.springframework.web.servlet.view.json; +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -73,6 +75,7 @@ public class MappingJacksonJsonView extends AbstractView { private boolean disableCaching = true; + private boolean updateContentLength = false; /** * Construct a new {@code JacksonJsonView}, setting the content type to {@code application/json}. @@ -201,6 +204,16 @@ public void setDisableCaching(boolean disableCaching) { this.disableCaching = disableCaching; } + /** + * Whether to update the 'Content-Length' header of the response. When set to + * {@code true}, the response is buffered in order to determine the content + * length and set the 'Content-Length' header of the response. + * <p>The default setting is {@code false}. + */ + public void setUpdateContentLength(boolean updateContentLength) { + this.updateContentLength = updateContentLength; + } + @Override protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) { @@ -217,9 +230,10 @@ protected void prepareResponse(HttpServletRequest request, HttpServletResponse r protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { + OutputStream stream = this.updateContentLength ? createTemporaryOutputStream() : response.getOutputStream(); + Object value = filterModel(model); - JsonGenerator generator = - this.objectMapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), this.encoding); + JsonGenerator generator = this.objectMapper.getJsonFactory().createJsonGenerator(stream, this.encoding); // A workaround for JsonGenerators not applying serialization features // https://github.com/FasterXML/jackson-databind/issues/12 @@ -231,6 +245,10 @@ protected void renderMergedOutputModel(Map<String, Object> model, HttpServletReq generator.writeRaw("{} && "); } this.objectMapper.writeValue(generator, value); + + if (this.updateContentLength) { + writeToResponse(response, (ByteArrayOutputStream) stream); + } } /**
true
Other
spring-projects
spring-framework
01a9dd97721c93fe80d8fd35bd5dc8de649b3595.json
Add option to set Content-Length in JSON Views MappingJackson2JsonView and MappingJacksonJsonView now provide an option that will set the Content-Length header of JSON responses. Use of the option implies buffering of the response and it must be enabled explicitly. Issue: SPR-7866
spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJackson2JsonViewTests.java
@@ -59,7 +59,7 @@ * @author Arjen Poutsma * @author Rossen Stoyanchev */ -public class MappingJackson2JsonViewTest { +public class MappingJackson2JsonViewTests { private MappingJackson2JsonView view; @@ -94,6 +94,7 @@ public void renderSimpleMap() throws Exception { model.put("bindingResult", createMock("binding_result", BindingResult.class)); model.put("foo", "bar"); + view.setUpdateContentLength(true); view.render(model, request, response); assertEquals("no-cache", response.getHeader("Pragma")); @@ -104,6 +105,7 @@ public void renderSimpleMap() throws Exception { String jsonResult = response.getContentAsString(); assertTrue(jsonResult.length() > 0); + assertEquals(jsonResult.length(), response.getContentLength()); validateResult(); } @@ -137,9 +139,11 @@ public void renderSimpleBean() throws Exception { model.put("bindingResult", createMock("binding_result", BindingResult.class)); model.put("foo", bean); + view.setUpdateContentLength(true); view.render(model, request, response); assertTrue(response.getContentAsString().length() > 0); + assertEquals(response.getContentAsString().length(), response.getContentLength()); validateResult(); }
true
Other
spring-projects
spring-framework
01a9dd97721c93fe80d8fd35bd5dc8de649b3595.json
Add option to set Content-Length in JSON Views MappingJackson2JsonView and MappingJacksonJsonView now provide an option that will set the Content-Length header of JSON responses. Use of the option implies buffering of the response and it must be enabled explicitly. Issue: SPR-7866
spring-webmvc/src/test/java/org/springframework/web/servlet/view/json/MappingJacksonJsonViewTests.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. @@ -52,7 +52,7 @@ * @author Jeremy Grelle * @author Arjen Poutsma */ -public class MappingJacksonJsonViewTest { +public class MappingJacksonJsonViewTests { private MappingJacksonJsonView view; @@ -87,6 +87,7 @@ public void renderSimpleMap() throws Exception { model.put("bindingResult", createMock("binding_result", BindingResult.class)); model.put("foo", "bar"); + view.setUpdateContentLength(true); view.render(model, request, response); assertEquals("no-cache", response.getHeader("Pragma")); @@ -97,6 +98,7 @@ public void renderSimpleMap() throws Exception { String jsonResult = response.getContentAsString(); assertTrue(jsonResult.length() > 0); + assertEquals(jsonResult.length(), response.getContentLength()); validateResult(); } @@ -130,9 +132,11 @@ public void renderSimpleBean() throws Exception { model.put("bindingResult", createMock("binding_result", BindingResult.class)); model.put("foo", bean); + view.setUpdateContentLength(true); view.render(model, request, response); assertTrue(response.getContentAsString().length() > 0); + assertEquals(response.getContentAsString().length(), response.getContentLength()); validateResult(); }
true
Other
spring-projects
spring-framework
01a9dd97721c93fe80d8fd35bd5dc8de649b3595.json
Add option to set Content-Length in JSON Views MappingJackson2JsonView and MappingJacksonJsonView now provide an option that will set the Content-Length header of JSON responses. Use of the option implies buffering of the response and it must be enabled explicitly. Issue: SPR-7866
src/dist/changelog.txt
@@ -25,7 +25,8 @@ Changes in version 3.2 M1 * support access to all URI vars via @PathVariable Map<String, String> * add "excludedExceptions" property to SimpleUrlHandlerMapping * add CompositeRequestCondition for use with multiple custom request mapping conditions -* add option to configure custom MessageCodesResolver through WebMvcConfigurer +* add ability to configure custom MessageCodesResolver through the MVC Java config +* add option in MappingJacksonJsonView for setting the Content-Length header Changes in version 3.1.1 (2012-02-16) -------------------------------------
true
Other
spring-projects
spring-framework
2af294ab26b670c7f997054ab11ecf7402fee6ed.json
Add MessageCodesResolver hook to WebMvcConfigurer This change makes it possible to provide a custom MessageCodesResolver through the MVC Java config whether using @EnableWebMvc and extending WebMVcConfigurerAdapter or sub-classing directly from WebMvcConfigurationSupport. Issue: SPR-9223
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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. @@ -22,20 +22,20 @@ import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.validation.MessageCodesResolver; import org.springframework.validation.Validator; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodReturnValueHandler; import org.springframework.web.servlet.HandlerExceptionResolver; /** - * Extends {@link WebMvcConfigurationSupport} with the ability to detect beans - * of type {@link WebMvcConfigurer} and give them a chance to customize the - * provided configuration by delegating to them at the appropriate times. - * + * A sub-class of {@code WebMvcConfigurationSupport} that detects and delegates + * to all beans of type {@link WebMvcConfigurer} allowing them to customize the + * configuration provided by {@code WebMvcConfigurationSupport}. This is the + * class actually imported by {@link EnableWebMvc @EnableWebMvc}. + * * @author Rossen Stoyanchev * @since 3.1 - * - * @see EnableWebMvc */ @Configuration public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport { @@ -52,52 +52,57 @@ public void setConfigurers(List<WebMvcConfigurer> configurers) { @Override protected void addInterceptors(InterceptorRegistry registry) { - configurers.addInterceptors(registry); + this.configurers.addInterceptors(registry); } @Override protected void addViewControllers(ViewControllerRegistry registry) { - configurers.addViewControllers(registry); + this.configurers.addViewControllers(registry); } @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { - configurers.addResourceHandlers(registry); + this.configurers.addResourceHandlers(registry); } @Override protected void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { - configurers.configureDefaultServletHandling(configurer); + this.configurers.configureDefaultServletHandling(configurer); } - + @Override protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { - configurers.addArgumentResolvers(argumentResolvers); + this.configurers.addArgumentResolvers(argumentResolvers); } @Override protected void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) { - configurers.addReturnValueHandlers(returnValueHandlers); + this.configurers.addReturnValueHandlers(returnValueHandlers); } @Override protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { - configurers.configureMessageConverters(converters); + this.configurers.configureMessageConverters(converters); } @Override protected void addFormatters(FormatterRegistry registry) { - configurers.addFormatters(registry); + this.configurers.addFormatters(registry); } @Override protected Validator getValidator() { - return configurers.getValidator(); + return this.configurers.getValidator(); + } + + @Override + protected MessageCodesResolver getMessageCodesResolver() { + return this.configurers.getMessageCodesResolver(); } @Override protected void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { - configurers.configureHandlerExceptionResolvers(exceptionResolvers); + this.configurers.configureHandlerExceptionResolvers(exceptionResolvers); } }
true
Other
spring-projects
spring-framework
2af294ab26b670c7f997054ab11ecf7402fee6ed.json
Add MessageCodesResolver hook to WebMvcConfigurer This change makes it possible to provide a custom MessageCodesResolver through the MVC Java config whether using @EnableWebMvc and extending WebMVcConfigurerAdapter or sub-classing directly from WebMvcConfigurationSupport. Issue: SPR-9223
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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. @@ -48,6 +48,7 @@ import org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter; import org.springframework.util.ClassUtils; import org.springframework.validation.Errors; +import org.springframework.validation.MessageCodesResolver; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.HttpRequestHandler; @@ -280,6 +281,7 @@ public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { ConfigurableWebBindingInitializer webBindingInitializer = new ConfigurableWebBindingInitializer(); webBindingInitializer.setConversionService(mvcConversionService()); webBindingInitializer.setValidator(mvcValidator()); + webBindingInitializer.setMessageCodesResolver(getMessageCodesResolver()); List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<HandlerMethodArgumentResolver>(); addArgumentResolvers(argumentResolvers); @@ -295,6 +297,69 @@ public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { return adapter; } + /** + * Returns a {@link FormattingConversionService} for use with annotated + * controller methods and the {@code spring:eval} JSP tag. + * Also see {@link #addFormatters} as an alternative to overriding this method. + */ + @Bean + public FormattingConversionService mvcConversionService() { + FormattingConversionService conversionService = new DefaultFormattingConversionService(); + addFormatters(conversionService); + return conversionService; + } + + /** + * Returns a global {@link Validator} instance for example for validating + * {@code @ModelAttribute} and {@code @RequestBody} method arguments. + * Delegates to {@link #getValidator()} first and if that returns {@code null} + * checks the classpath for the presence of a JSR-303 implementations + * before creating a {@code LocalValidatorFactoryBean}.If a JSR-303 + * implementation is not available, a no-op {@link Validator} is returned. + */ + @Bean + public Validator mvcValidator() { + Validator validator = getValidator(); + if (validator == null) { + if (ClassUtils.isPresent("javax.validation.Validator", getClass().getClassLoader())) { + Class<?> clazz; + try { + String className = "org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"; + clazz = ClassUtils.forName(className, WebMvcConfigurationSupport.class.getClassLoader()); + } catch (ClassNotFoundException e) { + throw new BeanInitializationException("Could not find default validator", e); + } catch (LinkageError e) { + throw new BeanInitializationException("Could not find default validator", e); + } + validator = (Validator) BeanUtils.instantiate(clazz); + } + else { + validator = new Validator() { + public boolean supports(Class<?> clazz) { + return false; + } + public void validate(Object target, Errors errors) { + } + }; + } + } + return validator; + } + + /** + * Override this method to provide a custom {@link Validator}. + */ + protected Validator getValidator() { + return null; + } + + /** + * Override this method to provide a custom {@link MessageCodesResolver}. + */ + protected MessageCodesResolver getMessageCodesResolver() { + return null; + } + /** * Add custom {@link HandlerMethodArgumentResolver}s to use in addition to * the ones registered by default. @@ -387,68 +452,12 @@ else if (ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", classLoad } } - /** - * Returns a {@link FormattingConversionService} for use with annotated - * controller methods and the {@code spring:eval} JSP tag. - * Also see {@link #addFormatters} as an alternative to overriding this method. - */ - @Bean - public FormattingConversionService mvcConversionService() { - FormattingConversionService conversionService = new DefaultFormattingConversionService(); - addFormatters(conversionService); - return conversionService; - } - /** * Override this method to add custom {@link Converter}s and {@link Formatter}s. */ protected void addFormatters(FormatterRegistry registry) { } - /** - * Returns a global {@link Validator} instance for example for validating - * {@code @ModelAttribute} and {@code @RequestBody} method arguments. - * Delegates to {@link #getValidator()} first and if that returns {@code null} - * checks the classpath for the presence of a JSR-303 implementations - * before creating a {@code LocalValidatorFactoryBean}.If a JSR-303 - * implementation is not available, a no-op {@link Validator} is returned. - */ - @Bean - public Validator mvcValidator() { - Validator validator = getValidator(); - if (validator == null) { - if (ClassUtils.isPresent("javax.validation.Validator", getClass().getClassLoader())) { - Class<?> clazz; - try { - String className = "org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"; - clazz = ClassUtils.forName(className, WebMvcConfigurationSupport.class.getClassLoader()); - } catch (ClassNotFoundException e) { - throw new BeanInitializationException("Could not find default validator", e); - } catch (LinkageError e) { - throw new BeanInitializationException("Could not find default validator", e); - } - validator = (Validator) BeanUtils.instantiate(clazz); - } - else { - validator = new Validator() { - public boolean supports(Class<?> clazz) { - return false; - } - public void validate(Object target, Errors errors) { - } - }; - } - } - return validator; - } - - /** - * Override this method to provide a custom {@link Validator}. - */ - protected Validator getValidator() { - return null; - } - /** * Returns a {@link HttpRequestHandlerAdapter} for processing requests * with {@link HttpRequestHandler}s.
true
Other
spring-projects
spring-framework
2af294ab26b670c7f997054ab11ecf7402fee6ed.json
Add MessageCodesResolver hook to WebMvcConfigurer This change makes it possible to provide a custom MessageCodesResolver through the MVC Java config whether using @EnableWebMvc and extending WebMVcConfigurerAdapter or sub-classing directly from WebMvcConfigurationSupport. Issue: SPR-9223
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurer.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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. @@ -22,6 +22,7 @@ import org.springframework.format.Formatter; import org.springframework.format.FormatterRegistry; import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.validation.MessageCodesResolver; import org.springframework.validation.Validator; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodReturnValueHandler; @@ -30,10 +31,10 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; /** - * Defines callback methods to customize the Java-based configuration for - * Spring MVC enabled via {@code @EnableWebMvc}. - * - * <p>{@code @EnableWebMvc}-annotated configuration classes may implement + * Defines callback methods to customize the Java-based configuration for + * Spring MVC enabled via {@code @EnableWebMvc}. + * + * <p>{@code @EnableWebMvc}-annotated configuration classes may implement * this interface to be called back and given a chance to customize the * default configuration. Consider extending {@link WebMvcConfigurerAdapter}, * which provides a stub implementation of all interface methods. @@ -46,7 +47,7 @@ public interface WebMvcConfigurer { /** - * Add {@link Converter}s and {@link Formatter}s in addition to the ones + * Add {@link Converter}s and {@link Formatter}s in addition to the ones * registered by default. */ void addFormatters(FormatterRegistry registry); @@ -69,55 +70,62 @@ public interface WebMvcConfigurer { Validator getValidator(); /** - * Add resolvers to support custom controller method argument types. - * <p>This does not override the built-in support for resolving handler - * method arguments. To customize the built-in support for argument + * Add resolvers to support custom controller method argument types. + * <p>This does not override the built-in support for resolving handler + * method arguments. To customize the built-in support for argument * resolution, configure {@link RequestMappingHandlerAdapter} directly. * @param argumentResolvers initially an empty list */ void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers); /** - * Add handlers to support custom controller method return value types. + * Add handlers to support custom controller method return value types. * <p>Using this option does not override the built-in support for handling - * return values. To customize the built-in support for handling return + * return values. To customize the built-in support for handling return * values, configure RequestMappingHandlerAdapter directly. * @param returnValueHandlers initially an empty list */ void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers); /** - * Configure the {@link HandlerExceptionResolver}s to handle unresolved + * Configure the {@link HandlerExceptionResolver}s to handle unresolved * controller exceptions. If no resolvers are added to the list, default * exception resolvers are added instead. * @param exceptionResolvers initially an empty list */ void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers); /** - * Add Spring MVC lifecycle interceptors for pre- and post-processing of - * controller method invocations. Interceptors can be registered to apply + * Add Spring MVC lifecycle interceptors for pre- and post-processing of + * controller method invocations. Interceptors can be registered to apply * to all requests or be limited to a subset of URL patterns. */ void addInterceptors(InterceptorRegistry registry); /** - * Add view controllers to create a direct mapping between a URL path and - * view name without the need for a controller in between. + * Provide a custom {@link MessageCodesResolver} for building message codes + * from data binding and validation error codes. Leave the return value as + * {@code null} to keep the default. + */ + MessageCodesResolver getMessageCodesResolver(); + + /** + * Add view controllers to create a direct mapping between a URL path and + * view name without the need for a controller in between. */ void addViewControllers(ViewControllerRegistry registry); /** - * Add handlers to serve static resources such as images, js, and, css + * Add handlers to serve static resources such as images, js, and, css * files from specific locations under web application root, the classpath, * and others. */ void addResourceHandlers(ResourceHandlerRegistry registry); /** - * Configure a handler to delegate unhandled requests by forwarding to the + * Configure a handler to delegate unhandled requests by forwarding to the * Servlet container's "default" servlet. A common use case for this is when - * the {@link DispatcherServlet} is mapped to "/" thus overriding the + * the {@link DispatcherServlet} is mapped to "/" thus overriding the * Servlet container's default handling of static resources. */ void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
true
Other
spring-projects
spring-framework
2af294ab26b670c7f997054ab11ecf7402fee6ed.json
Add MessageCodesResolver hook to WebMvcConfigurer This change makes it possible to provide a custom MessageCodesResolver through the MVC Java config whether using @EnableWebMvc and extending WebMVcConfigurerAdapter or sub-classing directly from WebMvcConfigurationSupport. Issue: SPR-9223
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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. @@ -20,13 +20,15 @@ import org.springframework.format.FormatterRegistry; import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.validation.MessageCodesResolver; import org.springframework.validation.Validator; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodReturnValueHandler; import org.springframework.web.servlet.HandlerExceptionResolver; /** - * An convenient base class with empty method implementations of {@link WebMvcConfigurer}. + * An implementation of {@link WebMvcConfigurer} with empty methods allowing + * sub-classes to override only the methods they're interested in. * * @author Rossen Stoyanchev * @since 3.1 @@ -76,6 +78,14 @@ public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnV public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { } + /** + * {@inheritDoc} + * <p>This implementation is empty. + */ + public MessageCodesResolver getMessageCodesResolver() { + return null; + } + /** * {@inheritDoc} * <p>This implementation is empty.
true
Other
spring-projects
spring-framework
2af294ab26b670c7f997054ab11ecf7402fee6ed.json
Add MessageCodesResolver hook to WebMvcConfigurer This change makes it possible to provide a custom MessageCodesResolver through the MVC Java config whether using @EnableWebMvc and extending WebMVcConfigurerAdapter or sub-classing directly from WebMvcConfigurationSupport. Issue: SPR-9223
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerComposite.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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. @@ -17,12 +17,11 @@ package org.springframework.web.servlet.config.annotation; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import org.springframework.format.FormatterRegistry; import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.validation.MessageCodesResolver; import org.springframework.validation.Validator; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.HandlerMethodReturnValueHandler; @@ -45,77 +44,92 @@ public void addWebMvcConfigurers(List<WebMvcConfigurer> configurers) { } public void addFormatters(FormatterRegistry registry) { - for (WebMvcConfigurer delegate : delegates) { + for (WebMvcConfigurer delegate : this.delegates) { delegate.addFormatters(registry); } } public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { - for (WebMvcConfigurer delegate : delegates) { + for (WebMvcConfigurer delegate : this.delegates) { delegate.configureMessageConverters(converters); } } public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { - for (WebMvcConfigurer delegate : delegates) { + for (WebMvcConfigurer delegate : this.delegates) { delegate.addArgumentResolvers(argumentResolvers); } } public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) { - for (WebMvcConfigurer delegate : delegates) { + for (WebMvcConfigurer delegate : this.delegates) { delegate.addReturnValueHandlers(returnValueHandlers); } } public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) { - for (WebMvcConfigurer delegate : delegates) { + for (WebMvcConfigurer delegate : this.delegates) { delegate.configureHandlerExceptionResolvers(exceptionResolvers); } } public void addInterceptors(InterceptorRegistry registry) { - for (WebMvcConfigurer delegate : delegates) { + for (WebMvcConfigurer delegate : this.delegates) { delegate.addInterceptors(registry); } } public void addViewControllers(ViewControllerRegistry registry) { - for (WebMvcConfigurer delegate : delegates) { + for (WebMvcConfigurer delegate : this.delegates) { delegate.addViewControllers(registry); } } public void addResourceHandlers(ResourceHandlerRegistry registry) { - for (WebMvcConfigurer delegate : delegates) { + for (WebMvcConfigurer delegate : this.delegates) { delegate.addResourceHandlers(registry); } } public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { - for (WebMvcConfigurer delegate : delegates) { + for (WebMvcConfigurer delegate : this.delegates) { delegate.configureDefaultServletHandling(configurer); } } public Validator getValidator() { - Map<WebMvcConfigurer, Validator> validators = new HashMap<WebMvcConfigurer, Validator>(); - for (WebMvcConfigurer delegate : delegates) { - Validator validator = delegate.getValidator(); + List<Validator> candidates = new ArrayList<Validator>(); + for (WebMvcConfigurer configurer : this.delegates) { + Validator validator = configurer.getValidator(); if (validator != null) { - validators.put(delegate, validator); + candidates.add(validator); } } - if (validators.size() == 0) { - return null; + return selectSingleInstance(candidates, Validator.class); + } + + private <T> T selectSingleInstance(List<T> instances, Class<T> instanceType) { + if (instances.size() > 1) { + throw new IllegalStateException( + "Only one [" + instanceType + "] was expected but multiple instances were provided: " + instances); } - else if (validators.size() == 1) { - return validators.values().iterator().next(); + else if (instances.size() == 1) { + return instances.get(0); } else { - throw new IllegalStateException( - "Multiple custom validators provided from [" + validators.keySet() + "]"); + return null; + } + } + + public MessageCodesResolver getMessageCodesResolver() { + List<MessageCodesResolver> candidates = new ArrayList<MessageCodesResolver>(); + for (WebMvcConfigurer configurer : this.delegates) { + MessageCodesResolver messageCodesResolver = configurer.getMessageCodesResolver(); + if (messageCodesResolver != null) { + candidates.add(messageCodesResolver); + } } + return selectSingleInstance(candidates, MessageCodesResolver.class); } }
true
Other
spring-projects
spring-framework
2af294ab26b670c7f997054ab11ecf7402fee6ed.json
Add MessageCodesResolver hook to WebMvcConfigurer This change makes it possible to provide a custom MessageCodesResolver through the MVC Java config whether using @EnableWebMvc and extending WebMVcConfigurerAdapter or sub-classing directly from WebMvcConfigurationSupport. Issue: SPR-9223
spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfigurationTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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. @@ -35,6 +35,7 @@ import org.springframework.format.support.FormattingConversionService; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; +import org.springframework.validation.DefaultMessageCodesResolver; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; import org.springframework.web.method.support.HandlerMethodArgumentResolver; @@ -72,6 +73,7 @@ public void requestMappingHandlerAdapter() throws Exception { configurer.configureMessageConverters(capture(converters)); expect(configurer.getValidator()).andReturn(null); + expect(configurer.getMessageCodesResolver()).andReturn(null); configurer.addFormatters(capture(conversionService)); configurer.addArgumentResolvers(capture(resolvers)); configurer.addReturnValueHandlers(capture(handlers)); @@ -91,7 +93,7 @@ public void requestMappingHandlerAdapter() throws Exception { verify(configurer); } - @Test + @Test public void configureMessageConverters() { List<WebMvcConfigurer> configurers = new ArrayList<WebMvcConfigurer>(); configurers.add(new WebMvcConfigurerAdapter() { @@ -102,11 +104,11 @@ public void configureMessageConverters(List<HttpMessageConverter<?>> converters) }); mvcConfiguration = new DelegatingWebMvcConfiguration(); mvcConfiguration.setConfigurers(configurers); - + RequestMappingHandlerAdapter adapter = mvcConfiguration.requestMappingHandlerAdapter(); assertEquals("Only one custom converter should be registered", 1, adapter.getMessageConverters().size()); } - + @Test public void getCustomValidator() { expect(configurer.getValidator()).andReturn(new LocalValidatorFactoryBean()); @@ -118,6 +120,17 @@ public void getCustomValidator() { verify(configurer); } + @Test + public void getCustomMessageCodesResolver() { + expect(configurer.getMessageCodesResolver()).andReturn(new DefaultMessageCodesResolver()); + replay(configurer); + + mvcConfiguration.setConfigurers(Arrays.asList(configurer)); + mvcConfiguration.getMessageCodesResolver(); + + verify(configurer); + } + @Test public void handlerExceptionResolver() throws Exception { Capture<List<HttpMessageConverter<?>>> converters = new Capture<List<HttpMessageConverter<?>>>(); @@ -139,7 +152,7 @@ public void handlerExceptionResolver() throws Exception { verify(configurer); } - @Test + @Test public void configureExceptionResolvers() throws Exception { List<WebMvcConfigurer> configurers = new ArrayList<WebMvcConfigurer>(); configurers.add(new WebMvcConfigurerAdapter() { @@ -149,10 +162,10 @@ public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> ex } }); mvcConfiguration.setConfigurers(configurers); - - HandlerExceptionResolverComposite composite = + + HandlerExceptionResolverComposite composite = (HandlerExceptionResolverComposite) mvcConfiguration.handlerExceptionResolver(); assertEquals("Only one custom converter is expected", 1, composite.getExceptionResolvers().size()); } - + }
true
Other
spring-projects
spring-framework
2af294ab26b670c7f997054ab11ecf7402fee6ed.json
Add MessageCodesResolver hook to WebMvcConfigurer This change makes it possible to provide a custom MessageCodesResolver through the MVC Java config whether using @EnableWebMvc and extending WebMVcConfigurerAdapter or sub-classing directly from WebMvcConfigurationSupport. Issue: SPR-9223
spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportTests.java
@@ -40,7 +40,9 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.stereotype.Controller; import org.springframework.validation.BeanPropertyBindingResult; +import org.springframework.validation.DefaultMessageCodesResolver; import org.springframework.validation.Errors; +import org.springframework.validation.MessageCodesResolver; import org.springframework.validation.Validator; import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; import org.springframework.web.bind.annotation.RequestMapping; @@ -190,6 +192,9 @@ public void webMvcConfigurerExtensionHooks() throws Exception { initializer.getValidator().validate(null, bindingResult); assertEquals("invalid", bindingResult.getAllErrors().get(0).getCode()); + String[] codes = initializer.getMessageCodesResolver().resolveMessageCodes("invalid", null); + assertEquals("custom.invalid", codes[0]); + @SuppressWarnings("unchecked") List<HandlerMethodArgumentResolver> argResolvers= (List<HandlerMethodArgumentResolver>) new DirectFieldAccessor(adapter).getPropertyValue("customArgumentResolvers"); @@ -248,8 +253,11 @@ private static class TestWebMvcConfiguration extends WebMvcConfigurationSupport } /** - * The purpose of this class is to test that an implementation of a {@link WebMvcConfigurer} - * can also apply customizations by extension from {@link WebMvcConfigurationSupport}. + * Since WebMvcConfigurationSupport does not implement WebMvcConfigurer, the purpose + * of this test class is also to ensure the two are in sync with each other. Effectively + * that ensures that application config classes that use the combo {@code @EnableWebMvc} + * plus WebMvcConfigurer can switch to extending WebMvcConfigurationSupport directly for + * more advanced configuration needs. */ private class WebConfig extends WebMvcConfigurationSupport implements WebMvcConfigurer { @@ -299,6 +307,17 @@ public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LocaleChangeInterceptor()); } + @SuppressWarnings("serial") + @Override + public MessageCodesResolver getMessageCodesResolver() { + return new DefaultMessageCodesResolver() { + @Override + public String[] resolveMessageCodes(String errorCode, String objectName) { + return new String[] { "custom." + errorCode }; + } + }; + } + @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/path"); @@ -313,6 +332,7 @@ public void addResourceHandlers(ResourceHandlerRegistry registry) { public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable("default"); } + } }
true
Other
spring-projects
spring-framework
2af294ab26b670c7f997054ab11ecf7402fee6ed.json
Add MessageCodesResolver hook to WebMvcConfigurer This change makes it possible to provide a custom MessageCodesResolver through the MVC Java config whether using @EnableWebMvc and extending WebMVcConfigurerAdapter or sub-classing directly from WebMvcConfigurationSupport. Issue: SPR-9223
src/dist/changelog.txt
@@ -25,6 +25,7 @@ Changes in version 3.2 M1 * support access to all URI vars via @PathVariable Map<String, String> * add "excludedExceptions" property to SimpleUrlHandlerMapping * add CompositeRequestCondition for use with multiple custom request mapping conditions +* add option to configure custom MessageCodesResolver through WebMvcConfigurer Changes in version 3.1.1 (2012-02-16) -------------------------------------
true
Other
spring-projects
spring-framework
9c223c178055829c778fc28a5082fa0338a68ca1.json
Fix broken link to JavaBean customization tutorial Issue: SPR-9408
src/reference/docbook/validation.xml
@@ -603,7 +603,7 @@ Float salary = (Float) company.getPropertyValue("managingDirector.salary");]]></ <para>Note that you can also use the standard <interfacename>BeanInfo</interfacename> JavaBeans mechanism here as well (described <ulink - url="http://java.sun.com/docs/books/tutorial/javabeans/customization/index.html" + url="http://docs.oracle.com/javase/tutorial/javabeans/advanced/customization.html" >in not-amazing-detail here</ulink>). Find below an example of using the <interfacename>BeanInfo</interfacename> mechanism for explicitly registering one or more <interfacename>PropertyEditor</interfacename>
false
Other
spring-projects
spring-framework
19aceebb961bd7fe24477a8e15830c668f519385.json
Fix broken javadoc link to ROME tools project Issue: SPR-9379
spring-web/src/main/java/org/springframework/http/converter/feed/AbstractWireFeedHttpMessageConverter.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. @@ -37,8 +37,8 @@ import org.springframework.util.StringUtils; /** - * Abstract base class for Atom and RSS Feed message converters, using java.net's - * <a href="https://rome.dev.java.net/">ROME</a> package. + * Abstract base class for Atom and RSS Feed message converters, using the + * <a href="http://rometools.org/">ROME tools</a> project. * * @author Arjen Poutsma * @since 3.0.2
false
Other
spring-projects
spring-framework
2ff43726be693f32b7bf2a6d237ab65f8ce84ba6.json
Restore serializability of HttpStatusCodeException SPR-7591 introduced a java.nio.charset.Charset field within HttpStatusCodeException. The former is non-serializable, thus by extension the latter also became non-serializable. Because the Charset field is only used for outputting the charset name in HttpStatusCodeException#getResponseBodyAsString, it is reasonable to store the value returned by Charset#name() instead of the actual Charset object itself. This commit refactors HttpStatusCodeException's responseCharset field to be of type String instead of Charset and adds tests to prove that HttpStatusCodeException objects are once again serializable as expected. Issue: SPR-9273, SPR-7591
spring-web/src/main/java/org/springframework/web/client/HttpClientErrorException.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. @@ -29,6 +29,8 @@ */ public class HttpClientErrorException extends HttpStatusCodeException { + private static final long serialVersionUID = 6777393766937023392L; + /** * Construct a new instance of {@code HttpClientErrorException} based on a {@link HttpStatus}. * @param statusCode the status code
true
Other
spring-projects
spring-framework
2ff43726be693f32b7bf2a6d237ab65f8ce84ba6.json
Restore serializability of HttpStatusCodeException SPR-7591 introduced a java.nio.charset.Charset field within HttpStatusCodeException. The former is non-serializable, thus by extension the latter also became non-serializable. Because the Charset field is only used for outputting the charset name in HttpStatusCodeException#getResponseBodyAsString, it is reasonable to store the value returned by Charset#name() instead of the actual Charset object itself. This commit refactors HttpStatusCodeException's responseCharset field to be of type String instead of Charset and adds tests to prove that HttpStatusCodeException objects are once again serializable as expected. Issue: SPR-9273, SPR-7591
spring-web/src/main/java/org/springframework/web/client/HttpServerErrorException.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. @@ -29,6 +29,8 @@ */ public class HttpServerErrorException extends HttpStatusCodeException { + private static final long serialVersionUID = -2565832100451369997L; + /** * Construct a new instance of {@code HttpServerErrorException} based on a {@link HttpStatus}. *
true
Other
spring-projects
spring-framework
2ff43726be693f32b7bf2a6d237ab65f8ce84ba6.json
Restore serializability of HttpStatusCodeException SPR-7591 introduced a java.nio.charset.Charset field within HttpStatusCodeException. The former is non-serializable, thus by extension the latter also became non-serializable. Because the Charset field is only used for outputting the charset name in HttpStatusCodeException#getResponseBodyAsString, it is reasonable to store the value returned by Charset#name() instead of the actual Charset object itself. This commit refactors HttpStatusCodeException's responseCharset field to be of type String instead of Charset and adds tests to prove that HttpStatusCodeException objects are once again serializable as expected. Issue: SPR-9273, SPR-7591
spring-web/src/main/java/org/springframework/web/client/HttpStatusCodeException.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. @@ -25,19 +25,22 @@ * Abstract base class for exceptions based on an {@link HttpStatus}. * * @author Arjen Poutsma + * @author Chris Beams * @since 3.0 */ public abstract class HttpStatusCodeException extends RestClientException { - private static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1"); + private static final long serialVersionUID = 1549626836533638803L; + + private static final String DEFAULT_CHARSET = "ISO-8859-1"; private final HttpStatus statusCode; private final String statusText; private final byte[] responseBody; - private final Charset responseCharset; + private final String responseCharset; /** * Construct a new instance of {@code HttpStatusCodeException} based on a {@link HttpStatus}. @@ -76,7 +79,7 @@ protected HttpStatusCodeException(HttpStatus statusCode, this.statusCode = statusCode; this.statusText = statusText; this.responseBody = responseBody != null ? responseBody : new byte[0]; - this.responseCharset = responseCharset != null ? responseCharset : DEFAULT_CHARSET; + this.responseCharset = responseCharset != null ? responseCharset.name() : DEFAULT_CHARSET; } /** @@ -109,7 +112,7 @@ public byte[] getResponseBodyAsByteArray() { */ public String getResponseBodyAsString() { try { - return new String(responseBody, responseCharset.name()); + return new String(responseBody, responseCharset); } catch (UnsupportedEncodingException ex) { // should not occur
true
Other
spring-projects
spring-framework
2ff43726be693f32b7bf2a6d237ab65f8ce84ba6.json
Restore serializability of HttpStatusCodeException SPR-7591 introduced a java.nio.charset.Charset field within HttpStatusCodeException. The former is non-serializable, thus by extension the latter also became non-serializable. Because the Charset field is only used for outputting the charset name in HttpStatusCodeException#getResponseBodyAsString, it is reasonable to store the value returned by Charset#name() instead of the actual Charset object itself. This commit refactors HttpStatusCodeException's responseCharset field to be of type String instead of Charset and adds tests to prove that HttpStatusCodeException objects are once again serializable as expected. Issue: SPR-9273, SPR-7591
spring-web/src/test/java/org/springframework/web/client/HttpStatusCodeExceptionTests.java
@@ -0,0 +1,57 @@ +/* + * 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.web.client; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.nio.charset.Charset; + +import org.junit.Test; +import org.springframework.http.HttpStatus; + +import static org.hamcrest.CoreMatchers.*; + +import static org.junit.Assert.*; + +/** + * Unit tests for {@link HttpStatusCodeException} and subclasses. + * + * @author Chris Beams + */ +public class HttpStatusCodeExceptionTests { + + /** + * Corners bug SPR-9273, which reported the fact that following the changes made in + * SPR-7591, {@link HttpStatusCodeException} and subtypes became no longer + * serializable due to the addition of a non-serializable {@link Charset} field. + */ + @Test + public void testSerializability() throws IOException, ClassNotFoundException { + HttpStatusCodeException ex1 = new HttpClientErrorException( + HttpStatus.BAD_REQUEST, null, null, Charset.forName("US-ASCII")); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + new ObjectOutputStream(out).writeObject(ex1); + ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); + HttpStatusCodeException ex2 = + (HttpStatusCodeException) new ObjectInputStream(in).readObject(); + assertThat(ex2.getResponseBodyAsString(), equalTo(ex1.getResponseBodyAsString())); + } + +}
true
Other
spring-projects
spring-framework
9a856c09f322b8ae821ff5e6a86dc0b0aeaf618d.json
Clarify @EnableScheduling javadoc It is now advised that destroyMethod="shutdown" should be used on @Bean methods returning an ExecutorService. Issue: SPR-9280
spring-context/src/main/java/org/springframework/scheduling/annotation/EnableScheduling.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 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. @@ -105,12 +105,16 @@ * taskRegistrar.setScheduler(taskExecutor()); * } * - * &#064;Bean + * &#064;Bean(destroyMethod="shutdown") * public Executor taskExecutor() { * return Executors.newScheduledThreadPool(100); * } * }</pre> * + * Note in the example above the use of {@code @Bean(destroyMethod="shutdown")}. This + * ensures that the task executor is properly shut down when the Spring application + * context itself is closed. + * * Implementing {@code SchedulingConfigurer} also allows for fine-grained * control over task registration via the {@code ScheduledTaskRegistrar}. * For example, the following configures the execution of a particular bean @@ -133,7 +137,7 @@ * ); * } * - * &#064;Bean + * &#064;Bean(destroyMethod="shutdown") * public Executor taskScheduler() { * return Executors.newScheduledThreadPool(42); * }
false
Other
spring-projects
spring-framework
ab2949f2b7149db155cdee661a4ce1baf3362ef0.json
Fix ResolvableType hashCode generation Fix ResolvableType.hashCode() to use the source of the variable resolver, rather than the resolver itself.
spring-core/src/main/java/org/springframework/core/ResolvableType.java
@@ -690,7 +690,8 @@ public boolean equals(Object obj) { @Override public int hashCode() { int hashCode = ObjectUtils.nullSafeHashCode(this.type); - hashCode = hashCode * 31 + ObjectUtils.nullSafeHashCode(this.variableResolver); + hashCode = hashCode * 31 + ObjectUtils.nullSafeHashCode( + this.variableResolver == null ? null : this.variableResolver.getSource()); hashCode = hashCode * 31 + ObjectUtils.nullSafeHashCode(this.componentType); return hashCode; }
false
Other
spring-projects
spring-framework
69238ba66f19279de7e1a0e2ddd69fbb9fd0de05.json
Move WebSocketExtension to top-level package
spring-websocket/src/main/java/org/springframework/web/socket/WebSocketExtension.java
@@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.web.socket.support; +package org.springframework.web.socket; import java.util.ArrayList; import java.util.Collections;
true
Other
spring-projects
spring-framework
69238ba66f19279de7e1a0e2ddd69fbb9fd0de05.json
Move WebSocketExtension to top-level package
spring-websocket/src/main/java/org/springframework/web/socket/WebSocketSession.java
@@ -24,7 +24,6 @@ import java.util.Map; import org.springframework.http.HttpHeaders; -import org.springframework.web.socket.support.WebSocketExtension; /** * A WebSocket session abstraction. Allows sending messages over a WebSocket connection
true
Other
spring-projects
spring-framework
69238ba66f19279de7e1a0e2ddd69fbb9fd0de05.json
Move WebSocketExtension to top-level package
spring-websocket/src/main/java/org/springframework/web/socket/adapter/JettyWebSocketSession.java
@@ -32,7 +32,7 @@ import org.springframework.web.socket.PingMessage; import org.springframework.web.socket.PongMessage; import org.springframework.web.socket.TextMessage; -import org.springframework.web.socket.support.WebSocketExtension; +import org.springframework.web.socket.WebSocketExtension; import org.springframework.web.socket.WebSocketSession; /**
true
Other
spring-projects
spring-framework
69238ba66f19279de7e1a0e2ddd69fbb9fd0de05.json
Move WebSocketExtension to top-level package
spring-websocket/src/main/java/org/springframework/web/socket/adapter/StandardWebSocketSession.java
@@ -36,7 +36,7 @@ import org.springframework.web.socket.PongMessage; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; -import org.springframework.web.socket.support.WebSocketExtension; +import org.springframework.web.socket.WebSocketExtension; /** * A {@link WebSocketSession} for use with the standard WebSocket for Java API.
true
Other
spring-projects
spring-framework
69238ba66f19279de7e1a0e2ddd69fbb9fd0de05.json
Move WebSocketExtension to top-level package
spring-websocket/src/main/java/org/springframework/web/socket/client/AbstractWebSocketClient.java
@@ -30,7 +30,7 @@ import org.springframework.util.concurrent.ListenableFuture; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketSession; -import org.springframework.web.socket.support.WebSocketExtension; +import org.springframework.web.socket.WebSocketExtension; import org.springframework.web.socket.support.WebSocketHttpHeaders; import org.springframework.web.util.UriComponentsBuilder;
true
Other
spring-projects
spring-framework
69238ba66f19279de7e1a0e2ddd69fbb9fd0de05.json
Move WebSocketExtension to top-level package
spring-websocket/src/main/java/org/springframework/web/socket/client/endpoint/StandardWebSocketClient.java
@@ -40,7 +40,7 @@ import org.springframework.web.socket.adapter.StandardWebSocketHandlerAdapter; import org.springframework.web.socket.adapter.StandardWebSocketSession; import org.springframework.web.socket.client.AbstractWebSocketClient; -import org.springframework.web.socket.support.WebSocketExtension; +import org.springframework.web.socket.WebSocketExtension; /** * Initiates WebSocket requests to a WebSocket server programatically through the standard
true
Other
spring-projects
spring-framework
69238ba66f19279de7e1a0e2ddd69fbb9fd0de05.json
Move WebSocketExtension to top-level package
spring-websocket/src/main/java/org/springframework/web/socket/client/jetty/JettyWebSocketClient.java
@@ -38,7 +38,7 @@ import org.springframework.web.socket.adapter.JettyWebSocketHandlerAdapter; import org.springframework.web.socket.adapter.JettyWebSocketSession; import org.springframework.web.socket.client.AbstractWebSocketClient; -import org.springframework.web.socket.support.WebSocketExtension; +import org.springframework.web.socket.WebSocketExtension; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder;
true
Other
spring-projects
spring-framework
69238ba66f19279de7e1a0e2ddd69fbb9fd0de05.json
Move WebSocketExtension to top-level package
spring-websocket/src/main/java/org/springframework/web/socket/server/RequestUpgradeStrategy.java
@@ -21,7 +21,7 @@ import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; -import org.springframework.web.socket.support.WebSocketExtension; +import org.springframework.web.socket.WebSocketExtension; import org.springframework.web.socket.WebSocketHandler; /**
true