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
9f5fd3afcf7196dcae1ba5813f78561f9ee0f0a1.json
Normalize indentation of Apache license URL In accordance with recommendations at http://www.apache.org/licenses/LICENSE-2.0.html. A number of classes had strayed from this format, now all are the same.
org.springframework.context/src/test/java/test/beans/CustomScope.java
@@ -5,7 +5,7 @@ * 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 + * 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,
true
Other
spring-projects
spring-framework
9f5fd3afcf7196dcae1ba5813f78561f9ee0f0a1.json
Normalize indentation of Apache license URL In accordance with recommendations at http://www.apache.org/licenses/LICENSE-2.0.html. A number of classes had strayed from this format, now all are the same.
org.springframework.core/src/main/java/org/springframework/core/env/AbstractEnvironment.java
@@ -5,7 +5,7 @@ * 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 + * 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,
true
Other
spring-projects
spring-framework
9f5fd3afcf7196dcae1ba5813f78561f9ee0f0a1.json
Normalize indentation of Apache license URL In accordance with recommendations at http://www.apache.org/licenses/LICENSE-2.0.html. A number of classes had strayed from this format, now all are the same.
org.springframework.core/src/test/java/org/springframework/core/env/DefaultEnvironmentTests.java
@@ -5,7 +5,7 @@ * 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 + * 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,
true
Other
spring-projects
spring-framework
9f5fd3afcf7196dcae1ba5813f78561f9ee0f0a1.json
Normalize indentation of Apache license URL In accordance with recommendations at http://www.apache.org/licenses/LICENSE-2.0.html. A number of classes had strayed from this format, now all are the same.
org.springframework.expression/src/main/java/org/springframework/expression/common/TemplateAwareExpressionParser.java
@@ -1 +1 @@ -/* * Copyright 2002-2009 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.expression.common; import java.util.LinkedList; import java.util.List; import java.util.Stack; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.ParseException; import org.springframework.expression.ParserContext; /** * An expression parser that understands templates. It can be subclassed * by expression parsers that do not offer first class support for templating. * * @author Keith Donald * @author Juergen Hoeller * @author Andy Clement * @since 3.0 */ public abstract class TemplateAwareExpressionParser implements ExpressionParser { /** * Default ParserContext instance for non-template expressions. */ private static final ParserContext NON_TEMPLATE_PARSER_CONTEXT = new ParserContext() { public String getExpressionPrefix() { return null; } public String getExpressionSuffix() { return null; } public boolean isTemplate() { return false; } }; public Expression parseExpression(String expressionString) throws ParseException { return parseExpression(expressionString, NON_TEMPLATE_PARSER_CONTEXT); } public Expression parseExpression(String expressionString, ParserContext context) throws ParseException { if (context == null) { context = NON_TEMPLATE_PARSER_CONTEXT; } if (context.isTemplate()) { return parseTemplate(expressionString, context); } else { return doParseExpression(expressionString, context); } } private Expression parseTemplate(String expressionString, ParserContext context) throws ParseException { if (expressionString.length() == 0) { return new LiteralExpression(""); } Expression[] expressions = parseExpressions(expressionString, context); if (expressions.length == 1) { return expressions[0]; } else { return new CompositeStringExpression(expressionString, expressions); } } /** * Helper that parses given expression string using the configured parser. The expression string can contain any * number of expressions all contained in "${...}" markers. For instance: "foo${expr0}bar${expr1}". The static * pieces of text will also be returned as Expressions that just return that static piece of text. As a result, * evaluating all returned expressions and concatenating the results produces the complete evaluated string. * Unwrapping is only done of the outermost delimiters found, so the string 'hello ${foo${abc}}' would break into * the pieces 'hello ' and 'foo${abc}'. This means that expression languages that used ${..} as part of their * functionality are supported without any problem. * The parsing is aware of the structure of an embedded expression. It assumes that parentheses '(', * square brackets '[' and curly brackets '}' must be in pairs within the expression unless they are within a * string literal and a string literal starts and terminates with a single quote '. * * @param expressionString the expression string * @return the parsed expressions * @throws ParseException when the expressions cannot be parsed */ private Expression[] parseExpressions(String expressionString, ParserContext context) throws ParseException { List<Expression> expressions = new LinkedList<Expression>(); String prefix = context.getExpressionPrefix(); String suffix = context.getExpressionSuffix(); int startIdx = 0; while (startIdx < expressionString.length()) { int prefixIndex = expressionString.indexOf(prefix,startIdx); if (prefixIndex >= startIdx) { // an inner expression was found - this is a composite if (prefixIndex > startIdx) { expressions.add(createLiteralExpression(context,expressionString.substring(startIdx, prefixIndex))); } int afterPrefixIndex = prefixIndex + prefix.length(); int suffixIndex = skipToCorrectEndSuffix(prefix,suffix,expressionString,afterPrefixIndex); if (suffixIndex == -1) { throw new ParseException(expressionString, prefixIndex, "No ending suffix '" + suffix + "' for expression starting at character " + prefixIndex + ": " + expressionString.substring(prefixIndex)); } if (suffixIndex == afterPrefixIndex) { throw new ParseException(expressionString, prefixIndex, "No expression defined within delimiter '" + prefix + suffix + "' at character " + prefixIndex); } else { String expr = expressionString.substring(prefixIndex + prefix.length(), suffixIndex); expr = expr.trim(); if (expr.length()==0) { throw new ParseException(expressionString, prefixIndex, "No expression defined within delimiter '" + prefix + suffix + "' at character " + prefixIndex); } expressions.add(doParseExpression(expr, context)); startIdx = suffixIndex + suffix.length(); } } else { // no more ${expressions} found in string, add rest as static text expressions.add(createLiteralExpression(context,expressionString.substring(startIdx))); startIdx = expressionString.length(); } } return expressions.toArray(new Expression[expressions.size()]); } private Expression createLiteralExpression(ParserContext context, String text) { return new LiteralExpression(text); } /** * Return true if the specified suffix can be found at the supplied position in the supplied expression string. * @param expressionString the expression string which may contain the suffix * @param pos the start position at which to check for the suffix * @param suffix the suffix string * @return */ private boolean isSuffixHere(String expressionString,int pos,String suffix) { int suffixPosition = 0; for (int i=0;i<suffix.length() && pos<expressionString.length();i++) { if (expressionString.charAt(pos++)!=suffix.charAt(suffixPosition++)) { return false; } } if (suffixPosition!=suffix.length()) { // the expressionString ran out before the suffix could entirely be found return false; } return true; } /** * Copes with nesting, for example '${...${...}}' where the correct end for the first ${ is the final }. * * @param prefix the prefix * @param suffix the suffix * @param expressionString the expression string * @param afterPrefixIndex the most recently found prefix location for which the matching end suffix is being sought * @return the position of the correct matching nextSuffix or -1 if none can be found */ private int skipToCorrectEndSuffix(String prefix, String suffix, String expressionString, int afterPrefixIndex) throws ParseException { // Chew on the expression text - relying on the rules: // brackets must be in pairs: () [] {} // string literals are "..." or '...' and these may contain unmatched brackets int pos = afterPrefixIndex; int maxlen = expressionString.length(); int nextSuffix = expressionString.indexOf(suffix,afterPrefixIndex); if (nextSuffix ==-1 ) { return -1; // the suffix is missing } Stack<Bracket> stack = new Stack<Bracket>(); while (pos<maxlen) { if (isSuffixHere(expressionString,pos,suffix) && stack.isEmpty()) { break; } char ch = expressionString.charAt(pos); switch (ch) { case '{': case '[': case '(': stack.push(new Bracket(ch,pos)); break; case '}':case ']':case ')': if (stack.isEmpty()) { throw new ParseException(expressionString, pos, "Found closing '"+ch+"' at position "+pos+" without an opening '"+Bracket.theOpenBracketFor(ch)+"'"); } Bracket p = stack.pop(); if (!p.compatibleWithCloseBracket(ch)) { throw new ParseException(expressionString, pos, "Found closing '"+ch+"' at position "+pos+" but most recent opening is '"+p.bracket+"' at position "+p.pos); } break; case '\'': case '"': // jump to the end of the literal int endLiteral = expressionString.indexOf(ch,pos+1); if (endLiteral==-1) { throw new ParseException(expressionString, pos, "Found non terminating string literal starting at position "+pos); } pos=endLiteral; break; } pos++; } if (!stack.isEmpty()) { Bracket p = stack.pop(); throw new ParseException(expressionString, p.pos, "Missing closing '"+Bracket.theCloseBracketFor(p.bracket)+"' for '"+p.bracket+"' at position "+p.pos); } if (!isSuffixHere(expressionString, pos, suffix)) { return -1; } return pos; } /** * This captures a type of bracket and the position in which it occurs in the expression. The positional * information is used if an error has to be reported because the related end bracket cannot be found. * Bracket is used to describe: square brackets [] round brackets () and curly brackets {} */ private static class Bracket { char bracket; int pos; Bracket(char bracket,int pos) { this.bracket = bracket; this.pos = pos; } boolean compatibleWithCloseBracket(char closeBracket) { if (bracket=='{') { return closeBracket=='}'; } else if (bracket=='[') { return closeBracket==']'; } return closeBracket==')'; } static char theOpenBracketFor(char closeBracket) { if (closeBracket=='}') { return '{'; } else if (closeBracket==']') { return '['; } return '('; } static char theCloseBracketFor(char openBracket) { if (openBracket=='{') { return '}'; } else if (openBracket=='[') { return ']'; } return ')'; } } /** * Actually parse the expression string and return an Expression object. * @param expressionString the raw expression string to parse * @param context a context for influencing this expression parsing routine (optional) * @return an evaluator for the parsed expression * @throws ParseException an exception occurred during parsing */ protected abstract Expression doParseExpression(String expressionString, ParserContext context) throws ParseException; } \ No newline at end of file +/* 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.expression.common; import java.util.LinkedList; import java.util.List; import java.util.Stack; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.ParseException; import org.springframework.expression.ParserContext; /** * An expression parser that understands templates. It can be subclassed * by expression parsers that do not offer first class support for templating. * * @author Keith Donald * @author Juergen Hoeller * @author Andy Clement * @since 3.0 */ public abstract class TemplateAwareExpressionParser implements ExpressionParser { /** * Default ParserContext instance for non-template expressions. */ private static final ParserContext NON_TEMPLATE_PARSER_CONTEXT = new ParserContext() { public String getExpressionPrefix() { return null; } public String getExpressionSuffix() { return null; } public boolean isTemplate() { return false; } }; public Expression parseExpression(String expressionString) throws ParseException { return parseExpression(expressionString, NON_TEMPLATE_PARSER_CONTEXT); } public Expression parseExpression(String expressionString, ParserContext context) throws ParseException { if (context == null) { context = NON_TEMPLATE_PARSER_CONTEXT; } if (context.isTemplate()) { return parseTemplate(expressionString, context); } else { return doParseExpression(expressionString, context); } } private Expression parseTemplate(String expressionString, ParserContext context) throws ParseException { if (expressionString.length() == 0) { return new LiteralExpression(""); } Expression[] expressions = parseExpressions(expressionString, context); if (expressions.length == 1) { return expressions[0]; } else { return new CompositeStringExpression(expressionString, expressions); } } /** * Helper that parses given expression string using the configured parser. The expression string can contain any * number of expressions all contained in "${...}" markers. For instance: "foo${expr0}bar${expr1}". The static * pieces of text will also be returned as Expressions that just return that static piece of text. As a result, * evaluating all returned expressions and concatenating the results produces the complete evaluated string. * Unwrapping is only done of the outermost delimiters found, so the string 'hello ${foo${abc}}' would break into * the pieces 'hello ' and 'foo${abc}'. This means that expression languages that used ${..} as part of their * functionality are supported without any problem. * The parsing is aware of the structure of an embedded expression. It assumes that parentheses '(', * square brackets '[' and curly brackets '}' must be in pairs within the expression unless they are within a * string literal and a string literal starts and terminates with a single quote '. * * @param expressionString the expression string * @return the parsed expressions * @throws ParseException when the expressions cannot be parsed */ private Expression[] parseExpressions(String expressionString, ParserContext context) throws ParseException { List<Expression> expressions = new LinkedList<Expression>(); String prefix = context.getExpressionPrefix(); String suffix = context.getExpressionSuffix(); int startIdx = 0; while (startIdx < expressionString.length()) { int prefixIndex = expressionString.indexOf(prefix,startIdx); if (prefixIndex >= startIdx) { // an inner expression was found - this is a composite if (prefixIndex > startIdx) { expressions.add(createLiteralExpression(context,expressionString.substring(startIdx, prefixIndex))); } int afterPrefixIndex = prefixIndex + prefix.length(); int suffixIndex = skipToCorrectEndSuffix(prefix,suffix,expressionString,afterPrefixIndex); if (suffixIndex == -1) { throw new ParseException(expressionString, prefixIndex, "No ending suffix '" + suffix + "' for expression starting at character " + prefixIndex + ": " + expressionString.substring(prefixIndex)); } if (suffixIndex == afterPrefixIndex) { throw new ParseException(expressionString, prefixIndex, "No expression defined within delimiter '" + prefix + suffix + "' at character " + prefixIndex); } else { String expr = expressionString.substring(prefixIndex + prefix.length(), suffixIndex); expr = expr.trim(); if (expr.length()==0) { throw new ParseException(expressionString, prefixIndex, "No expression defined within delimiter '" + prefix + suffix + "' at character " + prefixIndex); } expressions.add(doParseExpression(expr, context)); startIdx = suffixIndex + suffix.length(); } } else { // no more ${expressions} found in string, add rest as static text expressions.add(createLiteralExpression(context,expressionString.substring(startIdx))); startIdx = expressionString.length(); } } return expressions.toArray(new Expression[expressions.size()]); } private Expression createLiteralExpression(ParserContext context, String text) { return new LiteralExpression(text); } /** * Return true if the specified suffix can be found at the supplied position in the supplied expression string. * @param expressionString the expression string which may contain the suffix * @param pos the start position at which to check for the suffix * @param suffix the suffix string * @return */ private boolean isSuffixHere(String expressionString,int pos,String suffix) { int suffixPosition = 0; for (int i=0;i<suffix.length() && pos<expressionString.length();i++) { if (expressionString.charAt(pos++)!=suffix.charAt(suffixPosition++)) { return false; } } if (suffixPosition!=suffix.length()) { // the expressionString ran out before the suffix could entirely be found return false; } return true; } /** * Copes with nesting, for example '${...${...}}' where the correct end for the first ${ is the final }. * * @param prefix the prefix * @param suffix the suffix * @param expressionString the expression string * @param afterPrefixIndex the most recently found prefix location for which the matching end suffix is being sought * @return the position of the correct matching nextSuffix or -1 if none can be found */ private int skipToCorrectEndSuffix(String prefix, String suffix, String expressionString, int afterPrefixIndex) throws ParseException { // Chew on the expression text - relying on the rules: // brackets must be in pairs: () [] {} // string literals are "..." or '...' and these may contain unmatched brackets int pos = afterPrefixIndex; int maxlen = expressionString.length(); int nextSuffix = expressionString.indexOf(suffix,afterPrefixIndex); if (nextSuffix ==-1 ) { return -1; // the suffix is missing } Stack<Bracket> stack = new Stack<Bracket>(); while (pos<maxlen) { if (isSuffixHere(expressionString,pos,suffix) && stack.isEmpty()) { break; } char ch = expressionString.charAt(pos); switch (ch) { case '{': case '[': case '(': stack.push(new Bracket(ch,pos)); break; case '}':case ']':case ')': if (stack.isEmpty()) { throw new ParseException(expressionString, pos, "Found closing '"+ch+"' at position "+pos+" without an opening '"+Bracket.theOpenBracketFor(ch)+"'"); } Bracket p = stack.pop(); if (!p.compatibleWithCloseBracket(ch)) { throw new ParseException(expressionString, pos, "Found closing '"+ch+"' at position "+pos+" but most recent opening is '"+p.bracket+"' at position "+p.pos); } break; case '\'': case '"': // jump to the end of the literal int endLiteral = expressionString.indexOf(ch,pos+1); if (endLiteral==-1) { throw new ParseException(expressionString, pos, "Found non terminating string literal starting at position "+pos); } pos=endLiteral; break; } pos++; } if (!stack.isEmpty()) { Bracket p = stack.pop(); throw new ParseException(expressionString, p.pos, "Missing closing '"+Bracket.theCloseBracketFor(p.bracket)+"' for '"+p.bracket+"' at position "+p.pos); } if (!isSuffixHere(expressionString, pos, suffix)) { return -1; } return pos; } /** * This captures a type of bracket and the position in which it occurs in the expression. The positional * information is used if an error has to be reported because the related end bracket cannot be found. * Bracket is used to describe: square brackets [] round brackets () and curly brackets {} */ private static class Bracket { char bracket; int pos; Bracket(char bracket,int pos) { this.bracket = bracket; this.pos = pos; } boolean compatibleWithCloseBracket(char closeBracket) { if (bracket=='{') { return closeBracket=='}'; } else if (bracket=='[') { return closeBracket==']'; } return closeBracket==')'; } static char theOpenBracketFor(char closeBracket) { if (closeBracket=='}') { return '{'; } else if (closeBracket==']') { return '['; } return '('; } static char theCloseBracketFor(char openBracket) { if (openBracket=='{') { return '}'; } else if (openBracket=='[') { return ']'; } return ')'; } } /** * Actually parse the expression string and return an Expression object. * @param expressionString the raw expression string to parse * @param context a context for influencing this expression parsing routine (optional) * @return an evaluator for the parsed expression * @throws ParseException an exception occurred during parsing */ protected abstract Expression doParseExpression(String expressionString, ParserContext context) throws ParseException; } \ No newline at end of file
true
Other
spring-projects
spring-framework
9f5fd3afcf7196dcae1ba5813f78561f9ee0f0a1.json
Normalize indentation of Apache license URL In accordance with recommendations at http://www.apache.org/licenses/LICENSE-2.0.html. A number of classes had strayed from this format, now all are the same.
org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java
@@ -5,7 +5,7 @@ * 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 + * 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,
true
Other
spring-projects
spring-framework
9f5fd3afcf7196dcae1ba5813f78561f9ee0f0a1.json
Normalize indentation of Apache license URL In accordance with recommendations at http://www.apache.org/licenses/LICENSE-2.0.html. A number of classes had strayed from this format, now all are the same.
org.springframework.web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java
@@ -5,7 +5,7 @@ * 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 + * 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,
true
Other
spring-projects
spring-framework
9f5fd3afcf7196dcae1ba5813f78561f9ee0f0a1.json
Normalize indentation of Apache license URL In accordance with recommendations at http://www.apache.org/licenses/LICENSE-2.0.html. A number of classes had strayed from this format, now all are the same.
org.springframework.web/src/main/java/org/springframework/web/context/support/AbstractRefreshableWebApplicationContext.java
@@ -5,7 +5,7 @@ * 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 + * 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,
true
Other
spring-projects
spring-framework
9f5fd3afcf7196dcae1ba5813f78561f9ee0f0a1.json
Normalize indentation of Apache license URL In accordance with recommendations at http://www.apache.org/licenses/LICENSE-2.0.html. A number of classes had strayed from this format, now all are the same.
org.springframework.web/src/main/java/org/springframework/web/context/support/GenericWebApplicationContext.java
@@ -5,7 +5,7 @@ * 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 + * 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,
true
Other
spring-projects
spring-framework
9f5fd3afcf7196dcae1ba5813f78561f9ee0f0a1.json
Normalize indentation of Apache license URL In accordance with recommendations at http://www.apache.org/licenses/LICENSE-2.0.html. A number of classes had strayed from this format, now all are the same.
org.springframework.web/src/main/java/org/springframework/web/context/support/StaticWebApplicationContext.java
@@ -5,7 +5,7 @@ * 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 + * 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,
true
Other
spring-projects
spring-framework
9f5fd3afcf7196dcae1ba5813f78561f9ee0f0a1.json
Normalize indentation of Apache license URL In accordance with recommendations at http://www.apache.org/licenses/LICENSE-2.0.html. A number of classes had strayed from this format, now all are the same.
org.springframework.web/src/main/java/org/springframework/web/filter/ShallowEtagHeaderFilter.java
@@ -5,7 +5,7 @@ * 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 + * 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,
true
Other
spring-projects
spring-framework
9f5fd3afcf7196dcae1ba5813f78561f9ee0f0a1.json
Normalize indentation of Apache license URL In accordance with recommendations at http://www.apache.org/licenses/LICENSE-2.0.html. A number of classes had strayed from this format, now all are the same.
org.springframework.web/src/test/java/org/springframework/web/filter/DelegatingFilterProxyTests.java
@@ -4,7 +4,7 @@ * 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 + * 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,
true
Other
spring-projects
spring-framework
9f5fd3afcf7196dcae1ba5813f78561f9ee0f0a1.json
Normalize indentation of Apache license URL In accordance with recommendations at http://www.apache.org/licenses/LICENSE-2.0.html. A number of classes had strayed from this format, now all are the same.
org.springframework.web/src/test/java/org/springframework/web/filter/ShallowEtagHeaderFilterTests.java
@@ -5,7 +5,7 @@ * 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 + * 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,
true
Other
spring-projects
spring-framework
f46a455c72370714a7494ff95bf9d4cd927ebac8.json
Eliminate PropertySourceAggregator interface
org.springframework.core/src/main/java/org/springframework/core/env/ConfigurableEnvironment.java
@@ -16,6 +16,10 @@ package org.springframework.core.env; +import java.util.LinkedList; +import java.util.Map; +import java.util.Properties; + import org.springframework.core.convert.ConversionService; /** @@ -24,19 +28,34 @@ * @author Chris Beams * @since 3.1 */ -public interface ConfigurableEnvironment extends Environment, PropertySourceAggregator { +public interface ConfigurableEnvironment extends Environment { - /** - * TODO SPR-7508: document - */ void setActiveProfiles(String... profiles); - /** - * TODO SPR-7508: document - */ void setDefaultProfiles(String... profiles); public ConversionService getConversionService(); public void setConversionService(ConversionService conversionService); + + void addPropertySource(PropertySource<?> propertySource); + + void addPropertySource(String name, Properties properties); + + void addPropertySource(String name, Map<String, String> propertiesMap); + + /** + * TODO: SPR-7508 document + * + * Care should be taken to ensure duplicates are not introduced. + * + * Recommend using {@link LinkedList#set(int, Object)} for replacing items, + * and combining {@link LinkedList#remove()} with other methods like + * {@link LinkedList#add(Object)} to prevent duplicates. + * + * Explain how {@link PropertySource#equals(Object)} and hashCode work, and that + * recommend using {@link PropertySource#named(String)} for lookups in the list. + */ + LinkedList<PropertySource<?>> getPropertySources(); + }
true
Other
spring-projects
spring-framework
f46a455c72370714a7494ff95bf9d4cd927ebac8.json
Eliminate PropertySourceAggregator interface
org.springframework.core/src/main/java/org/springframework/core/env/PropertySourceAggregator.java
@@ -1,51 +0,0 @@ -/* - * Copyright 2002-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.core.env; - -import java.util.LinkedList; -import java.util.Map; -import java.util.Properties; - -/** - * TODO: SPR-7508 document - * - * @author Chris Beams - * @since 3.1 - */ -public interface PropertySourceAggregator { - - void addPropertySource(PropertySource<?> propertySource); - - void addPropertySource(String name, Properties properties); - - void addPropertySource(String name, Map<String, String> propertiesMap); - - /** - * TODO: SPR-7508 document - * - * Care should be taken to ensure duplicates are not introduced. - * - * Recommend using {@link LinkedList#set(int, Object)} for replacing items, - * and combining {@link LinkedList#remove()} with other methods like - * {@link LinkedList#add(Object)} to prevent duplicates. - * - * Explain how {@link PropertySource#equals(Object)} and hashCode work, and that - * recommend using {@link PropertySource#named(String)} for lookups in the list. - */ - LinkedList<PropertySource<?>> getPropertySources(); - -}
true
Other
spring-projects
spring-framework
8770ea96b03106a06ee7ce401dc2fe39f419f816.json
Expose Environment ConfigurationService AbstractEnvironment delegates to an underlying ConfigurationService when processing methods such as getProperty(String name, Class<?> targetType) Accessor methods have been added to the ConfigurableEnvironment interface that allow this service to be updated or replaced.
org.springframework.core/src/main/java/org/springframework/core/env/AbstractEnvironment.java
@@ -69,7 +69,13 @@ public abstract class AbstractEnvironment implements ConfigurableEnvironment { new PropertyPlaceholderHelper(PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, VALUE_SEPARATOR, false); + public ConversionService getConversionService() { + return this.conversionService; + } + public void setConversionService(ConversionService conversionService) { + this.conversionService = conversionService; + } public void addPropertySource(PropertySource<?> propertySource) { propertySources.push(propertySource);
true
Other
spring-projects
spring-framework
8770ea96b03106a06ee7ce401dc2fe39f419f816.json
Expose Environment ConfigurationService AbstractEnvironment delegates to an underlying ConfigurationService when processing methods such as getProperty(String name, Class<?> targetType) Accessor methods have been added to the ConfigurableEnvironment interface that allow this service to be updated or replaced.
org.springframework.core/src/main/java/org/springframework/core/env/ConfigurableEnvironment.java
@@ -16,6 +16,8 @@ package org.springframework.core.env; +import org.springframework.core.convert.ConversionService; + /** * TODO SPR-7508: document * @@ -34,4 +36,7 @@ public interface ConfigurableEnvironment extends Environment, PropertySourceAggr */ void setDefaultProfiles(String... profiles); + public ConversionService getConversionService(); + + public void setConversionService(ConversionService conversionService); }
true
Other
spring-projects
spring-framework
b3e36a335d98945f8bf04ebb80ebe31664283720.json
Eliminate reserved 'default' profile (SPR-7778) There is no longer a reserved default profile named 'default'. Rather, users must explicitly specify a default profile or profiles via ConfigurableEnvironment.setDefaultProfiles(String...) - or - spring.profile.default="pD1,pD2" Per above, the setDefaultProfile(String) method now accepts a variable number of profile names (one or more). This is symmetrical with the existing setActiveProfiles(String...) method. A typical scenario might involve setting both a default profile as a servlet context property in web.xml and then setting an active profile when deploying to production.
org.springframework.beans/src/main/resources/org/springframework/beans/factory/xml/spring-beans-3.1.xsd
@@ -84,13 +84,13 @@ TODO:SPR-7508: Document profile annotation: * may be comma-delimited * empty profile means beans will always be registered - * profile="default" means that beans will be registered unless other profile(s) are active - * profile="xyz,default" means that beans will be registered if 'xyz' is active or if no profile is active - * ConfigurableEnvironment.setDefaultProfileName(String) customizes the name of the default profile - * 'spring.profile.default' property customizes the name of the default profile (usually for use as a * ConfigurableEnvironment.setActiveProfiles(String...) sets which profiles are active * 'spring.profile.active' sets which profiles are active (typically as a -D system property) servlet context/init param) + * ConfigurableEnvironment.setDefaultProfiles(String...) or 'spring.profile.default' property specifies one + or more default profiles, e.g., 'default' + * if 'default' is specified as a default profile, `profile="xyz,default"` means that beans will be + registered if 'xyz' is active or if no profile is active ]]></xsd:documentation> </xsd:annotation> </xsd:attribute>
true
Other
spring-projects
spring-framework
b3e36a335d98945f8bf04ebb80ebe31664283720.json
Eliminate reserved 'default' profile (SPR-7778) There is no longer a reserved default profile named 'default'. Rather, users must explicitly specify a default profile or profiles via ConfigurableEnvironment.setDefaultProfiles(String...) - or - spring.profile.default="pD1,pD2" Per above, the setDefaultProfile(String) method now accepts a variable number of profile names (one or more). This is symmetrical with the existing setActiveProfiles(String...) method. A typical scenario might involve setting both a default profile as a servlet context property in web.xml and then setting an active profile when deploying to production.
org.springframework.beans/src/test/java/org/springframework/beans/factory/xml/ProfileXmlBeanDefinitionTests.java
@@ -86,21 +86,11 @@ public void testProfilePermutations() { @Test public void testDefaultProfile() { - assertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, NONE_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, "other"), not(containsTargetBean())); - - assertThat(beanFactoryFor(DEFAULT_AND_DEV_ELIGIBLE_XML, DEV_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(DEFAULT_AND_DEV_ELIGIBLE_XML, NONE_ACTIVE), containsTargetBean()); - assertThat(beanFactoryFor(DEFAULT_AND_DEV_ELIGIBLE_XML, PROD_ACTIVE), not(containsTargetBean())); - } - - @Test - public void testCustomDefaultProfile() { { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory); ConfigurableEnvironment env = new DefaultEnvironment(); - env.setDefaultProfile("custom-default"); + env.setDefaultProfiles("custom-default"); reader.setEnvironment(env); reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_ELIGIBLE_XML, getClass())); @@ -110,14 +100,52 @@ public void testCustomDefaultProfile() { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory); ConfigurableEnvironment env = new DefaultEnvironment(); - env.setDefaultProfile("custom-default"); + env.setDefaultProfiles("custom-default"); reader.setEnvironment(env); reader.loadBeanDefinitions(new ClassPathResource(CUSTOM_DEFAULT_ELIGIBLE_XML, getClass())); assertThat(beanFactory, containsTargetBean()); } } + @Test + public void testDefaultAndNonDefaultProfile() { + assertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, NONE_ACTIVE), not(containsTargetBean())); + assertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, "other"), not(containsTargetBean())); + + { + DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); + XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory); + ConfigurableEnvironment env = new DefaultEnvironment(); + env.setActiveProfiles(DEV_ACTIVE); + env.setDefaultProfiles("default"); + reader.setEnvironment(env); + reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClass())); + assertThat(beanFactory, containsTargetBean()); + } + { + DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); + XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory); + ConfigurableEnvironment env = new DefaultEnvironment(); + // env.setActiveProfiles(DEV_ACTIVE); + env.setDefaultProfiles("default"); + reader.setEnvironment(env); + reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClass())); + assertThat(beanFactory, containsTargetBean()); + } + { + DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); + XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory); + ConfigurableEnvironment env = new DefaultEnvironment(); + // env.setActiveProfiles(DEV_ACTIVE); + //env.setDefaultProfiles("default"); + reader.setEnvironment(env); + reader.loadBeanDefinitions(new ClassPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClass())); + assertThat(beanFactory, not(containsTargetBean())); + } + } + + private BeanDefinitionRegistry beanFactoryFor(String xmlName, String... activeProfiles) { DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
true
Other
spring-projects
spring-framework
b3e36a335d98945f8bf04ebb80ebe31664283720.json
Eliminate reserved 'default' profile (SPR-7778) There is no longer a reserved default profile named 'default'. Rather, users must explicitly specify a default profile or profiles via ConfigurableEnvironment.setDefaultProfiles(String...) - or - spring.profile.default="pD1,pD2" Per above, the setDefaultProfile(String) method now accepts a variable number of profile names (one or more). This is symmetrical with the existing setActiveProfiles(String...) method. A typical scenario might involve setting both a default profile as a servlet context property in web.xml and then setting an active profile when deploying to production.
org.springframework.context/src/main/java/org/springframework/context/annotation/Profile.java
@@ -27,12 +27,13 @@ * TODO SPR-7508: document * * Components not @Profile-annotated will always be registered - * @Profile("default") means that beans will be registered unless other profile(s) are active - * @Profile({"xyz,default"}) means that beans will be registered if 'xyz' is active or if no profile is active - * ConfigurableEnvironment.setDefaultProfileName(String) customizes the name of the default profile - * 'spring.profile.default' property customizes the name of the default profile (usually for use as a servlet context/init param) * ConfigurableEnvironment.setActiveProfiles(String...) sets which profiles are active * 'spring.profile.active' sets which profiles are active (typically as a -D system property) + servlet context/init param) + * ConfigurableEnvironment.setDefaultProfiles(String...) or 'spring.profile.default' property specifies one + or more default profiles, e.g., 'default' + * if 'default' is specified as a default profile, @Profile({"xyz,default}) means that beans will be + registered if 'xyz' is active or if no profile is active * * @author Chris Beams * @since 3.1
true
Other
spring-projects
spring-framework
b3e36a335d98945f8bf04ebb80ebe31664283720.json
Eliminate reserved 'default' profile (SPR-7778) There is no longer a reserved default profile named 'default'. Rather, users must explicitly specify a default profile or profiles via ConfigurableEnvironment.setDefaultProfiles(String...) - or - spring.profile.default="pD1,pD2" Per above, the setDefaultProfile(String) method now accepts a variable number of profile names (one or more). This is symmetrical with the existing setActiveProfiles(String...) method. A typical scenario might involve setting both a default profile as a servlet context property in web.xml and then setting an active profile when deploying to production.
org.springframework.context/src/test/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProviderTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2010 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,7 +29,6 @@ import org.aspectj.lang.annotation.Aspect; import org.junit.Test; import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.core.env.AbstractEnvironment; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.DefaultEnvironment; import org.springframework.core.type.filter.AnnotationTypeFilter; @@ -59,6 +58,7 @@ public class ClassPathScanningCandidateComponentProviderTests { private static final String TEST_BASE_PACKAGE = "example.scannable"; private static final String TEST_PROFILE_PACKAGE = "example.profilescan"; + private static final String TEST_DEFAULT_PROFILE_NAME = "testDefault"; @Test @@ -219,6 +219,7 @@ public void testIntegrationWithAnnotationConfigApplicationContext_invalidProfile @Test public void testIntegrationWithAnnotationConfigApplicationContext_defaultProfile() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + ctx.getEnvironment().setDefaultProfiles(TEST_DEFAULT_PROFILE_NAME); // no active profiles are set ctx.register(DefaultProfileAnnotatedComponent.class); ctx.refresh(); @@ -231,20 +232,23 @@ public void testIntegrationWithAnnotationConfigApplicationContext_defaultAndDevP String beanName = DefaultAndDevProfileAnnotatedComponent.BEAN_NAME; { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + ctx.getEnvironment().setDefaultProfiles(TEST_DEFAULT_PROFILE_NAME); // no active profiles are set ctx.register(beanClass); ctx.refresh(); assertThat(ctx.containsBean(beanName), is(true)); } { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + ctx.getEnvironment().setDefaultProfiles(TEST_DEFAULT_PROFILE_NAME); ctx.getEnvironment().setActiveProfiles("dev"); ctx.register(beanClass); ctx.refresh(); assertThat(ctx.containsBean(beanName), is(true)); } { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + ctx.getEnvironment().setDefaultProfiles(TEST_DEFAULT_PROFILE_NAME); ctx.getEnvironment().setActiveProfiles("other"); ctx.register(beanClass); ctx.refresh(); @@ -263,13 +267,13 @@ private boolean containsBeanClass(Set<BeanDefinition> candidates, Class<?> beanC } - @Profile(AbstractEnvironment.DEFAULT_PROFILE_NAME) + @Profile(TEST_DEFAULT_PROFILE_NAME) @Component(DefaultProfileAnnotatedComponent.BEAN_NAME) private static class DefaultProfileAnnotatedComponent { static final String BEAN_NAME = "defaultProfileAnnotatedComponent"; } - @Profile({AbstractEnvironment.DEFAULT_PROFILE_NAME,"dev"}) + @Profile({TEST_DEFAULT_PROFILE_NAME,"dev"}) @Component(DefaultAndDevProfileAnnotatedComponent.BEAN_NAME) private static class DefaultAndDevProfileAnnotatedComponent { static final String BEAN_NAME = "defaultAndDevProfileAnnotatedComponent";
true
Other
spring-projects
spring-framework
b3e36a335d98945f8bf04ebb80ebe31664283720.json
Eliminate reserved 'default' profile (SPR-7778) There is no longer a reserved default profile named 'default'. Rather, users must explicitly specify a default profile or profiles via ConfigurableEnvironment.setDefaultProfiles(String...) - or - spring.profile.default="pD1,pD2" Per above, the setDefaultProfile(String) method now accepts a variable number of profile names (one or more). This is symmetrical with the existing setActiveProfiles(String...) method. A typical scenario might involve setting both a default profile as a servlet context property in web.xml and then setting an active profile when deploying to production.
org.springframework.core/src/main/java/org/springframework/core/env/AbstractEnvironment.java
@@ -40,6 +40,7 @@ import org.springframework.core.convert.support.ConversionServiceFactory; import org.springframework.util.PropertyPlaceholderHelper; import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver; +import org.springframework.util.StringUtils; /** @@ -51,32 +52,23 @@ public abstract class AbstractEnvironment implements ConfigurableEnvironment { public static final String ACTIVE_PROFILES_PROPERTY_NAME = "spring.profile.active"; + public static final String DEFAULT_PROFILES_PROPERTY_NAME = "spring.profile.default"; - public static final String DEFAULT_PROFILE_PROPERTY_NAME = "spring.profile.default"; + protected final Log logger = LogFactory.getLog(getClass()); - /** - * Default name of the default profile. Override with - * {@link #setDefaultProfile(String)}. - * - * @see #setDefaultProfile(String) - */ - public static final String DEFAULT_PROFILE_NAME = "default"; + private Set<String> activeProfiles = new LinkedHashSet<String>(); + private Set<String> defaultProfiles = new LinkedHashSet<String>(); - protected final Log logger = LogFactory.getLog(getClass()); + private LinkedList<PropertySource<?>> propertySources = new LinkedList<PropertySource<?>>(); + private ConversionService conversionService = ConversionServiceFactory.createDefaultConversionService(); private final PropertyPlaceholderHelper nonStrictHelper = new PropertyPlaceholderHelper(PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, VALUE_SEPARATOR, true); private final PropertyPlaceholderHelper strictHelper = new PropertyPlaceholderHelper(PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, VALUE_SEPARATOR, false); - private Set<String> activeProfiles = new LinkedHashSet<String>(); - private LinkedList<PropertySource<?>> propertySources = new LinkedList<PropertySource<?>>(); - private ConversionService conversionService = ConversionServiceFactory.createDefaultConversionService(); - private boolean explicitlySetProfiles; - - private String defaultProfile = DEFAULT_PROFILE_NAME; public void addPropertySource(PropertySource<?> propertySource) { @@ -187,26 +179,33 @@ public Properties asProperties() { } public Set<String> getActiveProfiles() { - doGetProfiles(); + if (this.activeProfiles.isEmpty()) { + String profiles = getProperty(ACTIVE_PROFILES_PROPERTY_NAME); + if (StringUtils.hasText(profiles)) { + this.activeProfiles = commaDelimitedListToSet(trimAllWhitespace(profiles)); + } + } return Collections.unmodifiableSet(activeProfiles); } - private void doGetProfiles() { - if (explicitlySetProfiles) - return; + public void setActiveProfiles(String... profiles) { + this.activeProfiles.clear(); + this.activeProfiles.addAll(Arrays.asList(profiles)); + } - String profiles = getProperty(ACTIVE_PROFILES_PROPERTY_NAME); - if (profiles == null || profiles.equals("")) { - return; + public Set<String> getDefaultProfiles() { + if (this.defaultProfiles.isEmpty()) { + String profiles = getProperty(DEFAULT_PROFILES_PROPERTY_NAME); + if (StringUtils.hasText(profiles)) { + this.defaultProfiles = commaDelimitedListToSet(profiles); + } } - - this.activeProfiles = commaDelimitedListToSet(trimAllWhitespace(profiles)); + return Collections.unmodifiableSet(this.defaultProfiles); } - public void setActiveProfiles(String... profiles) { - explicitlySetProfiles = true; - this.activeProfiles.clear(); - this.activeProfiles.addAll(Arrays.asList(profiles)); + public void setDefaultProfiles(String... profiles) { + this.defaultProfiles.clear(); + this.defaultProfiles.addAll(Arrays.asList(profiles)); } public Map<String, String> getSystemEnvironment() { @@ -282,28 +281,17 @@ public String resolveRequiredPlaceholders(String text) { public boolean acceptsProfiles(String[] specifiedProfiles) { boolean activeProfileFound = false; Set<String> activeProfiles = this.getActiveProfiles(); + Set<String> defaultProfiles = this.getDefaultProfiles(); for (String profile : specifiedProfiles) { if (activeProfiles.contains(profile) - || (activeProfiles.isEmpty() && profile.equals(this.getDefaultProfile()))) { + || (activeProfiles.isEmpty() && defaultProfiles.contains(profile))) { activeProfileFound = true; break; } } return activeProfileFound; } - public String getDefaultProfile() { - String defaultProfileProperty = getProperty(DEFAULT_PROFILE_PROPERTY_NAME); - if (defaultProfileProperty != null) { - return defaultProfileProperty; - } - return defaultProfile; - } - - public void setDefaultProfile(String defaultProfile) { - this.defaultProfile = defaultProfile; - } - private String doResolvePlaceholders(String text, PropertyPlaceholderHelper helper) { return helper.replacePlaceholders(text, new PlaceholderResolver() { public String resolvePlaceholder(String placeholderName) { @@ -314,8 +302,8 @@ public String resolvePlaceholder(String placeholderName) { @Override public String toString() { - return getClass().getSimpleName() + " [activeProfiles=" + activeProfiles - + ", propertySources=" + propertySources + "]"; + return String.format("%s [activeProfiles=%s, defaultProfiles=%s, propertySources=%s]", + getClass().getSimpleName(), activeProfiles, defaultProfiles, propertySources); } }
true
Other
spring-projects
spring-framework
b3e36a335d98945f8bf04ebb80ebe31664283720.json
Eliminate reserved 'default' profile (SPR-7778) There is no longer a reserved default profile named 'default'. Rather, users must explicitly specify a default profile or profiles via ConfigurableEnvironment.setDefaultProfiles(String...) - or - spring.profile.default="pD1,pD2" Per above, the setDefaultProfile(String) method now accepts a variable number of profile names (one or more). This is symmetrical with the existing setActiveProfiles(String...) method. A typical scenario might involve setting both a default profile as a servlet context property in web.xml and then setting an active profile when deploying to production.
org.springframework.core/src/main/java/org/springframework/core/env/ConfigurableEnvironment.java
@@ -30,10 +30,8 @@ public interface ConfigurableEnvironment extends Environment, PropertySourceAggr void setActiveProfiles(String... profiles); /** - * Set the default profile name to be used instead of 'default' - * - * @param defaultProfile + * TODO SPR-7508: document */ - void setDefaultProfile(String defaultProfile); + void setDefaultProfiles(String... profiles); }
true
Other
spring-projects
spring-framework
b3e36a335d98945f8bf04ebb80ebe31664283720.json
Eliminate reserved 'default' profile (SPR-7778) There is no longer a reserved default profile named 'default'. Rather, users must explicitly specify a default profile or profiles via ConfigurableEnvironment.setDefaultProfiles(String...) - or - spring.profile.default="pD1,pD2" Per above, the setDefaultProfile(String) method now accepts a variable number of profile names (one or more). This is symmetrical with the existing setActiveProfiles(String...) method. A typical scenario might involve setting both a default profile as a servlet context property in web.xml and then setting an active profile when deploying to production.
org.springframework.core/src/main/java/org/springframework/core/env/Environment.java
@@ -38,7 +38,7 @@ public interface Environment { /** * TODO SPR-7508: document */ - String getDefaultProfile(); + Set<String> getDefaultProfiles(); /** * TODO SPR-7508: document
true
Other
spring-projects
spring-framework
b3e36a335d98945f8bf04ebb80ebe31664283720.json
Eliminate reserved 'default' profile (SPR-7778) There is no longer a reserved default profile named 'default'. Rather, users must explicitly specify a default profile or profiles via ConfigurableEnvironment.setDefaultProfiles(String...) - or - spring.profile.default="pD1,pD2" Per above, the setDefaultProfile(String) method now accepts a variable number of profile names (one or more). This is symmetrical with the existing setActiveProfiles(String...) method. A typical scenario might involve setting both a default profile as a servlet context property in web.xml and then setting an active profile when deploying to production.
org.springframework.core/src/test/java/org/springframework/core/env/DefaultEnvironmentTests.java
@@ -25,12 +25,12 @@ import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.matchers.JUnitMatchers.hasItem; import static org.junit.matchers.JUnitMatchers.hasItems; import static org.springframework.core.env.AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME; -import static org.springframework.core.env.AbstractEnvironment.DEFAULT_PROFILE_NAME; -import static org.springframework.core.env.AbstractEnvironment.DEFAULT_PROFILE_PROPERTY_NAME; +import static org.springframework.core.env.AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME; import static org.springframework.core.env.DefaultEnvironmentTests.CollectionMatchers.isEmpty; import java.lang.reflect.Field; @@ -239,26 +239,28 @@ public void systemPropertiesResoloutionOfProfiles() { @Test public void systemPropertiesResoloutionOfMultipleProfiles() { assertThat(environment.getActiveProfiles(), isEmpty()); - System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, "foo,bar"); assertThat(environment.getActiveProfiles(), hasItems("foo", "bar")); + System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME); + } + @Test + public void systemPropertiesResolutionOfMulitpleProfiles_withWhitespace() { + assertThat(environment.getActiveProfiles(), isEmpty()); System.setProperty(ACTIVE_PROFILES_PROPERTY_NAME, " bar , baz "); // notice whitespace - assertThat(environment.getActiveProfiles(), not(hasItems("foo", "bar"))); assertThat(environment.getActiveProfiles(), hasItems("bar", "baz")); - System.getProperties().remove(ACTIVE_PROFILES_PROPERTY_NAME); } @Test public void environmentResolutionOfDefaultSpringProfileProperty_noneSet() { - assertThat(environment.getDefaultProfile(), equalTo(DEFAULT_PROFILE_NAME)); + assertThat(environment.getDefaultProfiles(), isEmpty()); } @Test public void environmentResolutionOfDefaultSpringProfileProperty_isSet() { - testProperties.setProperty(DEFAULT_PROFILE_PROPERTY_NAME, "custom-default"); - assertThat(environment.getDefaultProfile(), equalTo("custom-default")); + testProperties.setProperty(DEFAULT_PROFILES_PROPERTY_NAME, "custom-default"); + assertTrue(environment.getDefaultProfiles().contains("custom-default")); } @Test
true
Other
spring-projects
spring-framework
cfe1fdb5e596ccf977d8eaef60f2acb1fe700248.json
Add missing Hamcrest dependency
org.springframework.spring-parent/pom.xml
@@ -47,6 +47,12 @@ <version>4.7</version> <scope>test</scope> </dependency> + <dependency> + <groupId>org.hamcrest</groupId> + <artifactId>hamcrest-core</artifactId> + <version>1.2</version> + <scope>test</scope> + </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId>
false
Other
spring-projects
spring-framework
b73224427f296a1f016e0334bd189eb9e2bf3b2f.json
Add missing ROME dep
org.springframework.web/pom.xml
@@ -21,6 +21,11 @@ <version>3.2.1</version> <optional>true</optional> </dependency> + <dependency> + <groupId>rome</groupId> + <artifactId>rome</artifactId> + <version>0.9</version> + </dependency> <dependency> <groupId>javax.el</groupId> <artifactId>el-api</artifactId>
false
Other
spring-projects
spring-framework
cecee4d02bb44de6cdeb39270e586c7b9b0a7e92.json
Fix typo in validation chapter
spring-framework-reference/src/validation.xml
@@ -929,10 +929,10 @@ public interface ConverterFactory<S, R> { }]]></programlisting> - <para> Parameterize S to be type you are converting from and R to be base - type defining the <emphasis>range</emphasis> of classes you can convert - to. Then implement getConverter(Class&lt;T&gt;), where T is a subclass - of R. </para> + <para> Parameterize S to be the type you are converting from and R to be + the base type defining the <emphasis>range</emphasis> of classes you can + convert to. Then implement getConverter(Class&lt;T&gt;), where T is a + subclass of R. </para> <para> Consider the <classname>StringToEnum</classname> ConverterFactory as an example: </para>
false
Other
spring-projects
spring-framework
bda3d81bc9cda4ec8da79da3c45c6b2a5b6713bd.json
implement file resolution for isReadable() as well
org.springframework.core/src/main/java/org/springframework/core/io/AbstractFileResolvingResource.java
@@ -110,6 +110,24 @@ public boolean exists() { } } + @Override + public boolean isReadable() { + try { + URL url = getURL(); + if (ResourceUtils.isFileURL(url)) { + // Proceed with file system resolution... + File file = getFile(); + return (file.canRead() && !file.isDirectory()); + } + else { + return true; + } + } + catch (IOException ex) { + return false; + } + } + @Override public int contentLength() throws IOException { URL url = getURL();
false
Other
spring-projects
spring-framework
a8133a9917744ed656189dd7f553a7b1acfa1129.json
ignore empty statements (SPR-7363)
org.springframework.jdbc/src/main/java/org/springframework/jdbc/datasource/init/ResourceDatabasePopulator.java
@@ -239,31 +239,32 @@ private boolean containsSqlScriptDelimiters(String script, char delim) { } /** - * Split an SQL script into separate statements delimited with the provided delimiter character. Each individual - * statement will be added to the provided <code>List</code>. + * Split an SQL script into separate statements delimited with the provided delimiter character. + * Each individual statement will be added to the provided <code>List</code>. * @param script the SQL script - * @param delim character delimiting each statement - typically a ';' character + * @param delim character delimiting each statement (typically a ';' character) * @param statements the List that will contain the individual statements */ private void splitSqlScript(String script, char delim, List<String> statements) { StringBuilder sb = new StringBuilder(); boolean inLiteral = false; char[] content = script.toCharArray(); for (int i = 0; i < script.length(); i++) { - if (content[i] == '\'') { + char c = content[i]; + if (c == '\'') { inLiteral = !inLiteral; } - if (content[i] == delim && !inLiteral) { + if ((c == delim || c == '\n') && !inLiteral) { if (sb.length() > 0) { statements.add(sb.toString()); sb = new StringBuilder(); } } else { - sb.append(content[i]); + sb.append(c); } } - if (sb.length() > 0) { + if (StringUtils.hasText(sb)) { statements.add(sb.toString()); } }
false
Other
spring-projects
spring-framework
0625990020f232abc8ad9c82da804fa36e11a564.json
Add missing equals sign to code snippet (SPR-7339)
spring-framework-reference/src/orm.xml
@@ -675,7 +675,7 @@ TR: REVISED, PLS REVIEW.-->This declarative transaction capability allows you &lt;property name="sessionFactory" ref="mySessionFactory2"/&gt; &lt;/bean&gt; - &lt;bean id"myProductService" class="product.ProductServiceImpl"&gt; + &lt;bean id="myProductService" class="product.ProductServiceImpl"&gt; &lt;property name="productDao" ref="myProductDao"/&gt; &lt;property name="inventoryDao" ref="myInventoryDao"/&gt; &lt;/bean&gt;
false
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/aop.xml
@@ -468,8 +468,8 @@ private void anyOldTransfer() {}<lineannotation>// the pointcut signature</linea <classname>IllegalArgumentException</classname> being thrown.</para> <para>The set of pointcut designators supported by Spring AOP may be - extended in future releases both to support more of the AspectJ - pointcut designators.</para> + extended in future releases to support more of the AspectJ pointcut + designators.</para> </sidebar> <itemizedlist>
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/beans.xml
@@ -592,8 +592,8 @@ List userList service.getUsernameList(); always adequate, however. It is sometimes desirable to introduce an alias for a bean that is defined elsewhere. This is commonly the case in large systems where configuration is split amongst each subsystem, - each subsystem having its own set of object defintions. In XML-based - configuration metadata, you can use of the + each subsystem having its own set of object definitions. In XML-based + configuration metadata, you can use the <literal>&lt;alias/&gt;</literal> element to accomplish this.</para> <programlisting language="xml">&lt;alias name="fromName" alias="toName"/&gt;</programlisting> @@ -1994,14 +1994,14 @@ support=support@example.co.uk</programlisting> during development, without negating the option of switching to explicit wiring when the code base becomes more stable.</para> </listitem> - </itemizedlist><footnote> - <para>See <xref linkend="beans-factory-collaborators" /></para> - </footnote> When using XML-based configuration metadata, you specify - autowire mode for a bean definition with the <literal>autowire</literal> - attribute of the <literal>&lt;bean/&gt;</literal> element. The - autowiring functionality has five modes. You specify autowiring - <emphasis>per</emphasis> bean and thus can choose which ones to - autowire.</para> + </itemizedlist> + When using XML-based configuration metadata<footnote><para>See + <xref linkend="beans-factory-collaborators" /></para></footnote>, you + specify autowire mode for a bean definition with the + <literal>autowire</literal> attribute of the + <literal>&lt;bean/&gt;</literal> element. The autowiring functionality has + five modes. You specify autowiring <emphasis>per</emphasis> bean and thus + can choose which ones to autowire.</para> <table id="beans-factory-autowiring-modes-tbl"> <title>Autowiring modes</title> @@ -4544,9 +4544,9 @@ dataSource.url=jdbc:mysql:mydb</programlisting> <para>An alternative to XML setups is provided by annotation-based configuration which rely on the bytecode metadata for wiring up components - instead on angle-bracket declarations. Instead of using XML to describe a + instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component - class itself by using annotations on relevant class, method or field + class itself by using annotations on the relevant class, method, or field declaration. As mentioned in <xref linkend="beans-factory-extension-bpp-examples-rabpp" />, using a <interfacename>BeanPostProcessor</interfacename> in conjunction with
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/dynamic-languages.xml
@@ -223,7 +223,7 @@ http://www.springframework.org/schema/lang http://www.springframework.org/schema </sidebar> <para> The final step involves defining dynamic-language-backed bean definitions, - one for each bean that you want to configure (this is no different to + one for each bean that you want to configure (this is no different from normal JavaBean configuration). However, instead of specifying the fully qualified classname of the class that is to be instantiated and configured by the container, you use the <literal>&lt;lang:language/&gt;</literal>
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/ejb.xml
@@ -279,7 +279,8 @@ public void setMyComponent(MyComponent myComponent) { </para> <para> Consider an example Stateless Session bean which actually delegates - the implementation to a plain java service object. We have the business interface: + the implementation to a plain java service object. We have the business + interface: </para> <programlisting language="java"><![CDATA[public interface MyComponent { public void myMethod(...); @@ -335,24 +336,27 @@ public void setMyComponent(MyComponent myComponent) { passivated and reactivated as part of their lifecycle, and which use a non-serializable container instance (which is the normal case) will have to manually call <literal>unloadBeanFactory()</literal> and - <literal>loadBeanFactory</literal> from <literal>ejbPassivate</literal> - and <literal>ejbActivate</literal>, respectively, to unload and reload the + <literal>loadBeanFactory()</literal> from <literal>ejbPassivate()</literal> + and <literal>ejbActivate()</literal>, respectively, to unload and reload the BeanFactory on passivation and activation, since it can not be saved by the EJB container. </para> <para> - The default behavior of the <classname>ContextJndiBeanFactoryLocator</classname> - classes which is to load an <classname>ApplicationContext</classname> for the - use of the EJB is adequate for some situations. However, it is problematic when - the <classname>ApplicationContext</classname> is loading a number - of beans, or the initialization of those beans is time consuming or memory - intensive (such as a Hibernate <classname>SessionFactory</classname> initialization, for - example), since every EJB will have their own copy. In this case, the user - may want to override the default <classname>ContextJndiBeanFactoryLocator</classname> - usage and use another <classname>BeanFactoryLocator</classname> variant, such as the - <classname>ContextSingletonBeanFactoryLocator</classname> which can load and use a - shared container to be used by multiple EJBs or other clients. Doing this is relatively - simple, by adding code similar to this to the EJB: + The default behavior of the + <classname>ContextJndiBeanFactoryLocator</classname> class is to load an + <classname>ApplicationContext</classname> for use by an EJB, and is + adequate for some situations. However, it is problematic when the + <classname>ApplicationContext</classname> is loading a number of beans, + or the initialization of those beans is time consuming or memory + intensive (such as a Hibernate <classname>SessionFactory</classname> + initialization, for example), since every EJB will have their own copy. + In this case, the user may want to override the default + <classname>ContextJndiBeanFactoryLocator</classname> usage and use + another <classname>BeanFactoryLocator</classname> variant, such as the + <classname>ContextSingletonBeanFactoryLocator</classname> which can load + and use a shared container to be used by multiple EJBs or other clients. + Doing this is relatively simple, by adding code similar to this to the + EJB: </para> <programlisting language="java"><![CDATA[ /** * Override default BeanFactoryLocator implementation
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/jdbc.xml
@@ -829,7 +829,7 @@ public Actor findActor(String specialty, int age) { </note> <listitem> - <para>Any a custom translation implemented by a subclass. Normally + <para>Any custom translation implemented by a subclass. Normally the provided concrete <classname>SQLErrorCodeSQLExceptionTranslator</classname> is used so this rule does not apply. It only applies if you have actually @@ -1715,7 +1715,7 @@ END;</programlisting>The <code>in_id</code> parameter contains the <para>The <classname>SimpleJdbcCall</classname> is declared in a similar manner to the <classname>SimpleJdbcInsert</classname>. You should instantiate and configure the class in the initialization method of your - data access layer. Compared to the StoredProcdedure class, you don't + data access layer. Compared to the StoredProcedure class, you don't have to create a subclass and you don't have to declare parameters that can be looked up in the database metadata. <!--Reword preceding: You need not subclass *what?* and you declare *what* in init method? TR: Revised, pplease review.-->Following is an example of a SimpleJdbcCall configuration using the above stored @@ -2134,7 +2134,7 @@ public Customer getCustomer(Long id) { <para>The method in this example retrieves the customer with the id that is passed in as the only parameter. Since we only want one object returned we simply call the convenience method <code>findObject</code> - with the id as parameter. If we instead had a query the returned a list + with the id as parameter. If we had instead a query that returned a list of objects and took additional parameters then we would use one of the execute methods that takes an array of parameter values passed in as varargs.</para> @@ -2476,9 +2476,9 @@ public class TitlesAfterDateStoredProcedure extends StoredProcedure { of these approaches use an implementation of the <classname>LobHandler</classname> interface for the actual management of the LOB data. The <classname>LobHandler</classname> provides access to a - <classname>LobCreator</classname><!--a LobCreator *what*? Say what it is. TR: Revised.-->class, - through the <classname>getLobCreator</classname> method, used for - creating new LOB objects to be inserted.</para> + <classname>LobCreator</classname> class, through the + <classname>getLobCreator</classname> method, used for creating new LOB + objects to be inserted.</para> <para>The <classname>LobCreator/LobHandler</classname> provides the following support for LOB input and output:</para> @@ -2577,14 +2577,14 @@ clobReader.close();</programlisting> <callout arearefs="jdbc.lobhandler.setBlob"> <para>Using the method - <classname>setBlobAsBinartStream</classname>, pass in the contents + <classname>setBlobAsBinaryStream</classname>, pass in the contents of the BLOB.</para> </callout> </calloutlist> </programlistingco> <para>Now it's time to read the LOB data from the database. Again, you - use a <code>JdbcTempate</code> with the same instance variable + use a <code>JdbcTemplate</code> with the same instance variable <code>l</code><code>obHandler </code>and a reference to a <classname>DefaultLobHandler</classname>.</para> @@ -2892,7 +2892,7 @@ public class DataAccessUnitTestTemplate { <para>If you want to initialize a database and you can provide a reference to a DataSource bean, use the - <literal>initialize-datasource</literal> tag in the + <literal>initialize-database</literal> tag in the <literal>spring-jdbc</literal> namespace:</para> <programlisting>&lt;jdbc:initialize-database data-source="dataSource"&gt; @@ -2916,11 +2916,12 @@ public class DataAccessUnitTestTemplate { the tables first and then inserts the data - the first step will fail if the tables already exist.</para> - <para>However, to get more control the creation and deletion of existing - data the XML namespace provides a couple more options. The first is flag - to switch the initialization on and off. This can be set according to - the environment (e.g. to pull a boolean value from system properties or - an environment bean), e.g.<programlisting>&lt;jdbc:initialize-database data-source="dataSource" + <para>However, to get more control over the creation and deletion of + existing data, the XML namespace provides a couple more options. The + first is flag to switch the initialization on and off. This can be set + according to the environment (e.g. to pull a boolean value from system + properties or an environment bean), e.g. + <programlisting>&lt;jdbc:initialize-database data-source="dataSource" <emphasis role="bold">enabled="#{systemProperties.INITIALIZE_DATABASE}"</emphasis>&gt; &lt;jdbc:script location="..."/&gt; &lt;/jdbc:initialize-database&gt;</programlisting></para>
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/jms.xml
@@ -403,14 +403,14 @@ public class JmsQueueSender { to create a text message from the supplied <classname>Session</classname> object. The <classname>JmsTemplate</classname> is constructed by passing a reference to a <classname>ConnectionFactory</classname>. As an alternative, - a zero argument constructor and <property>connectionFactory</property> / + a zero argument constructor and <property>connectionFactory</property> is provided and can be used for constructing the instance in JavaBean style (using a BeanFactory or plain Java code). Alternatively, consider deriving from Spring's <classname>JmsGatewaySupport</classname> convenience base class, which provides pre-built bean properties for JMS configuration.</para> <para>The method <methodname>send(String destinationName, MessageCreator - creator)</methodname> lets you send to a message using the string name of + creator)</methodname> lets you send a message using the string name of the destination. If these names are registered in JNDI, you should set the <property>destinationResolver</property> property of the template to an instance of <classname>JndiDestinationResolver</classname>.</para> @@ -444,7 +444,7 @@ public class JmsQueueSender { <para>The sandbox currently includes a <classname>MapMessageConverter</classname> which uses reflection to convert between a JavaBean and a <classname>MapMessage</classname>. - Other popular implementations choices you might implement yourself are + Other popular implementation choices you might implement yourself are Converters that use an existing XML marshalling package, such as JAXB, Castor, XMLBeans, or XStream, to create a <interfacename>TextMessage</interfacename> representing the @@ -500,7 +500,7 @@ public class JmsQueueSender { <interfacename>ProducerCallback</interfacename> expose the JMS <interfacename>Session</interfacename> and <interfacename>Session</interfacename> / - <interfacename>MessageProducer</interfacename> pair respectfully. The + <interfacename>MessageProducer</interfacename> pair respectively. The <methodname>execute()</methodname> methods on <classname>JmsTemplate</classname> execute these callback methods.</para> @@ -589,7 +589,7 @@ public class ExampleListener implements MessageListener { <para>The <interfacename>SessionAwareMessageListener</interfacename> interface is a Spring-specific interface that provides a similar - contract the JMS <interfacename>MessageListener</interfacename> + contract to the JMS <interfacename>MessageListener</interfacename> interface, but also provides the message handling method with access to the JMS <interfacename>Session</interfacename> from which the <interfacename>Message</interfacename> was received.</para>
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/jmx.xml
@@ -519,7 +519,7 @@ public class AnnotationTestBean implements IJmxTestBean { <literal>add(int, int)</literal>, when using the <classname>MetadataMBeanInfoAssembler</classname>.</para> - <para>The configuration below shouws how you configure the + <para>The configuration below shows how you configure the <classname>MBeanExporter</classname> to use the <classname>MetadataMBeanInfoAssembler</classname>:</para> <programlisting language="xml"><![CDATA[<beans>
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/mail.xml
@@ -210,7 +210,7 @@ sender.send(message);]]></programlisting> <section id="mail-javamail-mime-attachments"> <title>Sending attachments and inline resources</title> <para>Multipart email messages allow for both attachments and inline resources. - Examples of inline resources would be be images or a stylesheet you want to use + Examples of inline resources would be images or a stylesheet you want to use in your message, but that you don't want displayed as an attachment.</para> <section id="mail-javamail-mime-attachments-attachment"> <title>Attachments</title> @@ -268,7 +268,7 @@ sender.send(message);]]></programlisting> </section> <section id="mail-templates"> <title>Creating email content using a templating library</title> - <para>The code in the previous examples explicitly has been creating the + <para>The code in the previous examples explicitly created the content of the email message, using methods calls such as <methodname>message.setText(..)</methodname>. This is fine for simple cases, and it is okay in the context of the aforementioned
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/metadata.xml
@@ -38,7 +38,7 @@ public class PetStoreImpl implements PetStoreFacade, OrderService {</programlist from program source code, some important enterprise settings - notably transaction characteristics - arguably belong in program source.</para> - <para>Spring uses Java 5 annotations thoughout the framework and across a + <para>Spring uses Java 5 annotations throughout the framework and across a wide range of features such as DI, MVC, and AOP and supports standardized annotations such as @PreDestroy and @PostConstruct specified by JSR-250, and @Inject specified by JSR-330. This chapter describes the @Required annotation
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/mvc.xml
@@ -820,7 +820,7 @@ public String findOwner(<emphasis role="bold">@PathVariable</emphasis> String ow <!-- MLP: Bev Review --> <para>The matching of method parameter names to URI Template variable names can only be done if your code is compiled with debugging - enabled. If you do have not debugging enabled, you must specify the + enabled. If you do not have debugging enabled, you must specify the name of the URI Template variable name in the @PathVariable annotation in order to bind the resolved value of the variable name to a method parameter. For example:</para> @@ -1176,8 +1176,9 @@ public String processSubmit(<emphasis role="bold">@ModelAttribute("pet") Pet pet <listitem> <para>A <classname>HttpEntity&lt;?&gt;</classname> or <classname>ResponseEntity&lt;?&gt;</classname> object - to access to the Servlet reponse HTTP headers and contents. The entity body will - be converted to the response stream using + to provide access to the Servlet reponse HTTP headers and + contents. The entity body will be converted to the response + stream using <interfacename>HttpMessageConverter</interfacename>s. See <xref linkend="mvc-ann-httpentity" />.</para> </listitem> @@ -2241,7 +2242,7 @@ public class TimeBasedAccessInterceptor extends HandlerInterceptorAdapter { representation of the current resource regardless of the logical view name. The <literal>Accept</literal> header may include wildcards, for example text/*, in which case a <classname>View</classname> whose - Context-Type was text/xml is a compatible match.</para> + Content-Type was text/xml is a compatible match.</para> <para>To support the resolution of a view based on a file extension, use the <classname>ContentNegotiatingViewResolver </classname>bean property @@ -2760,7 +2761,7 @@ public class FileUpoadController { <literal>web.xml</literal>. However, they provide a more flexible way to handle exceptions. They provide information about which handler was executing when the exception was thrown. Furthermore, a programmatic way - of handling exception gives you more options for responding + of handling exceptions gives you more options for responding appropriately before the request is forwarded to another URL (the same end result as when you use the servlet specific exception mappings).</para>
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/orm.xml
@@ -1367,7 +1367,7 @@ TR: REVISED, PLS REVIEW.-->The factory bean uses the JPA configuration and is appropriate for environments where fine-grained customization is required. The <classname>LocalContainerEntityManagerFactoryBean</classname> creates - a <interfacename>PersistenceUnitInfo</interfacename> instance<!--A PersistenceUnitInfo *what*? TR: REVISED, PLS REVIEW. Added *instance*. -->based + a <interfacename>PersistenceUnitInfo</interfacename> instance based on the <literal>persistence.xml</literal> file, the supplied <literal>dataSourceLookup</literal> strategy, and the specified <literal>loadTimeWeaver</literal>. It is thus possible to work with @@ -1467,7 +1467,7 @@ TR: OK AS IS. The requirement is to provide the classloader for the runtime envi applied only <emphasis>per class loader</emphasis> and not per VM.</para> - <para>Refer to the section <xref linkend="aop-aj-ltw-spring" /> in the AOP chapter for more insight regarding the + <para>Refer to <xref linkend="aop-aj-ltw-spring" /> in the AOP chapter for more insight regarding the <interfacename>LoadTimeWeaver</interfacename> implementations and their setup, either generic or customized to various platforms (such as Tomcat, WebLogic, OC4J, GlassFish, Resin and JBoss).</para>
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/oxm.xml
@@ -573,7 +573,7 @@ public class Application { <para> The <classname>JibxMarshaller</classname> class implements both the <interfacename>Marshaller</interfacename> and <interfacename>Unmarshaller</interfacename> interface. - To operate, it requires the name of the class to marshall in, which you can set using the + To operate, it requires the name of the class to marshal in, which you can set using the <property>targetClass</property> property. Optionally, you can set the binding name using the <property>bindingName</property> property. In the next sample, we bind the <classname>Flights</classname> class:
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/remoting.xml
@@ -394,8 +394,8 @@ public class AccountServiceImpl implements AccountService { <title>Exposing the service object</title> <para>Setting up the HTTP invoker infrastructure for a service object - much resembles the way you would do using Hessian or Burlap. Just as - Hessian support provides the + resembles closely the way you would do the same using Hessian or Burlap. + Just as Hessian support provides the <classname>HessianServiceExporter</classname>, Spring's HttpInvoker support provides the <classname>org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter</classname>.</para> @@ -1280,7 +1280,7 @@ public class Client { <classname>RestTemplate</classname>'s behavior is customized by providing callback methods and configuring the <interfacename>HttpMessageConverter</interfacename> used to marshal - objects into the HTTP request body and to unmarshall any response back + objects into the HTTP request body and to unmarshal any response back into an object. As it is common to use XML as a message format, Spring provides a <classname>MarshallingHttpMessageConverter</classname> that uses the Object-to-XML framework that is part of the
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/scheduling.xml
@@ -726,7 +726,7 @@ public class ExampleJob extends QuartzJobBean { <title>Wiring up jobs using triggers and the <classname>SchedulerFactoryBean</classname></title> <para> We've created job details and jobs. We've also reviewed the convenience bean - that allows to you invoke a method on a specific object. Of course, we still need + that allows you to invoke a method on a specific object. Of course, we still need to schedule the jobs themselves. This is done using triggers and a <classname>SchedulerFactoryBean</classname>. Several triggers are available within Quartz. Spring offers two subclassed triggers with convenient defaults: @@ -870,4 +870,4 @@ public class ExampleJob extends QuartzJobBean { </section> </section> -</chapter> \ No newline at end of file +</chapter>
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/transaction.xml
@@ -354,10 +354,9 @@ TR:REVISED, PLS REVIEW--> &lt;property name="password" value="${jdbc.password}" /&gt; &lt;/bean&gt;</programlisting> - <para>The related <interfacename>The - PlatformTransactionManager</interfacename> bean definition will then have - a reference to the <interfacename>DataSource</interfacename> definition. - It will look like this:</para> + <para>The related <interfacename>PlatformTransactionManager</interfacename> + bean definition will then have a reference to the + <interfacename>DataSource</interfacename> definition. It will look like this:</para> <programlisting language="xml">&lt;bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt; &lt;property name="dataSource" ref="dataSource"/&gt; @@ -629,7 +628,7 @@ TR: REVISED, PLS REVIEW - rewrote this to hoefully make it more clear--></para> <para>The Spring Framework enables you to customize transactional behavior, by using AOP. For example, you can insert custom behavior in the case of transaction rollback. You can also add arbitrary advice, - along with the transactional advice. With EJB CMT, cannot influence + along with the transactional advice. With EJB CMT, you cannot influence the container's transaction management except with <methodname>setRollbackOnly()</methodname>.</para> </listitem> @@ -1858,7 +1857,7 @@ TR: REVISED, PLS REVIEW - changed it back; it's not just settings, the section d <para>When the propagation setting is <literal>PROPAGATION_REQUIRED</literal>, a <emphasis>logical</emphasis> transaction scope is created for each - method that to which the setting is applied. Each such logical + method upon which the setting is applied. Each such logical transaction scope can determine rollback-only status individually, with an outer transaction scope being logically independent from the inner transaction scope. Of course, in case of standard @@ -2137,7 +2136,7 @@ TR: REVISED, PLS REVIEW. changed to 'desired'; seems clear that the desired orde the aspect. The simplest way to configure the transaction management aspect is to use the <literal>&lt;tx:annotation-driven/&gt;</literal> element and specify the <literal>mode</literal> attribute to - <literal>asepctj</literal> as described in <xref + <literal>aspectj</literal> as described in <xref linkend="transaction-declarative-annotations" />. Because we're focusing here on applications running outside of a Spring container, we'll show you how to do it programmatically.</para>
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/view.xml
@@ -29,7 +29,7 @@ <note> <para> Setting up your application to use JSTL is a common source of error, - mainly cause by confusion over the different servlet spec., JSP and JSTL + mainly caused by confusion over the different servlet spec., JSP and JSTL version numbers, what they mean and how to declare the taglibs correctly. The article <ulink url="http://www.mularien.com/blog/2008/04/24/how-to-reference-and-use-jstl-in-your-web-application/"> @@ -760,7 +760,7 @@ productList.url=/WEB-INF/jsp/productlist.jsp</programlisting> <para>A key principle of REST is the use of the Uniform Interface. This means that all resources (URLs) can be manipulated using the same - four HTTP methods: GET, PUT, POST, and DELETE. For each methods, the + four HTTP methods: GET, PUT, POST, and DELETE. For each method, the HTTP specification defines the exact semantics. For instance, a GET should always be a safe operation, meaning that is has no side effects, and a PUT or DELETE should be idempotent, meaning that you @@ -986,7 +986,7 @@ findOwnersForm.url=/WEB-INF/jsp/findOwners.jsp <para><ulink url="http://velocity.apache.org">Velocity</ulink> and <ulink url="http://www.freemarker.org">FreeMarker</ulink> are two templating - languages that can both be used as view technologies within Spring MVC + languages that can be used as view technologies within Spring MVC applications. The languages are quite similar and serve similar needs and so are considered together in this section. For semantic and syntactic differences between the two languages, see the <ulink @@ -999,8 +999,8 @@ findOwnersForm.url=/WEB-INF/jsp/findOwners.jsp class="libraryfile">velocity-1.x.x.jar</filename> or <filename class="libraryfile">freemarker-2.x.jar</filename> in order to work with Velocity or FreeMarker respectively and <filename - class="libraryfile">commons-collections.jar</filename> needs also to be - available for Velocity. Typically they are included in the + class="libraryfile">commons-collections.jar</filename> is required for + Velocity. Typically they are included in the <literal>WEB-INF/lib</literal> folder where they are guaranteed to be found by a Java EE server and added to the classpath for your application. It is of course assumed that you already have the <filename @@ -2593,7 +2593,7 @@ simpleReport.reportDataKey=myBeanData</programlisting> response content as XML. The object to be marshalled can be set explicitly using <classname>MarhsallingView</classname>'s <property>modelKey</property> bean property. Alternatively, the view will - iterate over all model properties and marhsall only those types that are + iterate over all model properties and marshal only those types that are supported by the <interfacename>Marshaller</interfacename>. For more information on the functionality in the <classname>org.springframework.oxm</classname> package refer to the
true
Other
spring-projects
spring-framework
d97f899bee67eef894dcae15921b2ef3acfa0726.json
Fix typos (SPR-7339)
spring-framework-reference/src/web-integration.xml
@@ -627,7 +627,7 @@ and components very simple, and <emphasis role="bold">delegate</emphasis> as much logic as possible out to HiveMind [or Spring, or whatever] services. Listener methods should - ideally do little more than marshall together the correct information + ideally do little more than marshal together the correct information and pass it over to a service.</emphasis> </quote> </para>
true
Other
spring-projects
spring-framework
5ce4cada5362f330de847d92a94fb3b001e6b3cd.json
Fix typos in Chapter 27 (SPR-7339) Note that SPR-7433 has also been created to consider removing this chapter entirely.
spring-framework-reference/src/metadata.xml
@@ -10,7 +10,7 @@ <para>Java 5 introduced source-level metadata called annotations to program elements, usually, classes and/or methods</para> - <para>For example we might add metadata at the class level using the + <para>For example we might add metadata at the class level using Spring's @Transactional annotation that is used to support Spring's declarative transaction management features.</para> @@ -32,18 +32,18 @@ public class PetStoreImpl implements PetStoreFacade, OrderService {</programlist . . . }</programlisting> - <para>The value of using annoations has been broadly embrassed by the JEE - community. For example, it's much less verbose than the traditional XML + <para>The value of using annoations has been broadly embraced by the Java + community. For example, it's much less verbose than traditional XML deployment descriptors. While it is desirable to externalize some things from program source code, some important enterprise settings - notably - transaction characteristics - arguably belong in program source. </para> - - <para>Spring uses Java 5 annotations thoughout the framework across a wide - range of features such as DI, MVC, and AOP and supports JEE standard - annotations such as @PreDestroy and @PostConstruct defined by JSR-250. - This chapter describes the @Required attribute and provides links to other - parts the documentation where the various attributes are described in more - detail.</para> + transaction characteristics - arguably belong in program source.</para> + + <para>Spring uses Java 5 annotations thoughout the framework and across a + wide range of features such as DI, MVC, and AOP and supports standardized + annotations such as @PreDestroy and @PostConstruct specified by JSR-250, and + @Inject specified by JSR-330. This chapter describes the @Required annotation + and provides links to other parts of the documentation where the various + annotations are described in more detail.</para> </section> <section id="metadata-annotations"> @@ -98,10 +98,9 @@ public class PetStoreImpl implements PetStoreFacade, OrderService {</programlist <programlisting>Exception in thread "main" java.lang.IllegalArgumentException: Property 'movieFinder' is required for bean 'movieLister'.</programlisting> - <para>There is one last little (small, tiny) piece of Spring - configuration that is required to actually <emphasis>'switch - on'</emphasis> this behavior. Simply annotating the - <emphasis>'setter'</emphasis> properties of your classes is not enough + <para>There is one last bit of Spring configuration that is required to + actually <emphasis>'switch on'</emphasis> this behavior. Simply annotating + the <emphasis>'setter'</emphasis> properties of your classes is not enough to get this behavior. You need to enable a component that is aware of the <interfacename>@Required</interfacename> annotation and that can process it appropriately.</para>
false
Other
spring-projects
spring-framework
b87b23087dfb291fd44d0fdaf6fabe9bfbc4b029.json
Replace 'recourse' with simpler terms (SPR-7339)
spring-framework-reference/src/mail.xml
@@ -303,9 +303,9 @@ sender.send(message);]]></programlisting> create your email template(s), you will need to have the Velocity libraries available on your classpath. You will also need to create one or more Velocity templates for the email content that your application needs. Find below the Velocity - template that this example will be using... as you can see it is HTML-based, - and since it is plain text it can be created using your favorite HTML editor - without recourse to having to know Java.</para> + template that this example will be using. As you can see it is HTML-based, + and since it is plain text it can be created using your favorite HTML + or text editor.</para> <programlisting language="xml"><lineannotation># in the <literal>com/foo/package</literal></lineannotation><![CDATA[ <html> <body>
true
Other
spring-projects
spring-framework
b87b23087dfb291fd44d0fdaf6fabe9bfbc4b029.json
Replace 'recourse' with simpler terms (SPR-7339)
spring-framework-reference/src/validation.xml
@@ -108,9 +108,9 @@ public class Person { <classname>Customer</classname> objects, and so a distinct <classname>AddressValidator</classname> has been implemented. If you want your <classname>CustomerValidator</classname> to reuse the logic contained within the - <classname>AddressValidator</classname> class without recourse to copy-n-paste you can - dependency-inject or instantiate an <classname>AddressValidator</classname> within your - <classname>CustomerValidator</classname>, and use it like so:</para> + <classname>AddressValidator</classname> class without resorting to copy-and-paste, + you can dependency-inject or instantiate an <classname>AddressValidator</classname> + within your <classname>CustomerValidator</classname>, and use it like so:</para> <programlisting language="java"><![CDATA[public class CustomerValidator implements Validator { private final Validator addressValidator; @@ -1515,4 +1515,4 @@ public class MyController { </section> </section> </section> -</chapter> \ No newline at end of file +</chapter>
true
Other
spring-projects
spring-framework
bab902e85b6cb1c67885393abe6b2a7d5ac15f2d.json
Fix typo 'type form'->'type from' (SPR-7339)
spring-framework-reference/src/remoting.xml
@@ -1545,7 +1545,7 @@ String body = response.getBody();</programlisting> // Return the list of MediaType objects supported by this converter. List&lt;MediaType&gt; getSupportedMediaTypes(); - // Read an object of the given type form the given input message, and returns it. + // Read an object of the given type from the given input message, and returns it. T read(Class&lt;T&gt; clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException;
false
Other
spring-projects
spring-framework
d109879b6c68e38ecd08bd5c6573fe82d43dbbfc.json
Ignore OS X .DS_Store files
.gitignore
@@ -4,3 +4,4 @@ ivy-cache spring-build jmx.log .springBeans +.DS_Store
false
Other
spring-projects
spring-framework
8e5c033446c6435d631107f73d83eeb413998628.json
avoid double ConversionFailedException nesting
org.springframework.core/src/main/java/org/springframework/core/convert/support/ConversionUtils.java
@@ -35,6 +35,9 @@ public static Object invokeConverter(GenericConverter converter, Object source, try { return converter.convert(source, sourceType, targetType); } + catch (ConversionFailedException ex) { + throw ex; + } catch (Exception ex) { throw new ConversionFailedException(sourceType, targetType, source, ex); }
true
Other
spring-projects
spring-framework
8e5c033446c6435d631107f73d83eeb413998628.json
avoid double ConversionFailedException nesting
org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java
@@ -16,24 +16,18 @@ package org.springframework.web.servlet.config; -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.assertSame; -import static org.junit.Assert.assertTrue; - import java.util.Date; import java.util.Locale; - import javax.validation.Valid; import javax.validation.constraints.NotNull; +import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; + +import org.springframework.beans.TypeMismatchException; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.core.convert.ConversionFailedException; import org.springframework.core.convert.ConversionService; import org.springframework.core.io.ClassPathResource; import org.springframework.format.annotation.DateTimeFormat; @@ -120,7 +114,7 @@ public void testDefaultConfig() throws Exception { assertTrue(handler.recordedValidationError); } - @Test(expected=ConversionFailedException.class) + @Test(expected=TypeMismatchException.class) public void testCustomConversionService() throws Exception { XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext); reader.loadBeanDefinitions(new ClassPathResource("mvc-config-custom-conversion-service.xml", getClass()));
true
Other
spring-projects
spring-framework
605ac0e230b314e170a195de077980252a18c6ef.json
Remove redundant @Aspect from CodeStyleAspect.aj This has been present for quite some time, and compilation at the command line was never a problem. However, after upgrading to STS 2.3.3.M2, errors started appearing in the Problems tab about 'duplicate @Aspect annotations'. This message was a bit misleading given that the underlying issue is that applying an @Aspect annotation on an aspect declared in .aj style is redundant. Andy Clement is investigating as well, but for now the reason for the change in behavior remains a mystery.
org.springframework.aspects/src/test/java/org/springframework/aop/aspectj/autoproxy/CodeStyleAspect.aj
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2010 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,12 +16,9 @@ package org.springframework.aop.aspectj.autoproxy; -import org.aspectj.lang.annotation.Aspect; - /** * @author Adrian Colyer */ -@Aspect public aspect CodeStyleAspect { private String foo;
false
Other
spring-projects
spring-framework
022e74ea3dee9c8d443a9ed467ba51f32f9e2438.json
Add .springBeans to .gitignore
.gitignore
@@ -3,3 +3,4 @@ integration-repo ivy-cache spring-build jmx.log +.springBeans
false
Other
spring-projects
spring-framework
fecd6edf750b59fa5d91518c9273472551172a83.json
Fix unnecessary casts in Servlet*PropertySource
org.springframework.web/src/main/java/org/springframework/web/context/support/ServletConfigPropertySource.java
@@ -16,8 +16,6 @@ package org.springframework.web.context.support; -import java.util.Enumeration; - import javax.servlet.ServletConfig; import org.springframework.core.env.EnumerablePropertySource; @@ -38,10 +36,9 @@ public ServletConfigPropertySource(String name, ServletConfig servletConfig) { } @Override - @SuppressWarnings("unchecked") public String[] getPropertyNames() { return CollectionUtils.toArray( - (Enumeration<String>)this.source.getInitParameterNames(), EMPTY_NAMES_ARRAY); + this.source.getInitParameterNames(), EMPTY_NAMES_ARRAY); } @Override
true
Other
spring-projects
spring-framework
fecd6edf750b59fa5d91518c9273472551172a83.json
Fix unnecessary casts in Servlet*PropertySource
org.springframework.web/src/main/java/org/springframework/web/context/support/ServletContextPropertySource.java
@@ -16,8 +16,6 @@ package org.springframework.web.context.support; -import java.util.Enumeration; - import javax.servlet.ServletContext; import org.springframework.core.env.EnumerablePropertySource; @@ -38,10 +36,9 @@ public ServletContextPropertySource(String name, ServletContext servletContext) } @Override - @SuppressWarnings("unchecked") public String[] getPropertyNames() { return CollectionUtils.toArray( - (Enumeration<String>)this.source.getInitParameterNames(), EMPTY_NAMES_ARRAY); + this.source.getInitParameterNames(), EMPTY_NAMES_ARRAY); } @Override
true
Other
spring-projects
spring-framework
1eb581134794ba7d4926f6d10d4dc8a70de247ec.json
Introduce CommandLinePropertySource and impls Users may now work with command line arguments as a source of properties for use with the PropertySource and Environment APIs. An implementation based on the jopt library and a "simple" implementation requiring no external libraries are are provided out-of-the box. See Javadoc for CommandLinePropertySource, JOptCommandLinePropertySource and SimpleCommandLinePropertySource for details. Issue: SPR-8482
org.springframework.core/.classpath
@@ -13,6 +13,7 @@ <classpathentry kind="var" path="IVY_CACHE/org.custommonkey.xmlunit/com.springsource.org.custommonkey.xmlunit/1.2.0/com.springsource.org.custommonkey.xmlunit-1.2.0.jar" sourcepath="/IVY_CACHE/org.custommonkey.xmlunit/com.springsource.org.custommonkey.xmlunit/1.2.0/com.springsource.org.custommonkey.xmlunit-sources-1.2.0.jar"/> <classpathentry kind="var" path="IVY_CACHE/org.easymock/com.springsource.org.easymock/2.5.1/com.springsource.org.easymock-2.5.1.jar" sourcepath="/IVY_CACHE/org.easymock/com.springsource.org.easymock/2.5.1/com.springsource.org.easymock-sources-2.5.1.jar"/> <classpathentry kind="var" path="IVY_CACHE/org.codehaus.woodstox/com.springsource.com.ctc.wstx/3.2.7/com.springsource.com.ctc.wstx-3.2.7.jar" sourcepath="/IVY_CACHE/org.codehaus.woodstox/com.springsource.com.ctc.wstx/3.2.7/com.springsource.com.ctc.wstx-sources-3.2.7.jar"/> + <classpathentry kind="var" path="IVY_CACHE/net.sourceforge.jopt-simple/com.springsource.joptsimple/3.0.0/com.springsource.joptsimple-3.0.0.jar" sourcepath="IVY_CACHE/net.sourceforge.jopt-simple/com.springsource.joptsimple/3.0.0/com.springsource.joptsimple-sources-3.0.0.jar"/> <classpathentry kind="lib" path="/org.springframework.asm/target/artifacts/org.springframework.asm.jar" sourcepath="/org.springframework.asm/target/artifacts/org.springframework.asm-sources.jar"/> <classpathentry kind="output" path="target/classes"/> </classpath>
true
Other
spring-projects
spring-framework
1eb581134794ba7d4926f6d10d4dc8a70de247ec.json
Introduce CommandLinePropertySource and impls Users may now work with command line arguments as a source of properties for use with the PropertySource and Environment APIs. An implementation based on the jopt library and a "simple" implementation requiring no external libraries are are provided out-of-the box. See Javadoc for CommandLinePropertySource, JOptCommandLinePropertySource and SimpleCommandLinePropertySource for details. Issue: SPR-8482
org.springframework.core/ivy.xml
@@ -29,6 +29,7 @@ <dependency org="org.apache.log4j" name="com.springsource.org.apache.log4j" rev="1.2.15" conf="optional, log4j->compile"/> <dependency org="org.aspectj" name="com.springsource.org.aspectj.weaver" rev="${aspectj.version}" conf="optional, aspectj->compile"/> <dependency org="org.springframework" name="org.springframework.asm" rev="latest.integration" conf="optional->compile"/> + <dependency org="net.sourceforge.jopt-simple" name="com.springsource.joptsimple" rev="3.0.0" conf="optional->compile"/> <!-- test dependencies --> <dependency org="javax.servlet" name="com.springsource.javax.servlet" rev="2.5.0" conf="test->compile"/> <dependency org="org.junit" name="com.springsource.org.junit" rev="${junit.version}" conf="test->runtime"/>
true
Other
spring-projects
spring-framework
1eb581134794ba7d4926f6d10d4dc8a70de247ec.json
Introduce CommandLinePropertySource and impls Users may now work with command line arguments as a source of properties for use with the PropertySource and Environment APIs. An implementation based on the jopt library and a "simple" implementation requiring no external libraries are are provided out-of-the box. See Javadoc for CommandLinePropertySource, JOptCommandLinePropertySource and SimpleCommandLinePropertySource for details. Issue: SPR-8482
org.springframework.core/src/main/java/org/springframework/core/env/CommandLineArgs.java
@@ -0,0 +1,91 @@ +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core.env; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * A simple representation of command line arguments, broken into "option arguments" and + * "non-option arguments". + * + * @author Chris Beams + * @since 3.1 + * @see SimpleCommandLineArgsParser + */ +class CommandLineArgs { + + private final Map<String, List<String>> optionArgs = new HashMap<String, List<String>>(); + private final List<String> nonOptionArgs = new ArrayList<String>(); + + /** + * Add an option argument for the given option name and add the given value to the + * list of values associated with this option (of which there may be zero or more). + * The given value may be {@code null}, indicating that the option was specified + * without an associated value (e.g. "--foo" vs. "--foo=bar"). + */ + public void addOptionArg(String optionName, String optionValue) { + if (!this.optionArgs.containsKey(optionName)) { + this.optionArgs.put(optionName, new ArrayList<String>()); + } + if (optionValue != null) { + this.optionArgs.get(optionName).add(optionValue); + } + } + + /** + * Return the set of all option arguments present on the command line. + */ + public Set<String> getOptionNames() { + return Collections.unmodifiableSet(this.optionArgs.keySet()); + } + + /** + * Return whether the option with the given name was present on the command line. + */ + public boolean containsOption(String optionName) { + return this.optionArgs.containsKey(optionName); + } + + /** + * Return the list of values associated with the given option. {@code null} signifies + * that the option was not present; empty list signifies that no values were associated + * with this option. + */ + public List<String> getOptionValues(String optionName) { + return this.optionArgs.get(optionName); + } + + /** + * Add the given value to the list of non-option arguments. + */ + public void addNonOptionArg(String value) { + this.nonOptionArgs.add(value); + } + + /** + * Return the list of non-option arguments specified on the command line. + */ + public List<String> getNonOptionArgs() { + return Collections.unmodifiableList(this.nonOptionArgs); + } + +}
true
Other
spring-projects
spring-framework
1eb581134794ba7d4926f6d10d4dc8a70de247ec.json
Introduce CommandLinePropertySource and impls Users may now work with command line arguments as a source of properties for use with the PropertySource and Environment APIs. An implementation based on the jopt library and a "simple" implementation requiring no external libraries are are provided out-of-the box. See Javadoc for CommandLinePropertySource, JOptCommandLinePropertySource and SimpleCommandLinePropertySource for details. Issue: SPR-8482
org.springframework.core/src/main/java/org/springframework/core/env/CommandLinePropertySource.java
@@ -0,0 +1,296 @@ +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core.env; + +import java.util.Collection; +import java.util.List; + +import org.springframework.util.StringUtils; + +/** + * Abstract base class for {@link PropertySource} implementations backed by command line + * arguments. The parameterized type {@code T} represents the underlying source of command + * line options. This may be as simple as a String array in the case of + * {@link SimpleCommandLinePropertySource}, or specific to a particular API such as JOpt's + * {@code OptionSet} in the case of {@link JOptCommandLinePropertySource}. + * + * <h3>Purpose and General Usage</h3> + * For use in standalone Spring-based applications, i.e. those that are bootstrapped via + * a traditional {@code main} method accepting a {@code String[]} of arguments from the + * command line. In many cases, processing command-line arguments directly within the + * {@code main} method may be sufficient, but in other cases, it may be desirable to + * inject arguments as values into Spring beans. It is this latter set of cases in which + * a {@code CommandLinePropertySource} becomes useful. A {@code CommandLinePropertySource} + * will typically be added to the {@link Environment} of the Spring + * {@code ApplicationContext}, at which point all command line arguments become available + * through the {@link Environment#getProperty(String)} family of methods. For example: + * <pre class="code"> + * public static void main(String[] args) { + * CommandLinePropertySource clps = ...; + * AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + * ctx.getEnvironment().getPropertySources().addFirst(clps); + * ctx.register(AppConfig.class); + * ctx.refresh(); + * }</pre> + * With the bootstrap logic above, the {@code AppConfig} class may {@code @Inject} the + * Spring {@code Environment} and query it directly for properties: + * <pre class="code"> + * &#064;Configuration + * public class AppConfig { + * &#064;Inject Environment env; + * + * &#064;Bean + * public void DataSource dataSource() { + * MyVendorDataSource dataSource = new MyVendorDataSource(); + * dataSource.setHostname(env.getProperty("db.hostname", "localhost")); + * dataSource.setUsername(env.getRequiredProperty("db.username")); + * dataSource.setPassword(env.getRequiredProperty("db.password")); + * // ... + * return dataSource; + * } + * }</pre> + * Because the {@code CommandLinePropertySource} was added to the {@code Environment}'s + * set of {@link MutablePropertySources} using the {@code #addFirst} method, it has + * highest search precedence, meaning that while "db.hostname" and other properties may + * exist in other property sources such as the system environment variables, it will be + * chosen from the command line property source first. This is a reasonable approach + * given that arguments specified on the command line are naturally more specific than + * those specified as environment variables. + * + * <p>As an alternative to injecting the {@code Environment}, Spring's {@code @Value} + * annotation may be used to inject these properties, given that a {@link + * PropertySourcesPropertyResolver} bean has been registered, either directly or through + * using the {@code <context:property-placeholder>} element. For example: + * <pre class="code"> + * &#064;Component + * public class MyComponent { + * &#064;Value("my.property:defaultVal") + * private String myProperty; + * + * public void getMyProperty() { + * return this.myProperty; + * } + * + * // ... + * }</pre> + * + * <h3>Working with option arguments</h3> + * + * <p>Individual command line arguments are represented as properties through the usual + * {@link PropertySource#getProperty(String)} and + * {@link PropertySource#containsProperty(String)} methods. For example, given the + * following command line: + * <pre class="code"> + * --o1=v1 --o2</pre> + * 'o1' and 'o2' are treated as "option arguments", and the following assertions would + * evaluate true: + * <pre class="code"> + * CommandLinePropertySource<?> ps = ... + * assert ps.containsProperty("o1") == true; + * assert ps.containsProperty("o2") == true; + * assert ps.containsProperty("o3") == false; + * assert ps.getProperty("o1").equals("v1"); + * assert ps.getProperty("o2").equals(""); + * assert ps.getProperty("o3") == null;</pre> + * + * Note that the 'o2' option has no argument, but {@code getProperty("o2")} resolves to + * empty string ({@code ""}) as opposed to {@code null}, while {@code getProperty("o3")} + * resolves to {@code null} because it was not specified. This behavior is consistent with + * the general contract to be followed by all {@code PropertySource} implementations. + * + * <p>Note also that while "--" was used in the examples above to denote an option + * argument, this syntax may vary across individual command line argument libraries. For + * example, a JOpt- or Commons CLI-based implementation may allow for single dash ("-") + * "short" option arguments, etc. + * + * <h3>Working with non-option arguments</h3> + * + * <p>Non-option arguments are also supported through this abstraction. Any arguments + * supplied without an option-style prefix such as "-" or "--" are considered "non-option + * arguments" and available through the special {@linkplain + * #DEFAULT_NON_OPTION_ARGS_PROPERTY_NAME "nonOptionArgs"} property. If multiple + * non-option arguments are specified, the value of this property will be a + * comma-delimited string containing all of the arguments. This approach ensures a simple + * and consistent return type (String) for all properties from a {@code + * CommandLinePropertySource} and at the same time lends itself to conversion when used + * in conjunction with the Spring {@link Environment} and its built-in {@code + * ConversionService}. Consider the following example: + * <pre class="code"> + * --o1=v1 --o2=v2 /path/to/file1 /path/to/file2</pre> + * In this example, "o1" and "o2" would be considered "option arguments", while the two + * filesystem paths qualify as "non-option arguments". As such, the following assertions + * will evaluate true: + * <pre class="code"> + * CommandLinePropertySource<?> ps = ... + * assert ps.containsProperty("o1") == true; + * assert ps.containsProperty("o2") == true; + * assert ps.containsProperty("nonOptionArgs") == true; + * assert ps.getProperty("o1").equals("v1"); + * assert ps.getProperty("o2").equals("v2"); + * assert ps.getProperty("nonOptionArgs").equals("/path/to/file1,/path/to/file2");</pre> + * + * <p>As mentioned above, when used in conjunction with the Spring {@code Environment} + * abstraction, this comma-delimited string may easily be converted to a String array or + * list: + * <pre class="code"> + * Environment env = applicationContext.getEnvironment(); + * String[] nonOptionArgs = env.getProperty("nonOptionArgs", String[].class); + * assert nonOptionArgs[0].equals("/path/to/file1"); + * assert nonOptionArgs[1].equals("/path/to/file2");</pre> + * + * <p>The name of the special "non-option arguments" property may be customized through + * the {@link #setNonOptionArgsPropertyName(String)} method. Doing so is recommended as + * it gives proper semantic value to non-option arguments. For example, if filesystem + * paths are being specified as non-option arguments, it is likely preferable to refer to + * these as something like "file.locations" than the default of "nonOptionArgs": + * <pre class="code"> + * public static void main(String[] args) { + * CommandLinePropertySource clps = ...; + * clps.setNonOptionArgsPropertyName("file.locations"); + * + * AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + * ctx.getEnvironment().getPropertySources().addFirst(clps); + * ctx.register(AppConfig.class); + * ctx.refresh(); + * }</pre> + * + * <h3>Limitations</h3> + * This abstraction is not intended to expose the full power of underlying command line + * parsing APIs such as JOpt or Commons CLI. It's intent is rather just the opposite: to + * provide the simplest possible abstraction for accessing command line arguments + * <em>after</em> they have been parsed. So the typical case will involve fully configuring + * the underlying command line parsing API, parsing the {@code String[]} of arguments + * coming into the main method, and then simply providing the parsing results to an + * implementation of {@code CommandLinePropertySource}. At that point, all arguments can + * be considered either 'option' or 'non-option' arguments and as described above can be + * accessed through the normal {@code PropertySource} and {@code Environment} APIs. + * + * @author Chris Beams + * @since 3.1 + * @see PropertySource + * @see SimpleCommandLinePropertySource + * @see JOptCommandLinePropertySource + */ +public abstract class CommandLinePropertySource<T> extends PropertySource<T> { + + /** The default name given to {@link CommandLinePropertySource} instances: {@value} */ + public static final String DEFAULT_COMMAND_LINE_PROPERTY_SOURCE_NAME = "commandLineArgs"; + + /** The default name of the property representing non-option arguments: {@value} */ + public static final String DEFAULT_NON_OPTION_ARGS_PROPERTY_NAME = "nonOptionArgs"; + + private String nonOptionArgsPropertyName = DEFAULT_NON_OPTION_ARGS_PROPERTY_NAME; + + /** + * Create a new {@code CommandLinePropertySource} having the default name {@value + * #DEFAULT_COMMAND_LINE_PROPERTY_SOURCE_NAME} and backed by the given source object. + */ + public CommandLinePropertySource(T source) { + super(DEFAULT_COMMAND_LINE_PROPERTY_SOURCE_NAME, source); + } + + /** + * Create a new {@link CommandLinePropertySource} having the given name and backed by + * the given source object. + */ + public CommandLinePropertySource(String name, T source) { + super(name, source); + } + + /** + * Specify the name of the special "non-option arguments" property. The default is + * {@value #DEFAULT_NON_OPTION_ARGS_PROPERTY_NAME}. + */ + public void setNonOptionArgsPropertyName(String nonOptionArgsPropertyName) { + this.nonOptionArgsPropertyName = nonOptionArgsPropertyName; + } + + /** + * Return whether this {@code PropertySource} contains the given key. + * <p>This implementation first checks to see if the key specified is the special + * {@linkplain #setNonOptionArgsPropertyName(String) "non-option arguments" property}, + * and if so delegates to the abstract {@link #getNonOptionArgs()} method + * checking to see whether it returns an empty collection. Otherwise delegates to and + * returns the value of the abstract {@link #containsOption(String)} method. + */ + @Override + public final boolean containsProperty(String key) { + if (this.nonOptionArgsPropertyName.equals(key)) { + return !this.getNonOptionArgs().isEmpty(); + } + return this.containsOption(key); + } + + /** + * {@inheritDoc} + * <p>This implementation first checks to see if the key specified is the special + * {@linkplain #setNonOptionArgsPropertyName(String) "non-option arguments" property}, + * and if so delegates to the abstract {@link #getNonOptionArgs()} method. If so + * and the collection of non-option arguments is empty, this method returns {@code + * null}. If not empty, it returns a comma-separated String of all non-option + * arguments. Otherwise delegates to and returns the result of the abstract {@link + * #getOptionValues(String)} method. + */ + @Override + public final String getProperty(String key) { + if (this.nonOptionArgsPropertyName.equals(key)) { + Collection<String> nonOptionArguments = this.getNonOptionArgs(); + if (nonOptionArguments.isEmpty()) { + return null; + } + else { + return StringUtils.collectionToCommaDelimitedString(nonOptionArguments); + } + } + Collection<String> optionValues = this.getOptionValues(key); + if (optionValues == null) { + return null; + } + else { + return StringUtils.collectionToCommaDelimitedString(optionValues); + } + } + + /** + * Return whether the set of option arguments parsed from the command line contains + * an option with the given name. + */ + protected abstract boolean containsOption(String name); + + /** + * Return the collection of values associated with the command line option having the + * given name. + * <ul> + * <li>if the option is present and has no argument (e.g.: "--foo"), return an empty + * collection ({@code []})</li> + * <li>if the option is present and has a single value (e.g. "--foo=bar"), return a + * collection having one element ({@code ["bar"]})</li> + * <li>if the option is present and the underlying command line parsing library + * supports multiple arguments (e.g. "--foo=bar --foo=baz"), return a collection + * having elements for each value ({@code ["bar", "baz"]})</li> + * <li>if the option is not present, return {@code null}</li> + * </ul> + */ + protected abstract List<String> getOptionValues(String name); + + /** + * Return the collection of non-option arguments parsed from the command line. Never + * {@code null}. + */ + protected abstract List<String> getNonOptionArgs(); + +}
true
Other
spring-projects
spring-framework
1eb581134794ba7d4926f6d10d4dc8a70de247ec.json
Introduce CommandLinePropertySource and impls Users may now work with command line arguments as a source of properties for use with the PropertySource and Environment APIs. An implementation based on the jopt library and a "simple" implementation requiring no external libraries are are provided out-of-the box. See Javadoc for CommandLinePropertySource, JOptCommandLinePropertySource and SimpleCommandLinePropertySource for details. Issue: SPR-8482
org.springframework.core/src/main/java/org/springframework/core/env/JOptCommandLinePropertySource.java
@@ -0,0 +1,106 @@ +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core.env; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import joptsimple.OptionSet; + +/** + * {@link CommandLinePropertySource} implementation backed by a JOpt {@link OptionSet}. + * + * <h2>Typical usage</h2> + * Configure and execute an {@code OptionParser} against the {@code String[]} of arguments + * supplied to the {@code main} method, and create a {@link JOptCommandLinePropertySource} + * using the resulting {@code OptionSet} object: + * <pre class="code"> + * public static void main(String[] args) { + * OptionParser parser = new OptionParser(); + * parser.accepts("option1"); + * parser.accepts("option2").withRequiredArg(); + * OptionSet options = parser.parse(args); + * PropertySource<?> ps = new JOptCommandLinePropertySource(options); + * // ... + * }</pre> + * + * See {@link CommandLinePropertySource} for complete general usage examples. + * + * <h3>Requirements</h3> + * + * <p>Use of this class requires adding the jopt-simple JAR to your application classpath. + * Versions 3.0 and better are supported. + * + * @author Chris Beams + * @since 3.1 + * @see CommandLinePropertySource + * @see joptsimple.OptionParser + * @see joptsimple.OptionSet + */ +public class JOptCommandLinePropertySource extends CommandLinePropertySource<OptionSet> { + + /** + * Create a new {@code JOptCommandLinePropertySource} having the default name + * and backed by the given {@code OptionSet}. + * @see CommandLinePropertySource#DEFAULT_COMMAND_LINE_PROPERTY_SOURCE_NAME + * @see CommandLinePropertySource#CommandLinePropertySource(Object) + */ + public JOptCommandLinePropertySource(OptionSet options) { + super(options); + } + + /** + * Create a new {@code JOptCommandLinePropertySource} having the given name + * and backed by the given {@code OptionSet}. + */ + public JOptCommandLinePropertySource(String name, OptionSet options) { + super(name, options); + } + + @Override + protected boolean containsOption(String key) { + return this.source.has(key); + } + + @Override + public List<String> getOptionValues(String key) { + List<?> argValues = this.source.valuesOf(key); + List<String> stringArgValues = new ArrayList<String>(); + for(Object argValue : argValues) { + if (!(argValue instanceof String)) { + throw new IllegalArgumentException("argument values must be of type String"); + } + stringArgValues.add((String)argValue); + } + if (stringArgValues.size() == 0) { + if (this.source.has(key)) { + return Collections.emptyList(); + } + else { + return null; + } + } + return Collections.unmodifiableList(stringArgValues); + } + + @Override + protected List<String> getNonOptionArgs() { + return this.source.nonOptionArguments(); + } + +}
true
Other
spring-projects
spring-framework
1eb581134794ba7d4926f6d10d4dc8a70de247ec.json
Introduce CommandLinePropertySource and impls Users may now work with command line arguments as a source of properties for use with the PropertySource and Environment APIs. An implementation based on the jopt library and a "simple" implementation requiring no external libraries are are provided out-of-the box. See Javadoc for CommandLinePropertySource, JOptCommandLinePropertySource and SimpleCommandLinePropertySource for details. Issue: SPR-8482
org.springframework.core/src/main/java/org/springframework/core/env/SimpleCommandLineArgsParser.java
@@ -0,0 +1,86 @@ +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core.env; + +/** + * Parses a {@code String[]} of command line arguments in order to populate a + * {@link CommandLineArgs} object. + * + * <h3>Working with option arguments</h3> + * Option arguments must adhere to the exact syntax: + * <pre class="code">--optName[=optValue]</pre> + * That is, options must be prefixed with "{@code --}", and may or may not specify a value. + * If a value is specified, the name and value must be separated <em>without spaces</em> + * by an equals sign ("="). + * + * <h4>Valid examples of option arguments</h4> + * <pre class="code"> + * --foo + * --foo=bar + * --foo="bar then baz" + * --foo=bar,baz,biz</pre> + * + * <h4>Invalid examples of option arguments</h4> + * <pre class="code"> + * -foo + * --foo bar + * --foo = bar + * --foo=bar --foo=baz --foo=biz</pre> + * + * <h3>Working with non-option arguments</h3> + * Any and all arguments specified at the command line without the "{@code --}" option + * prefix will be considered as "non-option arguments" and made available through the + * {@link CommandLineArgs#getNonOptionArgs()} method. + * + * @author Chris Beams + * @since 3.1 + */ +class SimpleCommandLineArgsParser { + + /** + * Parse the given {@code String} array based on the rules described {@linkplain + * SimpleCommandLineArgsParser above}, returning a fully-populated + * {@link CommandLineArgs} object. + * @param args command line arguments, typically from a {@code main()} method + */ + public CommandLineArgs parse(String... args) { + CommandLineArgs commandLineArgs = new CommandLineArgs(); + for (String arg : args) { + if (arg.startsWith("--")) { + String optionText = arg.substring(2, arg.length()); + String optionName; + String optionValue = null; + if (optionText.contains("=")) { + optionName = optionText.substring(0, optionText.indexOf("=")); + optionValue = optionText.substring(optionText.indexOf("=")+1, optionText.length()); + } + else { + optionName = optionText; + } + if (optionName.isEmpty() || (optionValue != null && optionValue.isEmpty())) { + throw new IllegalArgumentException("Invalid argument syntax: " + arg); + } + commandLineArgs.addOptionArg(optionName, optionValue); + } + else { + commandLineArgs.addNonOptionArg(arg); + } + } + return commandLineArgs; + } + +} \ No newline at end of file
true
Other
spring-projects
spring-framework
1eb581134794ba7d4926f6d10d4dc8a70de247ec.json
Introduce CommandLinePropertySource and impls Users may now work with command line arguments as a source of properties for use with the PropertySource and Environment APIs. An implementation based on the jopt library and a "simple" implementation requiring no external libraries are are provided out-of-the box. See Javadoc for CommandLinePropertySource, JOptCommandLinePropertySource and SimpleCommandLinePropertySource for details. Issue: SPR-8482
org.springframework.core/src/main/java/org/springframework/core/env/SimpleCommandLinePropertySource.java
@@ -0,0 +1,113 @@ +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core.env; + +import java.util.List; + +/** + * {@link CommandLinePropertySource} implementation backed by a simple String array. + * + * <h3>Purpose</h3> + * This {@code CommandLinePropertySource} implementation aims to provide the simplest + * possible approach to parsing command line arguments. As with all {@code + * CommandLinePropertySource} implementations, command line arguments are broken into two + * distinct groups: <em>option arguments</em> and <em>non-option arguments</em>, as + * described below <em>(some sections copied from Javadoc for {@link SimpleCommandLineArgsParser})</em>: + * + * <h3>Working with option arguments</h3> + * Option arguments must adhere to the exact syntax: + * <pre class="code">--optName[=optValue]</pre> + * That is, options must be prefixed with "{@code --}", and may or may not specify a value. + * If a value is specified, the name and value must be separated <em>without spaces</em> + * by an equals sign ("="). + * + * <h4>Valid examples of option arguments</h4> + * <pre class="code"> + * --foo + * --foo=bar + * --foo="bar then baz" + * --foo=bar,baz,biz</pre> + * + * <h4>Invalid examples of option arguments</h4> + * <pre class="code"> + * -foo + * --foo bar + * --foo = bar + * --foo=bar --foo=baz --foo=biz</pre> + * + * <h3>Working with non-option arguments</h3> + * Any and all arguments specified at the command line without the "{@code --}" option + * prefix will be considered as "non-option arguments" and made available through the + * {@link #getNonOptionArgs()} method. + * + * <h2>Typical usage</h2> + * <pre class="code"> + * public static void main(String[] args) { + * PropertySource<?> ps = new SimpleCommandLinePropertySource(args); + * // ... + * }</pre> + * + * See {@link CommandLinePropertySource} for complete general usage examples. + * + * <h3>Beyond the basics</h3> + * + * <p>When more fully-featured command line parsing is necessary, consider using + * the provided {@link JOptCommandLinePropertySource}, or implement your own + * {@code CommandLinePropertySource} against the command line parsing library of your + * choice! + * + * @author Chris Beams + * @since 3.1 + * @see CommandLinePropertySource + * @see JOptCommandLinePropertySource + */ +public class SimpleCommandLinePropertySource extends CommandLinePropertySource<CommandLineArgs> { + + /** + * Create a new {@code SimpleCommandLinePropertySource} having the default name + * and backed by the given {@code String[]} of command line arguments. + * @see CommandLinePropertySource#DEFAULT_COMMAND_LINE_PROPERTY_SOURCE_NAME + * @see CommandLinePropertySource#CommandLinePropertySource(Object) + */ + public SimpleCommandLinePropertySource(String... args) { + super(new SimpleCommandLineArgsParser().parse(args)); + } + + /** + * Create a new {@code SimpleCommandLinePropertySource} having the given name + * and backed by the given {@code String[]} of command line arguments. + */ + public SimpleCommandLinePropertySource(String name, String[] args) { + super(name, new SimpleCommandLineArgsParser().parse(args)); + } + + @Override + protected boolean containsOption(String key) { + return this.source.containsOption(key); + } + + @Override + protected List<String> getOptionValues(String key) { + return this.source.getOptionValues(key); + } + + @Override + protected List<String> getNonOptionArgs() { + return this.source.getNonOptionArgs(); + } + +}
true
Other
spring-projects
spring-framework
1eb581134794ba7d4926f6d10d4dc8a70de247ec.json
Introduce CommandLinePropertySource and impls Users may now work with command line arguments as a source of properties for use with the PropertySource and Environment APIs. An implementation based on the jopt library and a "simple" implementation requiring no external libraries are are provided out-of-the box. See Javadoc for CommandLinePropertySource, JOptCommandLinePropertySource and SimpleCommandLinePropertySource for details. Issue: SPR-8482
org.springframework.core/src/test/java/org/springframework/core/env/JOptCommandLinePropertySourceTests.java
@@ -0,0 +1,165 @@ +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core.env; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; + +import joptsimple.OptionParser; +import joptsimple.OptionSet; + +import org.junit.Test; + +/** + * Unit tests for {@link JOptCommandLinePropertySource}. + * + * @author Chris Beams + * @since 3.1 + */ +public class JOptCommandLinePropertySourceTests { + + @Test + public void withRequiredArg_andArgIsPresent() { + OptionParser parser = new OptionParser(); + parser.accepts("foo").withRequiredArg(); + OptionSet options = parser.parse("--foo=bar"); + + PropertySource<?> ps = new JOptCommandLinePropertySource(options); + assertThat((String)ps.getProperty("foo"), equalTo("bar")); + } + + @Test + public void withOptionalArg_andArgIsMissing() { + OptionParser parser = new OptionParser(); + parser.accepts("foo").withOptionalArg(); + OptionSet options = parser.parse("--foo"); + + PropertySource<?> ps = new JOptCommandLinePropertySource(options); + assertThat(ps.containsProperty("foo"), is(true)); + assertThat((String)ps.getProperty("foo"), equalTo("")); + } + + @Test + public void withNoArg() { + OptionParser parser = new OptionParser(); + parser.accepts("o1"); + parser.accepts("o2"); + OptionSet options = parser.parse("--o1"); + + PropertySource<?> ps = new JOptCommandLinePropertySource(options); + assertThat(ps.containsProperty("o1"), is(true)); + assertThat(ps.containsProperty("o2"), is(false)); + assertThat((String)ps.getProperty("o1"), equalTo("")); + assertThat(ps.getProperty("o2"), nullValue()); + } + + @Test + public void withRequiredArg_andMultipleArgsPresent_usingDelimiter() { + OptionParser parser = new OptionParser(); + parser.accepts("foo").withRequiredArg().withValuesSeparatedBy(','); + OptionSet options = parser.parse("--foo=bar,baz,biz"); + + CommandLinePropertySource<?> ps = new JOptCommandLinePropertySource(options); + assertEquals(Arrays.asList("bar","baz","biz"), ps.getOptionValues("foo")); + assertThat(ps.getProperty("foo"), equalTo("bar,baz,biz")); + } + + @Test + public void withRequiredArg_andMultipleArgsPresent_usingRepeatedOption() { + OptionParser parser = new OptionParser(); + parser.accepts("foo").withRequiredArg().withValuesSeparatedBy(','); + OptionSet options = parser.parse("--foo=bar", "--foo=baz", "--foo=biz"); + + CommandLinePropertySource<?> ps = new JOptCommandLinePropertySource(options); + assertEquals(Arrays.asList("bar","baz","biz"), ps.getOptionValues("foo")); + assertThat(ps.getProperty("foo"), equalTo("bar,baz,biz")); + } + + @Test + public void withMissingOption() { + OptionParser parser = new OptionParser(); + parser.accepts("foo").withRequiredArg().withValuesSeparatedBy(','); + OptionSet options = parser.parse(); // <-- no options whatsoever + + PropertySource<?> ps = new JOptCommandLinePropertySource(options); + assertThat(ps.getProperty("foo"), nullValue()); + } + + @Test + public void withDottedOptionName() { + OptionParser parser = new OptionParser(); + parser.accepts("spring.profiles.active").withRequiredArg(); + OptionSet options = parser.parse("--spring.profiles.active=p1"); + + CommandLinePropertySource<?> ps = new JOptCommandLinePropertySource(options); + assertThat(ps.getProperty("spring.profiles.active"), equalTo("p1")); + } + + @Test + public void withDefaultNonOptionArgsNameAndNoNonOptionArgsPresent() { + OptionParser parser = new OptionParser(); + parser.accepts("o1").withRequiredArg(); + parser.accepts("o2"); + OptionSet optionSet = parser.parse("--o1=v1", "--o2"); + PropertySource<?> ps = new JOptCommandLinePropertySource(optionSet); + + assertThat(ps.containsProperty("nonOptionArgs"), is(false)); + assertThat(ps.containsProperty("o1"), is(true)); + assertThat(ps.containsProperty("o2"), is(true)); + + assertThat(ps.containsProperty("nonOptionArgs"), is(false)); + assertThat(ps.getProperty("nonOptionArgs"), nullValue()); + } + + @Test + public void withDefaultNonOptionArgsNameAndNonOptionArgsPresent() { + OptionParser parser = new OptionParser(); + parser.accepts("o1").withRequiredArg(); + parser.accepts("o2"); + OptionSet optionSet = parser.parse("--o1=v1", "noa1", "--o2", "noa2"); + PropertySource<?> ps = new JOptCommandLinePropertySource(optionSet); + + assertThat(ps.containsProperty("nonOptionArgs"), is(true)); + assertThat(ps.containsProperty("o1"), is(true)); + assertThat(ps.containsProperty("o2"), is(true)); + + String nonOptionArgs = (String)ps.getProperty("nonOptionArgs"); + assertThat(nonOptionArgs, equalTo("noa1,noa2")); + } + + @Test + public void withCustomNonOptionArgsNameAndNoNonOptionArgsPresent() { + OptionParser parser = new OptionParser(); + parser.accepts("o1").withRequiredArg(); + parser.accepts("o2"); + OptionSet optionSet = parser.parse("--o1=v1", "noa1", "--o2", "noa2"); + CommandLinePropertySource<?> ps = new JOptCommandLinePropertySource(optionSet); + ps.setNonOptionArgsPropertyName("NOA"); + + assertThat(ps.containsProperty("nonOptionArgs"), is(false)); + assertThat(ps.containsProperty("NOA"), is(true)); + assertThat(ps.containsProperty("o1"), is(true)); + assertThat(ps.containsProperty("o2"), is(true)); + String nonOptionArgs = ps.getProperty("NOA"); + assertThat(nonOptionArgs, equalTo("noa1,noa2")); + } +}
true
Other
spring-projects
spring-framework
1eb581134794ba7d4926f6d10d4dc8a70de247ec.json
Introduce CommandLinePropertySource and impls Users may now work with command line arguments as a source of properties for use with the PropertySource and Environment APIs. An implementation based on the jopt library and a "simple" implementation requiring no external libraries are are provided out-of-the box. See Javadoc for CommandLinePropertySource, JOptCommandLinePropertySource and SimpleCommandLinePropertySource for details. Issue: SPR-8482
org.springframework.core/src/test/java/org/springframework/core/env/SimpleCommandLineParserTests.java
@@ -0,0 +1,114 @@ +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core.env; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + +import java.util.Collections; +import java.util.List; + +import org.junit.Test; + +public class SimpleCommandLineParserTests { + + @Test + public void withNoOptions() { + SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); + assertThat(parser.parse().getOptionValues("foo"), nullValue()); + } + + @Test + public void withSingleOptionAndNoValue() { + SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); + CommandLineArgs args = parser.parse("--o1"); + assertThat(args.containsOption("o1"), is(true)); + assertThat(args.getOptionValues("o1"), equalTo(Collections.EMPTY_LIST)); + } + + @Test + public void withSingleOptionAndValue() { + SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); + CommandLineArgs args = parser.parse("--o1=v1"); + assertThat(args.containsOption("o1"), is(true)); + assertThat(args.getOptionValues("o1").get(0), equalTo("v1")); + } + + @Test + public void withMixOfOptionsHavingValueAndOptionsHavingNoValue() { + SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); + CommandLineArgs args = parser.parse("--o1=v1", "--o2"); + assertThat(args.containsOption("o1"), is(true)); + assertThat(args.containsOption("o2"), is(true)); + assertThat(args.containsOption("o3"), is(false)); + assertThat(args.getOptionValues("o1").get(0), equalTo("v1")); + assertThat(args.getOptionValues("o2"), equalTo(Collections.EMPTY_LIST)); + assertThat(args.getOptionValues("o3"), nullValue()); + } + + @Test(expected=IllegalArgumentException.class) + public void withEmptyOptionText() { + SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); + parser.parse("--"); + } + + @Test(expected=IllegalArgumentException.class) + public void withEmptyOptionName() { + SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); + parser.parse("--=v1"); + } + + @Test(expected=IllegalArgumentException.class) + public void withEmptyOptionValue() { + SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); + parser.parse("--o1="); + } + + @Test(expected=IllegalArgumentException.class) + public void withEmptyOptionNameAndEmptyOptionValue() { + SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); + parser.parse("--="); + } + + @Test + public void withNonOptionArguments() { + SimpleCommandLineArgsParser parser = new SimpleCommandLineArgsParser(); + CommandLineArgs args = parser.parse("--o1=v1", "noa1", "--o2=v2", "noa2"); + assertThat(args.getOptionValues("o1").get(0), equalTo("v1")); + assertThat(args.getOptionValues("o2").get(0), equalTo("v2")); + + List<String> nonOptions = args.getNonOptionArgs(); + assertThat(nonOptions.get(0), equalTo("noa1")); + assertThat(nonOptions.get(1), equalTo("noa2")); + assertThat(nonOptions.size(), equalTo(2)); + } + + @Test(expected=UnsupportedOperationException.class) + public void assertOptionNamesIsUnmodifiable() { + CommandLineArgs args = new SimpleCommandLineArgsParser().parse(); + args.getOptionNames().add("bogus"); + } + + @Test(expected=UnsupportedOperationException.class) + public void assertNonOptionArgsIsUnmodifiable() { + CommandLineArgs args = new SimpleCommandLineArgsParser().parse(); + args.getNonOptionArgs().add("foo"); + } + +}
true
Other
spring-projects
spring-framework
1eb581134794ba7d4926f6d10d4dc8a70de247ec.json
Introduce CommandLinePropertySource and impls Users may now work with command line arguments as a source of properties for use with the PropertySource and Environment APIs. An implementation based on the jopt library and a "simple" implementation requiring no external libraries are are provided out-of-the box. See Javadoc for CommandLinePropertySource, JOptCommandLinePropertySource and SimpleCommandLinePropertySource for details. Issue: SPR-8482
org.springframework.core/src/test/java/org/springframework/core/env/SimpleCommandLinePropertySourceTests.java
@@ -0,0 +1,126 @@ +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core.env; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.junit.Test; + +/** + * Unit tests for {@link SimpleCommandLinePropertySource}. + * + * @author Chris Beams + * @since 3.1 + */ +public class SimpleCommandLinePropertySourceTests { + + @Test + public void withDefaultName() { + PropertySource<?> ps = new SimpleCommandLinePropertySource(); + assertThat(ps.getName(), + equalTo(CommandLinePropertySource.DEFAULT_COMMAND_LINE_PROPERTY_SOURCE_NAME)); + } + + @Test + public void withCustomName() { + PropertySource<?> ps = new SimpleCommandLinePropertySource("ps1", new String[0]); + assertThat(ps.getName(), equalTo("ps1")); + } + + @Test + public void withNoArgs() { + PropertySource<?> ps = new SimpleCommandLinePropertySource(); + assertThat(ps.containsProperty("foo"), is(false)); + assertThat(ps.getProperty("foo"), nullValue()); + } + + @Test + public void withOptionArgsOnly() { + CommandLinePropertySource<?> ps = + new SimpleCommandLinePropertySource("--o1=v1", "--o2"); + assertThat(ps.containsProperty("o1"), is(true)); + assertThat(ps.containsProperty("o2"), is(true)); + assertThat(ps.containsProperty("o3"), is(false)); + assertThat(ps.getProperty("o1"), equalTo("v1")); + assertThat(ps.getProperty("o2"), equalTo("")); + assertThat(ps.getProperty("o3"), nullValue()); + } + + @Test + public void withDefaultNonOptionArgsNameAndNoNonOptionArgsPresent() { + PropertySource<?> ps = new SimpleCommandLinePropertySource("--o1=v1", "--o2"); + + assertThat(ps.containsProperty("nonOptionArgs"), is(false)); + assertThat(ps.containsProperty("o1"), is(true)); + assertThat(ps.containsProperty("o2"), is(true)); + + assertThat(ps.containsProperty("nonOptionArgs"), is(false)); + assertThat(ps.getProperty("nonOptionArgs"), nullValue()); + } + + @Test + public void withDefaultNonOptionArgsNameAndNonOptionArgsPresent() { + CommandLinePropertySource<?> ps = + new SimpleCommandLinePropertySource("--o1=v1", "noa1", "--o2", "noa2"); + + assertThat(ps.containsProperty("nonOptionArgs"), is(true)); + assertThat(ps.containsProperty("o1"), is(true)); + assertThat(ps.containsProperty("o2"), is(true)); + + String nonOptionArgs = ps.getProperty("nonOptionArgs"); + assertThat(nonOptionArgs, equalTo("noa1,noa2")); + } + + @Test + public void withCustomNonOptionArgsNameAndNoNonOptionArgsPresent() { + CommandLinePropertySource<?> ps = + new SimpleCommandLinePropertySource("--o1=v1", "noa1", "--o2", "noa2"); + ps.setNonOptionArgsPropertyName("NOA"); + + assertThat(ps.containsProperty("nonOptionArgs"), is(false)); + assertThat(ps.containsProperty("NOA"), is(true)); + assertThat(ps.containsProperty("o1"), is(true)); + assertThat(ps.containsProperty("o2"), is(true)); + String nonOptionArgs = ps.getProperty("NOA"); + assertThat(nonOptionArgs, equalTo("noa1,noa2")); + } + + @Test + public void covertNonOptionArgsToStringArrayAndList() { + CommandLinePropertySource<?> ps = + new SimpleCommandLinePropertySource("--o1=v1", "noa1", "--o2", "noa2"); + StandardEnvironment env = new StandardEnvironment(); + env.getPropertySources().addFirst(ps); + + String nonOptionArgs = env.getProperty("nonOptionArgs"); + assertThat(nonOptionArgs, equalTo("noa1,noa2")); + + String[] nonOptionArgsArray = env.getProperty("nonOptionArgs", String[].class); + assertThat(nonOptionArgsArray[0], equalTo("noa1")); + assertThat(nonOptionArgsArray[1], equalTo("noa2")); + + @SuppressWarnings("unchecked") + List<String> nonOptionArgsList = env.getProperty("nonOptionArgs", List.class); + assertThat(nonOptionArgsList.get(0), equalTo("noa1")); + assertThat(nonOptionArgsList.get(1), equalTo("noa2")); + } +}
true
Other
spring-projects
spring-framework
1eb581134794ba7d4926f6d10d4dc8a70de247ec.json
Introduce CommandLinePropertySource and impls Users may now work with command line arguments as a source of properties for use with the PropertySource and Environment APIs. An implementation based on the jopt library and a "simple" implementation requiring no external libraries are are provided out-of-the box. See Javadoc for CommandLinePropertySource, JOptCommandLinePropertySource and SimpleCommandLinePropertySource for details. Issue: SPR-8482
org.springframework.core/template.mf
@@ -11,6 +11,7 @@ Import-Template: org.apache.commons.logging.*;version="[1.1.1, 2.0.0)", org.springframework.asm.*;version=${spring.osgi.range};resolution:=optional, org.apache.log4j.*;version="[1.2.15, 2.0.0)";resolution:=optional, + joptsimple.*;version="[3.0.0, 4.0.0)";resolution:=optional, org.aspectj.*;version=${aj.osgi.range};resolution:=optional, org.xml.sax.*;version="0";resolution:=optional, org.w3c.dom.*;version="0";resolution:=optional
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java
@@ -30,6 +30,7 @@ import org.aspectj.weaver.BCException; import org.aspectj.weaver.patterns.NamePattern; import org.aspectj.weaver.reflect.ReflectionWorld; +import org.aspectj.weaver.reflect.ReflectionWorld.ReflectionWorldException; import org.aspectj.weaver.reflect.ShadowMatchImpl; import org.aspectj.weaver.tools.ContextBasedMatcher; import org.aspectj.weaver.tools.FuzzyBoolean; @@ -41,7 +42,6 @@ import org.aspectj.weaver.tools.PointcutParser; import org.aspectj.weaver.tools.PointcutPrimitive; import org.aspectj.weaver.tools.ShadowMatch; - import org.springframework.aop.ClassFilter; import org.springframework.aop.IntroductionAwareMethodMatcher; import org.springframework.aop.MethodMatcher; @@ -73,6 +73,7 @@ * @author Rod Johnson * @author Juergen Hoeller * @author Ramnivas Laddad + * @author Dave Syer * @since 2.0 */ public class AspectJExpressionPointcut extends AbstractExpressionPointcut @@ -186,30 +187,40 @@ private void checkReadyToMatch() { * Build the underlying AspectJ pointcut expression. */ private PointcutExpression buildPointcutExpression() { - PointcutParser parser = initializePointcutParser(); + ClassLoader cl = (this.beanFactory instanceof ConfigurableBeanFactory ? ((ConfigurableBeanFactory) this.beanFactory) + .getBeanClassLoader() : Thread.currentThread() + .getContextClassLoader()); + return buildPointcutExpression(cl); + } + + /** + * Build the underlying AspectJ pointcut expression. + */ + private PointcutExpression buildPointcutExpression(ClassLoader classLoader) { + PointcutParser parser = initializePointcutParser(classLoader); PointcutParameter[] pointcutParameters = new PointcutParameter[this.pointcutParameterNames.length]; for (int i = 0; i < pointcutParameters.length; i++) { pointcutParameters[i] = parser.createPointcutParameter( - this.pointcutParameterNames[i], this.pointcutParameterTypes[i]); + this.pointcutParameterNames[i], + this.pointcutParameterTypes[i]); } return parser.parsePointcutExpression( - replaceBooleanOperators(getExpression()), this.pointcutDeclarationScope, pointcutParameters); + replaceBooleanOperators(getExpression()), + this.pointcutDeclarationScope, pointcutParameters); } /** * Initialize the underlying AspectJ pointcut parser. */ - private PointcutParser initializePointcutParser() { - ClassLoader cl = (this.beanFactory instanceof ConfigurableBeanFactory ? - ((ConfigurableBeanFactory) this.beanFactory).getBeanClassLoader() : - Thread.currentThread().getContextClassLoader()); - PointcutParser parser = - PointcutParser.getPointcutParserSupportingSpecifiedPrimitivesAndUsingSpecifiedClassLoaderForResolution( + private PointcutParser initializePointcutParser(ClassLoader cl) { + PointcutParser parser = PointcutParser + .getPointcutParserSupportingSpecifiedPrimitivesAndUsingSpecifiedClassLoaderForResolution( SUPPORTED_PRIMITIVES, cl); parser.registerPointcutDesignatorHandler(new BeanNamePointcutDesignatorHandler()); return parser; } + /** * If a pointcut expression has been specified in XML, the user cannot * write <code>and</code> as "&&" (though &amp;&amp; will work). @@ -236,7 +247,19 @@ public boolean matches(Class targetClass) { checkReadyToMatch(); try { return this.pointcutExpression.couldMatchJoinPointsInType(targetClass); - } + } catch (ReflectionWorldException e) { + logger.debug("PointcutExpression matching rejected target class", e); + try { + // Actually this is still a "maybe" - treat the pointcut as dynamic if we + // don't know enough yet + return getFallbackPointcutExpression(targetClass).couldMatchJoinPointsInType(targetClass); + } catch (BCException ex) { + logger.debug( + "Fallback PointcutExpression matching rejected target class", + ex); + return false; + } + } catch (BCException ex) { logger.debug("PointcutExpression matching rejected target class", ex); return false; @@ -308,7 +331,7 @@ public boolean matches(Method method, Class targetClass, Object[] args) { * <p>See SPR-2979 for the original bug. */ if (pmi != null) { // there is a current invocation - RuntimeTestWalker originalMethodResidueTest = new RuntimeTestWalker(originalShadowMatch); + RuntimeTestWalker originalMethodResidueTest = getRuntimeTestWalker(originalShadowMatch); if (!originalMethodResidueTest.testThisInstanceOfResidue(thisObject.getClass())) { return false; } @@ -325,18 +348,35 @@ protected String getCurrentProxiedBeanName() { } + /** + * Get a new pointcut expression based on a target class's loader, rather + * than the default. + */ + private PointcutExpression getFallbackPointcutExpression( + Class<?> targetClass) { + ClassLoader classLoader = targetClass.getClassLoader(); + return classLoader == null ? this.pointcutExpression : buildPointcutExpression(classLoader); + } + /** * A match test returned maybe - if there are any subtype sensitive variables * involved in the test (this, target, at_this, at_target, at_annotation) then * we say this is not a match as in Spring there will never be a different * runtime subtype. */ private boolean matchesIgnoringSubtypes(ShadowMatch shadowMatch) { - return !(new RuntimeTestWalker(shadowMatch).testsSubtypeSensitiveVars()); + return !(getRuntimeTestWalker(shadowMatch).testsSubtypeSensitiveVars()); } private boolean matchesTarget(ShadowMatch shadowMatch, Class targetClass) { - return new RuntimeTestWalker(shadowMatch).testTargetInstanceOfResidue(targetClass); + return getRuntimeTestWalker(shadowMatch).testTargetInstanceOfResidue(targetClass); + } + + private RuntimeTestWalker getRuntimeTestWalker(ShadowMatch shadowMatch) { + if (shadowMatch instanceof DefensiveShadowMatch) { + return new RuntimeTestWalker(((DefensiveShadowMatch)shadowMatch).primary); + } + return new RuntimeTestWalker(shadowMatch); } private void bindParameters(ProxyMethodInvocation invocation, JoinPointMatch jpm) { @@ -355,28 +395,45 @@ private ShadowMatch getShadowMatch(Method targetMethod, Method originalMethod) { if (shadowMatch == null) { synchronized (this.shadowMatchCache) { // Not found - now check again with full lock... - shadowMatch = this.shadowMatchCache.get(targetMethod); + Method methodToMatch = targetMethod; + PointcutExpression fallbackPointcutExpression = null; + shadowMatch = this.shadowMatchCache.get(methodToMatch); if (shadowMatch == null) { try { shadowMatch = this.pointcutExpression.matchesMethodExecution(targetMethod); } catch (ReflectionWorld.ReflectionWorldException ex) { // Failed to introspect target method, probably because it has been loaded // in a special ClassLoader. Let's try the original method instead... - if (targetMethod == originalMethod) { - shadowMatch = new ShadowMatchImpl(org.aspectj.util.FuzzyBoolean.NO, null, null, null); - } - else { - try { - shadowMatch = this.pointcutExpression.matchesMethodExecution(originalMethod); - } - catch (ReflectionWorld.ReflectionWorldException ex2) { - // Could neither introspect the target class nor the proxy class -> - // let's simply consider this method as non-matching. + try { + fallbackPointcutExpression = getFallbackPointcutExpression(methodToMatch.getDeclaringClass()); + shadowMatch = fallbackPointcutExpression.matchesMethodExecution(methodToMatch); + } catch (ReflectionWorld.ReflectionWorldException e) { + if (targetMethod == originalMethod) { shadowMatch = new ShadowMatchImpl(org.aspectj.util.FuzzyBoolean.NO, null, null, null); } + else { + try { + shadowMatch = this.pointcutExpression.matchesMethodExecution(originalMethod); + } + catch (ReflectionWorld.ReflectionWorldException ex2) { + // Could neither introspect the target class nor the proxy class -> + // let's simply consider this method as non-matching. + methodToMatch = originalMethod; + fallbackPointcutExpression = getFallbackPointcutExpression(methodToMatch.getDeclaringClass()); + try { + shadowMatch = fallbackPointcutExpression.matchesMethodExecution(methodToMatch); + } catch (ReflectionWorld.ReflectionWorldException e2) { + shadowMatch = new ShadowMatchImpl(org.aspectj.util.FuzzyBoolean.NO, null, null, null); + } + } + } } } + if (shadowMatch.maybeMatches() && fallbackPointcutExpression!=null) { + shadowMatch = new DefensiveShadowMatch(shadowMatch, + fallbackPointcutExpression.matchesMethodExecution(methodToMatch)); + } this.shadowMatchCache.put(targetMethod, shadowMatch); } } @@ -543,4 +600,42 @@ private void readObject(ObjectInputStream ois) throws IOException, ClassNotFound this.shadowMatchCache = new ConcurrentHashMap<Method, ShadowMatch>(32); } + private static class DefensiveShadowMatch implements ShadowMatch { + + private final ShadowMatch primary; + private final ShadowMatch other; + + public DefensiveShadowMatch(ShadowMatch primary, ShadowMatch other) { + this.primary = primary; + this.other = other; + } + + public boolean alwaysMatches() { + return primary.alwaysMatches(); + } + + public boolean maybeMatches() { + return primary.maybeMatches(); + } + + public boolean neverMatches() { + return primary.neverMatches(); + } + + public JoinPointMatch matchesJoinPoint(Object thisObject, + Object targetObject, Object[] args) { + try { + return primary.matchesJoinPoint(thisObject, targetObject, args); + } catch (ReflectionWorldException e) { + return other.matchesJoinPoint(thisObject, targetObject, args); + } + } + + public void setMatchingContext(MatchingContext aMatchContext) { + primary.setMatchingContext(aMatchContext); + other.setMatchingContext(aMatchContext); + } + + } + }
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.aop/src/test/java/org/springframework/aop/aspectj/TrickyAspectJPointcutExpressionTests.java
@@ -0,0 +1,174 @@ +package org.springframework.aop.aspectj; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.reflect.Method; + +import org.junit.Test; +import org.springframework.aop.Advisor; +import org.springframework.aop.MethodBeforeAdvice; +import org.springframework.aop.ThrowsAdvice; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.aop.support.DefaultPointcutAdvisor; +import org.springframework.core.OverridingClassLoader; + +/** + * @author Dave Syer + */ +public class TrickyAspectJPointcutExpressionTests { + + @Test + public void testManualProxyJavaWithUnconditionalPointcut() throws Exception { + TestService target = new TestServiceImpl(); + LogUserAdvice logAdvice = new LogUserAdvice(); + testAdvice(new DefaultPointcutAdvisor(logAdvice), logAdvice, target, "TestServiceImpl"); + } + + @Test + public void testManualProxyJavaWithStaticPointcut() throws Exception { + TestService target = new TestServiceImpl(); + LogUserAdvice logAdvice = new LogUserAdvice(); + AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); + pointcut.setExpression(String.format("execution(* %s.TestService.*(..))", getClass().getName())); + testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "TestServiceImpl"); + } + + @Test + public void testManualProxyJavaWithDynamicPointcut() throws Exception { + TestService target = new TestServiceImpl(); + LogUserAdvice logAdvice = new LogUserAdvice(); + AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); + pointcut.setExpression(String.format("@within(%s.Log)", getClass().getName())); + testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "TestServiceImpl"); + } + + @Test + public void testManualProxyJavaWithDynamicPointcutAndProxyTargetClass() throws Exception { + TestService target = new TestServiceImpl(); + LogUserAdvice logAdvice = new LogUserAdvice(); + AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); + pointcut.setExpression(String.format("@within(%s.Log)", getClass().getName())); + testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "TestServiceImpl", true); + } + + @Test + public void testManualProxyJavaWithStaticPointcutAndTwoClassLoaders() throws Exception { + + LogUserAdvice logAdvice = new LogUserAdvice(); + AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); + pointcut.setExpression(String.format("execution(* %s.TestService.*(..))", getClass().getName())); + + // Test with default class loader first... + testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, new TestServiceImpl(), "TestServiceImpl"); + + // Then try again with a different class loader on the target... + SimpleThrowawayClassLoader loader = new SimpleThrowawayClassLoader(new TestServiceImpl().getClass().getClassLoader()); + // Make sure the interface is loaded from the parent class loader + loader.excludeClass(TestService.class.getName()); + loader.excludeClass(TestException.class.getName()); + TestService other = (TestService) loader.loadClass(TestServiceImpl.class.getName()).newInstance(); + testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, other, "TestServiceImpl"); + + } + + private void testAdvice(Advisor advisor, LogUserAdvice logAdvice, TestService target, String message) + throws Exception { + testAdvice(advisor, logAdvice, target, message, false); + } + + private void testAdvice(Advisor advisor, LogUserAdvice logAdvice, TestService target, String message, + boolean proxyTargetClass) throws Exception { + + logAdvice.reset(); + + ProxyFactory factory = new ProxyFactory(target); + factory.setProxyTargetClass(proxyTargetClass); + factory.addAdvisor(advisor); + TestService bean = (TestService) factory.getProxy(); + + assertEquals(0, logAdvice.getCountThrows()); + try { + bean.sayHello(); + fail("Expected exception"); + } catch (TestException e) { + assertEquals(message, e.getMessage()); + } + assertEquals(1, logAdvice.getCountThrows()); + } + + public static class SimpleThrowawayClassLoader extends OverridingClassLoader { + + /** + * Create a new SimpleThrowawayClassLoader for the given class loader. + * @param parent the ClassLoader to build a throwaway ClassLoader for + */ + public SimpleThrowawayClassLoader(ClassLoader parent) { + super(parent); + } + + } + + public static class TestException extends RuntimeException { + + public TestException(String string) { + super(string); + } + + } + + @Target({ ElementType.METHOD, ElementType.TYPE }) + @Retention(RetentionPolicy.RUNTIME) + @Documented + @Inherited + public static @interface Log { + } + + public static interface TestService { + public String sayHello(); + } + + @Log + public static class TestServiceImpl implements TestService{ + public String sayHello() { + throw new TestException("TestServiceImpl"); + } + } + + public class LogUserAdvice implements MethodBeforeAdvice, ThrowsAdvice { + + private int countBefore = 0; + + private int countThrows = 0; + + public void before(Method method, Object[] objects, Object o) throws Throwable { + countBefore++; + } + + public void afterThrowing(Exception e) throws Throwable { + countThrows++; + throw e; + } + + public int getCountBefore() { + return countBefore; + } + + public int getCountThrows() { + return countThrows; + } + + public void reset() { + countThrows = 0; + countBefore = 0; + } + + } + +}
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests-groovy-dynamic-context.xml
@@ -0,0 +1,21 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:lang="http://www.springframework.org/schema/lang" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:p="http://www.springframework.org/schema/p" + xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd + http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd + http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> + + <aop:config > + <aop:advisor id="logUserAdvisor" pointcut="@within(org.springframework.scripting.groovy.Log)" advice-ref="logUserAdvice"/> + </aop:config> + + <bean id="logUserAdvice" class="org.springframework.scripting.groovy.LogUserAdvice" /> + + <!-- N.B. the pointcut never matches if refresh-delay is set (because proxy-target-class is always false) --> + <lang:groovy id="groovyBean" script-source="classpath:/org/springframework/scripting/groovy/GroovyServiceImpl.grv" refresh-check-delay="1000"/> + +</beans> \ No newline at end of file
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests-groovy-interface-context.xml
@@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:lang="http://www.springframework.org/schema/lang" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:p="http://www.springframework.org/schema/p" + xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd + http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd + http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> + + <aop:config > + <aop:advisor id="logUserAdvisor" pointcut="@within(org.springframework.scripting.groovy.Log)" advice-ref="logUserAdvice"/> + </aop:config> + + <bean id="logUserAdvice" class="org.springframework.scripting.groovy.LogUserAdvice" /> + + <lang:groovy id="groovyBean" script-source="classpath:/org/springframework/scripting/groovy/GroovyServiceImpl.grv"/> + +</beans> \ No newline at end of file
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests-groovy-proxy-target-class-context.xml
@@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:lang="http://www.springframework.org/schema/lang" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:p="http://www.springframework.org/schema/p" + xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd + http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd + http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> + + <aop:config > + <aop:advisor id="logUserAdvisor" pointcut="@within(org.springframework.scripting.groovy.Log)" advice-ref="logUserAdvice"/> + </aop:config> + + <bean id="logUserAdvice" class="org.springframework.scripting.groovy.LogUserAdvice" /> + + <lang:groovy id="groovyBean" script-source="classpath:/org/springframework/scripting/groovy/GroovyServiceImpl.grv" refresh-check-delay="1000" proxy-target-class="true"/> + +</beans> \ No newline at end of file
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests-java-context.xml
@@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:lang="http://www.springframework.org/schema/lang" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:p="http://www.springframework.org/schema/p" + xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd + http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd + http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> + + <aop:config > + <aop:advisor id="logUserAdvisor" pointcut="@within(org.springframework.scripting.groovy.Log)" advice-ref="logUserAdvice"/> + </aop:config> + + <bean id="logUserAdvice" class="org.springframework.scripting.groovy.LogUserAdvice" /> + + <bean id="javaBean" class="org.springframework.scripting.groovy.TestServiceImpl"/> + +</beans> \ No newline at end of file
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.context/src/test/java/org/springframework/scripting/groovy/GroovyAspectIntegrationTests.java
@@ -0,0 +1,100 @@ +package org.springframework.scripting.groovy; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.After; +import org.junit.Test; +import org.springframework.context.support.GenericXmlApplicationContext; + +/** + * @author Dave Syer + */ +public class GroovyAspectIntegrationTests { + + private GenericXmlApplicationContext context; + + @After + public void close() { + if (context != null) { + context.close(); + } + } + + @Test + public void testJavaBean() { + + context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName()+"-java-context.xml"); + + TestService bean = context.getBean("javaBean", TestService.class); + LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); + + assertEquals(0, logAdvice.getCountThrows()); + try { + bean.sayHello(); + fail("Expected exception"); + } catch (RuntimeException e) { + assertEquals("TestServiceImpl", e.getMessage()); + } + assertEquals(1, logAdvice.getCountThrows()); + + } + + @Test + public void testGroovyBeanInterface() { + context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName()+"-groovy-interface-context.xml"); + + TestService bean = context.getBean("groovyBean", TestService.class); + LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); + + assertEquals(0, logAdvice.getCountThrows()); + try { + bean.sayHello(); + fail("Expected exception"); + } catch (RuntimeException e) { + assertEquals("GroovyServiceImpl", e.getMessage()); + } + assertEquals(1, logAdvice.getCountThrows()); + } + + + @Test + public void testGroovyBeanDynamic() { + + context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName()+"-groovy-dynamic-context.xml"); + + TestService bean = context.getBean("groovyBean", TestService.class); + LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); + + assertEquals(0, logAdvice.getCountThrows()); + try { + bean.sayHello(); + fail("Expected exception"); + } catch (RuntimeException e) { + assertEquals("GroovyServiceImpl", e.getMessage()); + } + // No proxy here because the pointcut only applies to the concrete class, not the interface + assertEquals(0, logAdvice.getCountThrows()); + assertEquals(0, logAdvice.getCountBefore()); + } + + @Test + public void testGroovyBeanProxyTargetClass() { + + context = new GenericXmlApplicationContext(getClass(), getClass().getSimpleName()+"-groovy-proxy-target-class-context.xml"); + + TestService bean = context.getBean("groovyBean", TestService.class); + LogUserAdvice logAdvice = context.getBean(LogUserAdvice.class); + + assertEquals(0, logAdvice.getCountThrows()); + try { + bean.sayHello(); + fail("Expected exception"); + } catch (TestException e) { + assertEquals("GroovyServiceImpl", e.getMessage()); + } + assertEquals(1, logAdvice.getCountBefore()); + assertEquals(1, logAdvice.getCountThrows()); + } + +}
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.context/src/test/java/org/springframework/scripting/groovy/GroovyAspectTests.java
@@ -0,0 +1,101 @@ +package org.springframework.scripting.groovy; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; +import org.springframework.aop.Advisor; +import org.springframework.aop.aspectj.AspectJExpressionPointcut; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.aop.support.DefaultPointcutAdvisor; +import org.springframework.core.io.ClassPathResource; +import org.springframework.scripting.groovy.GroovyScriptFactory; +import org.springframework.scripting.support.ResourceScriptSource; +import org.springframework.util.ClassUtils; + +/** + * @author Dave Syer + */ +public class GroovyAspectTests { + + @Test + public void testManualGroovyBeanWithUnconditionalPointcut() throws Exception { + + LogUserAdvice logAdvice = new LogUserAdvice(); + + GroovyScriptFactory scriptFactory = new GroovyScriptFactory("GroovyServiceImpl.grv"); + TestService target = (TestService) scriptFactory.getScriptedObject(new ResourceScriptSource( + new ClassPathResource("GroovyServiceImpl.grv", getClass())), null); + + testAdvice(new DefaultPointcutAdvisor(logAdvice), logAdvice, target, "GroovyServiceImpl"); + + } + + @Test + public void testManualGroovyBeanWithStaticPointcut() throws Exception { + LogUserAdvice logAdvice = new LogUserAdvice(); + + GroovyScriptFactory scriptFactory = new GroovyScriptFactory("GroovyServiceImpl.grv"); + TestService target = (TestService) scriptFactory.getScriptedObject(new ResourceScriptSource( + new ClassPathResource("GroovyServiceImpl.grv", getClass())), null); + + AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); + pointcut.setExpression(String.format("execution(* %s.TestService+.*(..))", ClassUtils.getPackageName(getClass()))); + testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "GroovyServiceImpl", true); + } + + @Test + public void testManualGroovyBeanWithDynamicPointcut() throws Exception { + + LogUserAdvice logAdvice = new LogUserAdvice(); + + GroovyScriptFactory scriptFactory = new GroovyScriptFactory("GroovyServiceImpl.grv"); + TestService target = (TestService) scriptFactory.getScriptedObject(new ResourceScriptSource( + new ClassPathResource("GroovyServiceImpl.grv", getClass())), null); + + AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); + pointcut.setExpression(String.format("@within(%s.Log)", ClassUtils.getPackageName(getClass()))); + testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "GroovyServiceImpl", false); + + } + + @Test + public void testManualGroovyBeanWithDynamicPointcutProxyTargetClass() throws Exception { + + LogUserAdvice logAdvice = new LogUserAdvice(); + + GroovyScriptFactory scriptFactory = new GroovyScriptFactory("GroovyServiceImpl.grv"); + TestService target = (TestService) scriptFactory.getScriptedObject(new ResourceScriptSource( + new ClassPathResource("GroovyServiceImpl.grv", getClass())), null); + + AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); + pointcut.setExpression(String.format("@within(%s.Log)", ClassUtils.getPackageName(getClass()))); + testAdvice(new DefaultPointcutAdvisor(pointcut, logAdvice), logAdvice, target, "GroovyServiceImpl", true); + + } + + private void testAdvice(Advisor advisor, LogUserAdvice logAdvice, TestService target, String message) + throws Exception { + testAdvice(advisor, logAdvice, target, message, false); + } + + private void testAdvice(Advisor advisor, LogUserAdvice logAdvice, TestService target, String message, + boolean proxyTargetClass) throws Exception { + + logAdvice.reset(); + + ProxyFactory factory = new ProxyFactory(target); + factory.setProxyTargetClass(proxyTargetClass); + factory.addAdvisor(advisor); + TestService bean = (TestService) factory.getProxy(); + + assertEquals(0, logAdvice.getCountThrows()); + try { + bean.sayHello(); + fail("Expected exception"); + } catch (TestException e) { + assertEquals(message, e.getMessage()); + } + assertEquals(1, logAdvice.getCountThrows()); + } +}
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.context/src/test/java/org/springframework/scripting/groovy/GroovyServiceImpl.grv
@@ -0,0 +1,11 @@ +package org.springframework.scripting.groovy; + +@Log +public class GroovyServiceImpl implements TestService { + + public String sayHello() { + throw new TestException("GroovyServiceImpl"); + } + + +} \ No newline at end of file
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.context/src/test/java/org/springframework/scripting/groovy/Log.java
@@ -0,0 +1,15 @@ +package org.springframework.scripting.groovy; + +import java.lang.annotation.Inherited; +import java.lang.annotation.Target; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Documented; + +@Target({ ElementType.METHOD, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Inherited +public @interface Log { +}
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.context/src/test/java/org/springframework/scripting/groovy/LogUserAdvice.java
@@ -0,0 +1,41 @@ +package org.springframework.scripting.groovy; + +import java.lang.reflect.Method; + +import org.springframework.aop.MethodBeforeAdvice; +import org.springframework.aop.ThrowsAdvice; + +public class LogUserAdvice implements MethodBeforeAdvice, ThrowsAdvice { + + private int countBefore = 0; + + private int countThrows = 0; + + public void before(Method method, Object[] objects, Object o) throws Throwable { + countBefore++; + System.out.println("Method:"+method.getName()); + } + + public void afterThrowing(Exception e) throws Throwable { + countThrows++; + System.out.println("***********************************************************************************"); + System.out.println("Exception caught:"); + System.out.println("***********************************************************************************"); + e.printStackTrace(); + throw e; + } + + public int getCountBefore() { + return countBefore; + } + + public int getCountThrows() { + return countThrows; + } + + public void reset() { + countThrows = 0; + countBefore = 0; + } + +}
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.context/src/test/java/org/springframework/scripting/groovy/TestException.java
@@ -0,0 +1,29 @@ +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.scripting.groovy; + +/** + * @author Dave Syer + * + */ +public class TestException extends RuntimeException { + + public TestException(String string) { + super(string); + } + +}
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.context/src/test/java/org/springframework/scripting/groovy/TestService.java
@@ -0,0 +1,5 @@ +package org.springframework.scripting.groovy; + +public interface TestService { + public String sayHello(); +}
true
Other
spring-projects
spring-framework
bd0f68d095ba881621b8499925334de38a6b1051.json
SPR-5749: Add defensive matching using target class loader * Changes to ASpectJExpressionPointcut plus some tests in Spring AOP * plus some tests in groovy support
org.springframework.context/src/test/java/org/springframework/scripting/groovy/TestServiceImpl.java
@@ -0,0 +1,8 @@ +package org.springframework.scripting.groovy; + +@Log +public class TestServiceImpl implements TestService{ + public String sayHello() { + throw new TestException("TestServiceImpl"); + } +}
true
Other
spring-projects
spring-framework
fd4b9cf6a333a8eb1affe204370ebff6a9f5c114.json
SPR-6881: remove extra dependency
org.springframework.web.portlet/pom.xml
@@ -86,12 +86,6 @@ <version>${project.version}</version> <scope>compile</scope> </dependency> - <dependency> - <groupId>org.springframework</groupId> - <artifactId>spring-asm</artifactId> - <version>${project.version}</version> - <scope>compile</scope> - </dependency> <dependency> <groupId>org.easymock</groupId> <artifactId>easymock</artifactId>
false
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.aop/pom.xml
@@ -4,12 +4,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent> <dependencies>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.asm/pom.xml
@@ -4,12 +4,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-asm</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.aspects/pom.xml
@@ -4,12 +4,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent> <dependencies>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.beans/pom.xml
@@ -4,12 +4,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent> <dependencies>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.context.support/pom.xml
@@ -4,12 +4,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.context/pom.xml
@@ -6,12 +6,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent> <dependencies>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.core/pom.xml
@@ -6,12 +6,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent> <dependencies>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.expression/pom.xml
@@ -4,12 +4,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent> <dependencies>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.instrument.tomcat/pom.xml
@@ -4,12 +4,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-instrument-tomcat</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent> <dependencies>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.instrument/pom.xml
@@ -4,12 +4,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-instrument</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent> </project>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.integration-tests/pom.xml
@@ -4,12 +4,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-integration-tests</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent> <dependencies> <dependency>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.jdbc/pom.xml
@@ -4,12 +4,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent> <dependencies> <dependency>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.jms/pom.xml
@@ -4,12 +4,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent> <dependencies>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.orm/pom.xml
@@ -6,12 +6,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent> <dependencies> <dependency>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.oxm/pom.xml
@@ -6,12 +6,12 @@ <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <packaging>jar</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <parent> <groupId>org.springframework</groupId> <artifactId>spring-parent</artifactId> <relativePath>../org.springframework.spring-parent</relativePath> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> </parent> <dependencies>
true
Other
spring-projects
spring-framework
1a351db6e0b62f5b4bc74f7dfc3acb9cba40f4c3.json
Update Central POMs to 3.0.2
org.springframework.spring-library/pom.xml
@@ -14,7 +14,7 @@ <groupId>org.springframework</groupId> <artifactId>spring-library</artifactId> <packaging>libd</packaging> - <version>3.0.1.BUILD-SNAPSHOT</version> + <version>3.0.2.BUILD-SNAPSHOT</version> <name>Spring Framework</name> <description>Spring is a layered Java/J2EE application platform, based on code published in Expert One-on-One J2EE Design and Development by Rod Johnson (Wrox, 2002). </description>
true