diff --git a/pom.xml b/pom.xml index 84db552..1725412 100644 --- a/pom.xml +++ b/pom.xml @@ -1,3 +1,4 @@ + 4.0.0 @@ -16,8 +17,8 @@ scm:git:https://github.com/codehaus-plexus/plexus-interpolation.git scm:git:https://github.com/codehaus-plexus/plexus-interpolation.git - http://github.com/codehaus-plexus/plexus-interpolation/tree/${project.scm.tag}/ master + http://github.com/codehaus-plexus/plexus-interpolation/tree/${project.scm.tag}/ @@ -60,15 +61,17 @@ org.apache.maven.plugins maven-scm-publish-plugin - ${project.reporting.outputDirectory} + ${project.reporting.outputDirectory} + scm-publish - site-deploy + publish-scm + site-deploy diff --git a/src/main/java/org/codehaus/plexus/interpolation/AbstractDelegatingValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/AbstractDelegatingValueSource.java index 9e05709..836c6b3 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/AbstractDelegatingValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/AbstractDelegatingValueSource.java @@ -18,40 +18,31 @@ import java.util.List; -public abstract class AbstractDelegatingValueSource - implements ValueSource -{ - +public abstract class AbstractDelegatingValueSource implements ValueSource { + private final ValueSource delegate; - protected AbstractDelegatingValueSource( ValueSource delegate ) - { - if ( delegate == null ) - { - throw new NullPointerException( "Delegate ValueSource cannot be null." ); + protected AbstractDelegatingValueSource(ValueSource delegate) { + if (delegate == null) { + throw new NullPointerException("Delegate ValueSource cannot be null."); } - + this.delegate = delegate; } - - protected ValueSource getDelegate() - { + + protected ValueSource getDelegate() { return delegate; } - public Object getValue( String expression ) - { - return getDelegate().getValue( expression ); + public Object getValue(String expression) { + return getDelegate().getValue(expression); } - - public void clearFeedback() - { + + public void clearFeedback() { delegate.clearFeedback(); } - public List getFeedback() - { + public List getFeedback() { return delegate.getFeedback(); } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/AbstractFunctionValueSourceWrapper.java b/src/main/java/org/codehaus/plexus/interpolation/AbstractFunctionValueSourceWrapper.java index bdd84e4..0082caf 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/AbstractFunctionValueSourceWrapper.java +++ b/src/main/java/org/codehaus/plexus/interpolation/AbstractFunctionValueSourceWrapper.java @@ -28,9 +28,7 @@ * value of the second expression, which is resolved from the wrapped value * source.

*/ -public abstract class AbstractFunctionValueSourceWrapper - implements ValueSource -{ +public abstract class AbstractFunctionValueSourceWrapper implements ValueSource { private final ValueSource valueSource; @@ -40,8 +38,7 @@ public abstract class AbstractFunctionValueSourceWrapper * * @param valueSource The value source to wrap */ - protected AbstractFunctionValueSourceWrapper( ValueSource valueSource ) - { + protected AbstractFunctionValueSourceWrapper(ValueSource valueSource) { this.valueSource = valueSource; } @@ -56,26 +53,23 @@ protected AbstractFunctionValueSourceWrapper( ValueSource valueSource ) * for the current expression. * */ - public Object getValue( String expression ) - { - Object value = valueSource.getValue( expression ); + public Object getValue(String expression) { + Object value = valueSource.getValue(expression); String expr = expression; - if ( valueSource instanceof QueryEnabledValueSource ) - { + if (valueSource instanceof QueryEnabledValueSource) { expr = ((QueryEnabledValueSource) valueSource).getLastExpression(); } - return executeFunction( expr, value ); + return executeFunction(expr, value); } /** * Retrieve the embedded value source. * @return {@link ValueSource} */ - protected ValueSource getValueSource() - { + protected ValueSource getValueSource() { return valueSource; } @@ -87,6 +81,5 @@ protected ValueSource getValueSource() * @param value The value for the current expression, resolved by the embedded {@link ValueSource} * @return The result of modifying the current expression's value using the function named by the last expression. */ - protected abstract Object executeFunction( String expression, Object value ); - + protected abstract Object executeFunction(String expression, Object value); } diff --git a/src/main/java/org/codehaus/plexus/interpolation/AbstractValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/AbstractValueSource.java index d2d9038..67a3495 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/AbstractValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/AbstractValueSource.java @@ -19,45 +19,34 @@ import java.util.ArrayList; import java.util.List; -public abstract class AbstractValueSource - implements ValueSource -{ - +public abstract class AbstractValueSource implements ValueSource { + private final List feedback; - - protected AbstractValueSource( boolean usesFeedback ) - { - if ( usesFeedback ) - { + + protected AbstractValueSource(boolean usesFeedback) { + if (usesFeedback) { feedback = new ArrayList(); - } - else - { + } else { feedback = null; } } - public void clearFeedback() - { - if ( feedback != null ) - { + public void clearFeedback() { + if (feedback != null) { feedback.clear(); } } - public List getFeedback() - { + public List getFeedback() { return feedback; } - protected void addFeedback( String message ) - { - feedback.add( message ); + protected void addFeedback(String message) { + feedback.add(message); } - - protected void addFeedback( String message, Throwable cause ) - { - feedback.add( message ); - feedback.add( cause ); + + protected void addFeedback(String message, Throwable cause) { + feedback.add(message); + feedback.add(cause); } } diff --git a/src/main/java/org/codehaus/plexus/interpolation/BasicInterpolator.java b/src/main/java/org/codehaus/plexus/interpolation/BasicInterpolator.java index f0df0ef..7b0870a 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/BasicInterpolator.java +++ b/src/main/java/org/codehaus/plexus/interpolation/BasicInterpolator.java @@ -20,8 +20,7 @@ * * TODO: Really really needs a way to communicate errors. */ -public interface BasicInterpolator -{ +public interface BasicInterpolator { /** * See {@link org.codehaus.plexus.interpolation.Interpolator#interpolate(String, String, org.codehaus.plexus.interpolation.RecursionInterceptor)}. *

@@ -34,8 +33,7 @@ public interface BasicInterpolator * @return the interpolated string. * @throws InterpolationException in case of an error. */ - String interpolate( String input ) - throws InterpolationException; + String interpolate(String input) throws InterpolationException; /** * See {@link org.codehaus.plexus.interpolation.Interpolator#interpolate(String, String, org.codehaus.plexus.interpolation.RecursionInterceptor)}. @@ -52,6 +50,5 @@ String interpolate( String input ) * @return the interpolated string. * @throws InterpolationException in case of an error. */ - String interpolate( String input, RecursionInterceptor recursionInterceptor ) - throws InterpolationException; + String interpolate(String input, RecursionInterceptor recursionInterceptor) throws InterpolationException; } diff --git a/src/main/java/org/codehaus/plexus/interpolation/EnvarBasedValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/EnvarBasedValueSource.java index 729952e..f954a4d 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/EnvarBasedValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/EnvarBasedValueSource.java @@ -16,20 +16,18 @@ * limitations under the License. */ -import org.codehaus.plexus.interpolation.os.OperatingSystemUtils; - import java.io.IOException; import java.util.Properties; +import org.codehaus.plexus.interpolation.os.OperatingSystemUtils; + /** * {@link ValueSource} which resolves expressions against the environment variables * available from the underlying operating system (and possibly, the shell environment * that created the present Java process). If the expression starts with 'env.', * this prefix is trimmed before resolving the rest as an environment variable name. */ -public class EnvarBasedValueSource - extends AbstractValueSource -{ +public class EnvarBasedValueSource extends AbstractValueSource { private static Properties envarsCaseSensitive; private static Properties envarsCaseInsensitive; @@ -43,9 +41,8 @@ public class EnvarBasedValueSource * * @throws IOException in case of an error. */ - public EnvarBasedValueSource() throws IOException - { - this( true ); + public EnvarBasedValueSource() throws IOException { + this(true); } /** @@ -55,29 +52,21 @@ public EnvarBasedValueSource() throws IOException * case-sensitive manner for lookups * @throws IOException in case of an error. */ - public EnvarBasedValueSource( boolean caseSensitive ) throws IOException - { - super( false ); + public EnvarBasedValueSource(boolean caseSensitive) throws IOException { + super(false); this.caseSensitive = caseSensitive; - this.envars = getEnvars( caseSensitive ); + this.envars = getEnvars(caseSensitive); } - private static synchronized Properties getEnvars( boolean caseSensitive ) - throws IOException - { - if ( caseSensitive ) - { - if ( envarsCaseSensitive == null ) - { - envarsCaseSensitive = OperatingSystemUtils.getSystemEnvVars( caseSensitive ); + private static synchronized Properties getEnvars(boolean caseSensitive) throws IOException { + if (caseSensitive) { + if (envarsCaseSensitive == null) { + envarsCaseSensitive = OperatingSystemUtils.getSystemEnvVars(caseSensitive); } return envarsCaseSensitive; - } - else - { - if ( envarsCaseInsensitive == null ) - { - envarsCaseInsensitive = OperatingSystemUtils.getSystemEnvVars( caseSensitive ); + } else { + if (envarsCaseInsensitive == null) { + envarsCaseInsensitive = OperatingSystemUtils.getSystemEnvVars(caseSensitive); } return envarsCaseInsensitive; } @@ -92,30 +81,25 @@ private static synchronized Properties getEnvars( boolean caseSensitive ) * @param expression envar expression, like 'HOME' or 'env.HOME' * @return the environment variable value for the given expression */ - public Object getValue( String expression ) - { + public Object getValue(String expression) { String expr = expression; - if ( expr.startsWith( "env." ) ) - { - expr = expr.substring( "env.".length() ); + if (expr.startsWith("env.")) { + expr = expr.substring("env.".length()); } - if ( !caseSensitive ) - { + if (!caseSensitive) { expr = expr.toUpperCase(); } - return envars.getProperty( expr ); + return envars.getProperty(expr); } - + /** * reset static variables acting as a cache for testing purposes only */ - static void resetStatics() - { + static void resetStatics() { envarsCaseSensitive = null; envarsCaseInsensitive = null; } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/FeedbackEnabledValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/FeedbackEnabledValueSource.java index 3186311..7217b94 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/FeedbackEnabledValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/FeedbackEnabledValueSource.java @@ -16,7 +16,6 @@ * limitations under the License. */ - /** * Represents a {@link ValueSource} which provides information back to the caller * about what may have gone wrong while resolving the value for an expression. @@ -25,7 +24,4 @@ * * @deprecated Rolled into {@link ValueSource} now. */ -public interface FeedbackEnabledValueSource - extends ValueSource -{ -} +public interface FeedbackEnabledValueSource extends ValueSource {} diff --git a/src/main/java/org/codehaus/plexus/interpolation/FixedInterpolatorValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/FixedInterpolatorValueSource.java index 8ff2611..fa13b27 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/FixedInterpolatorValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/FixedInterpolatorValueSource.java @@ -1,40 +1,34 @@ package org.codehaus.plexus.interpolation; +import java.util.List; + import org.codehaus.plexus.interpolation.fixed.FixedStringSearchInterpolator; import org.codehaus.plexus.interpolation.fixed.InterpolationState; -import java.util.List; - /** * A value source that allows a fixed interpolator to be injected into * a regular interpolator. This value source encapsulates state, so even though * the fixed interpolator can be used as a singleton, a single FixedInterpolatorValueSource * can only belong to one interpolator any given time. */ -public class FixedInterpolatorValueSource implements ValueSource +public class FixedInterpolatorValueSource implements ValueSource { -{ private final FixedStringSearchInterpolator fixedStringSearchInterpolator; private final InterpolationState errorCollector = new InterpolationState(); - public FixedInterpolatorValueSource( FixedStringSearchInterpolator fixedStringSearchInterpolator ) - { + public FixedInterpolatorValueSource(FixedStringSearchInterpolator fixedStringSearchInterpolator) { this.fixedStringSearchInterpolator = fixedStringSearchInterpolator; } - public Object getValue( String expression ) - { - return fixedStringSearchInterpolator.getValue( expression, errorCollector ); + public Object getValue(String expression) { + return fixedStringSearchInterpolator.getValue(expression, errorCollector); } - public List getFeedback() - { + public List getFeedback() { return errorCollector.asList(); } - public void clearFeedback() - { + public void clearFeedback() { errorCollector.clear(); - } } diff --git a/src/main/java/org/codehaus/plexus/interpolation/InterpolationCycleException.java b/src/main/java/org/codehaus/plexus/interpolation/InterpolationCycleException.java index d00b52a..8391f33 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/InterpolationCycleException.java +++ b/src/main/java/org/codehaus/plexus/interpolation/InterpolationCycleException.java @@ -16,17 +16,14 @@ * limitations under the License. */ -public class InterpolationCycleException - extends InterpolationException -{ - +public class InterpolationCycleException extends InterpolationException { + private static final long serialVersionUID = 1L; - public InterpolationCycleException( RecursionInterceptor recursionInterceptor, String realExpr, String wholeExpr ) - { - super( "Detected the following recursive expression cycle in '" + realExpr + "': " - + recursionInterceptor.getExpressionCycle( realExpr ), wholeExpr ); - + public InterpolationCycleException(RecursionInterceptor recursionInterceptor, String realExpr, String wholeExpr) { + super( + "Detected the following recursive expression cycle in '" + realExpr + "': " + + recursionInterceptor.getExpressionCycle(realExpr), + wholeExpr); } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/InterpolationException.java b/src/main/java/org/codehaus/plexus/interpolation/InterpolationException.java index b1958a6..780003d 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/InterpolationException.java +++ b/src/main/java/org/codehaus/plexus/interpolation/InterpolationException.java @@ -24,14 +24,12 @@ * particular expression part, should NOT result in InterpolationExceptions * being thrown. Instead, they should be reported in the feedback from the {@link ValueSource}, * which is propagated out through {@link Interpolator#getFeedback()}. - * + * */ -public class InterpolationException - extends Exception -{ +public class InterpolationException extends Exception { private static final long serialVersionUID = 1L; - + private final String expression; /** @@ -39,11 +37,8 @@ public class InterpolationException * @param expression The expression that triggered the problem * @param cause The wrapped exception */ - public InterpolationException( String message, - String expression, - Throwable cause ) - { - super( buildMessage( message, expression ), cause ); + public InterpolationException(String message, String expression, Throwable cause) { + super(buildMessage(message, expression), cause); this.expression = expression; } @@ -51,24 +46,19 @@ public InterpolationException( String message, * @param message The general description of the problem * @param expression The expression that triggered the problem */ - public InterpolationException( String message, String expression ) - { - super( buildMessage( message, expression ) ); + public InterpolationException(String message, String expression) { + super(buildMessage(message, expression)); this.expression = expression; } - private static String buildMessage( String message, - String expression ) - { + private static String buildMessage(String message, String expression) { return "Resolving expression: '" + expression + "': " + message; } /** * @return The expression that triggered this exception. */ - public String getExpression() - { + public String getExpression() { return expression; } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/InterpolationPostProcessor.java b/src/main/java/org/codehaus/plexus/interpolation/InterpolationPostProcessor.java index 0ec8130..0028efa 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/InterpolationPostProcessor.java +++ b/src/main/java/org/codehaus/plexus/interpolation/InterpolationPostProcessor.java @@ -20,18 +20,16 @@ * Used to allow full recursion of value interpolation before applying some rule * to the result. */ -public interface InterpolationPostProcessor -{ - +public interface InterpolationPostProcessor { + /** * Given the starting expression and the fully-recursively-interpolated value, * perform some post-processing step and return the resulting [possibly different] * value, or null if no change was made.. - * + * * @param expression the original expression * @param value the original value after fully recursive interpolation of expression * @return the processed value if a change was made; else return null */ - Object execute( String expression, Object value ); - + Object execute(String expression, Object value); } diff --git a/src/main/java/org/codehaus/plexus/interpolation/Interpolator.java b/src/main/java/org/codehaus/plexus/interpolation/Interpolator.java index 83ac37a..7ed2c88 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/Interpolator.java +++ b/src/main/java/org/codehaus/plexus/interpolation/Interpolator.java @@ -23,36 +23,34 @@ * * @author cstamas */ -public interface Interpolator - extends BasicInterpolator -{ +public interface Interpolator extends BasicInterpolator { /** * Add a new {@link ValueSource} to the stack used to resolve expressions * in this interpolator instance. * @param valueSource {@link ValueSource}. */ - void addValueSource( ValueSource valueSource ); + void addValueSource(ValueSource valueSource); /** * Remove the specified {@link ValueSource} from the stack used to resolve * expressions in this interpolator instance. * @param valueSource {@link ValueSource}. */ - void removeValuesSource( ValueSource valueSource ); - + void removeValuesSource(ValueSource valueSource); + /** - * Add a new post-processor to handle final processing after + * Add a new post-processor to handle final processing after * recursively-interpolated value is determined. * @param postProcessor {@link InterpolationPostProcessor}. */ - void addPostProcessor( InterpolationPostProcessor postProcessor ); + void addPostProcessor(InterpolationPostProcessor postProcessor); /** * Remove the given post-processor. * @param postProcessor {@link InterpolationPostProcessor}. */ - void removePostProcessor( InterpolationPostProcessor postProcessor ); + void removePostProcessor(InterpolationPostProcessor postProcessor); /** * See {@link Interpolator#interpolate(String, String, RecursionInterceptor)}. @@ -67,9 +65,7 @@ public interface Interpolator * @return interpolated string. * @throws InterpolationException in case of an error. */ - String interpolate( String input, - String thisPrefixPattern ) - throws InterpolationException; + String interpolate(String input, String thisPrefixPattern) throws InterpolationException; /** * Attempt to resolve all expressions in the given input string, using the @@ -89,10 +85,8 @@ String interpolate( String input, * @return interpolated string. * @throws InterpolationException in case of an error. */ - String interpolate( String input, - String thisPrefixPattern, - RecursionInterceptor recursionInterceptor ) - throws InterpolationException; + String interpolate(String input, String thisPrefixPattern, RecursionInterceptor recursionInterceptor) + throws InterpolationException; /** * Return any feedback messages and errors that were generated - but @@ -109,7 +103,7 @@ String interpolate( String input, * Clear the feedback messages from previous interpolate(..) calls. */ void clearFeedback(); - + /** * @return state of the cacheAnswers */ @@ -118,7 +112,7 @@ String interpolate( String input, /** * @param cacheAnswers true/false. */ - void setCacheAnswers( boolean cacheAnswers ); - + void setCacheAnswers(boolean cacheAnswers); + void clearAnswers(); } diff --git a/src/main/java/org/codehaus/plexus/interpolation/InterpolatorFilterReader.java b/src/main/java/org/codehaus/plexus/interpolation/InterpolatorFilterReader.java index 43ebab0..6cd55c6 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/InterpolatorFilterReader.java +++ b/src/main/java/org/codehaus/plexus/interpolation/InterpolatorFilterReader.java @@ -64,13 +64,11 @@ * * @author cstamas */ -public class InterpolatorFilterReader - extends FilterReader -{ +public class InterpolatorFilterReader extends FilterReader { /** Interpolator used to interpolate */ private Interpolator interpolator; - + /** * @since 1.12 */ @@ -90,56 +88,53 @@ public class InterpolatorFilterReader /** Default end token. */ public static final String DEFAULT_END_TOKEN = "}"; - + private String beginToken; - + private String orginalBeginToken; - + private String endToken; - + /** true by default to preserve backward comp */ private boolean interpolateWithPrefixPattern = true; private String escapeString; - + private boolean useEscape = false; - + /** if true escapeString will be preserved \{foo} -> \{foo} */ private boolean preserveEscapeString = false; - + /** - * this constructor use default begin token ${ and default end token } + * this constructor use default begin token ${ and default end token } * @param in reader to use * @param interpolator interpolator instance to use */ - public InterpolatorFilterReader( Reader in, Interpolator interpolator ) - { - this( in, interpolator, DEFAULT_BEGIN_TOKEN, DEFAULT_END_TOKEN ); + public InterpolatorFilterReader(Reader in, Interpolator interpolator) { + this(in, interpolator, DEFAULT_BEGIN_TOKEN, DEFAULT_END_TOKEN); } - + /** * @param in reader to use * @param interpolator interpolator instance to use * @param beginToken start token to use * @param endToken end token to use */ - public InterpolatorFilterReader( Reader in, Interpolator interpolator, String beginToken, String endToken ) - { - this( in, interpolator, beginToken, endToken, new SimpleRecursionInterceptor() ); - } + public InterpolatorFilterReader(Reader in, Interpolator interpolator, String beginToken, String endToken) { + this(in, interpolator, beginToken, endToken, new SimpleRecursionInterceptor()); + } /** - * this constructor use default begin token ${ and default end token } + * this constructor use default begin token ${ and default end token } * @param in reader to use * @param interpolator interpolator instance to use * @param ri The {@link RecursionInterceptor} to use to prevent recursive expressions. * @since 1.12 */ - public InterpolatorFilterReader( Reader in, Interpolator interpolator, RecursionInterceptor ri ) - { - this( in, interpolator, DEFAULT_BEGIN_TOKEN, DEFAULT_END_TOKEN, ri ); + public InterpolatorFilterReader(Reader in, Interpolator interpolator, RecursionInterceptor ri) { + this(in, interpolator, DEFAULT_BEGIN_TOKEN, DEFAULT_END_TOKEN, ri); } - + /** * @param in reader to use * @param interpolator interpolator instance to use @@ -148,20 +143,20 @@ public InterpolatorFilterReader( Reader in, Interpolator interpolator, Recursion * @param ri The {@link RecursionInterceptor} to use to prevent recursive expressions. * @since 1.12 */ - public InterpolatorFilterReader( Reader in, Interpolator interpolator, String beginToken, String endToken, RecursionInterceptor ri ) - { - super( in ); + public InterpolatorFilterReader( + Reader in, Interpolator interpolator, String beginToken, String endToken, RecursionInterceptor ri) { + super(in); this.interpolator = interpolator; - + this.beginToken = beginToken; - + this.endToken = endToken; - + recursionInterceptor = ri; - + this.orginalBeginToken = this.beginToken; - } + } /** * Skips characters. This method will block until some characters are available, an I/O error occurs, or the end of @@ -172,18 +167,13 @@ public InterpolatorFilterReader( Reader in, Interpolator interpolator, String be * @exception IllegalArgumentException If n is negative. * @exception IOException If an I/O error occurs */ - public long skip( long n ) - throws IOException - { - if ( n < 0L ) - { - throw new IllegalArgumentException( "skip value is negative" ); + public long skip(long n) throws IOException { + if (n < 0L) { + throw new IllegalArgumentException("skip value is negative"); } - for ( long i = 0; i < n; i++ ) - { - if ( read() == -1 ) - { + for (long i = 0; i < n; i++) { + if (read() == -1) { return i; } } @@ -200,20 +190,13 @@ public long skip( long n ) * @return the number of characters read, or -1 if the end of the stream has been reached * @exception IOException If an I/O error occurs */ - public int read( char cbuf[], int off, int len ) - throws IOException - { - for ( int i = 0; i < len; i++ ) - { + public int read(char cbuf[], int off, int len) throws IOException { + for (int i = 0; i < len; i++) { int ch = read(); - if ( ch == -1 ) - { - if ( i == 0 ) - { + if (ch == -1) { + if (i == 0) { return -1; - } - else - { + } else { return i; } } @@ -228,198 +211,152 @@ public int read( char cbuf[], int off, int len ) * @return the next character in the resulting stream, or -1 if the end of the resulting stream has been reached * @exception IOException if the underlying stream throws an IOException during reading */ - public int read() - throws IOException - { - if ( replaceIndex != -1 && replaceIndex < replaceData.length() ) - { - int ch = replaceData.charAt( replaceIndex++ ); - if ( replaceIndex >= replaceData.length() ) - { + public int read() throws IOException { + if (replaceIndex != -1 && replaceIndex < replaceData.length()) { + int ch = replaceData.charAt(replaceIndex++); + if (replaceIndex >= replaceData.length()) { replaceIndex = -1; } return ch; } int ch = -1; - if ( previousIndex != -1 && previousIndex < this.endToken.length() ) - { - ch = this.endToken.charAt( previousIndex++ ); - } - else - { + if (previousIndex != -1 && previousIndex < this.endToken.length()) { + ch = this.endToken.charAt(previousIndex++); + } else { ch = in.read(); } - - if ( ch == this.beginToken.charAt( 0 ) || ( useEscape && ch == this.orginalBeginToken.charAt( 0 ) ) ) - { - StringBuilder key = new StringBuilder( ); - key.append( (char) ch ); + if (ch == this.beginToken.charAt(0) || (useEscape && ch == this.orginalBeginToken.charAt(0))) { + StringBuilder key = new StringBuilder(); + + key.append((char) ch); int beginTokenMatchPos = 1; - do - { - if ( previousIndex != -1 && previousIndex < this.endToken.length() ) - { - ch = this.endToken.charAt( previousIndex++ ); - } - else - { + do { + if (previousIndex != -1 && previousIndex < this.endToken.length()) { + ch = this.endToken.charAt(previousIndex++); + } else { ch = in.read(); } - if ( ch != -1 ) - { - key.append( (char) ch ); - if ( ( beginTokenMatchPos < this.beginToken.length() ) - && ( ch != this.beginToken.charAt( beginTokenMatchPos++ ) ) - && ( useEscape && this.orginalBeginToken.length() > ( beginTokenMatchPos - 1 ) && ch != this.orginalBeginToken - .charAt( beginTokenMatchPos - 1 ) ) ) - { + if (ch != -1) { + key.append((char) ch); + if ((beginTokenMatchPos < this.beginToken.length()) + && (ch != this.beginToken.charAt(beginTokenMatchPos++)) + && (useEscape + && this.orginalBeginToken.length() > (beginTokenMatchPos - 1) + && ch != this.orginalBeginToken.charAt(beginTokenMatchPos - 1))) { ch = -1; // not really EOF but to trigger code below break; } - } - else - { + } else { break; } // MSHARED-81 olamy : we must take care of token with length 1, escaping and same char : \@foo@ // here ch == endToken == beginToken -> not going to next char : bad :-) - if ( useEscape && this.orginalBeginToken == this.endToken && key.toString().startsWith( this.beginToken ) ) - { + if (useEscape + && this.orginalBeginToken == this.endToken + && key.toString().startsWith(this.beginToken)) { ch = in.read(); - key.append( (char) ch ); + key.append((char) ch); } - } - while ( ch != this.endToken.charAt( 0 ) ); + } while (ch != this.endToken.charAt(0)); // now test endToken - if ( ch != -1 && this.endToken.length() > 1 ) - { + if (ch != -1 && this.endToken.length() > 1) { int endTokenMatchPos = 1; - do - { - if ( previousIndex != -1 && previousIndex < this.endToken.length() ) - { - ch = this.endToken.charAt( previousIndex++ ); - } - else - { + do { + if (previousIndex != -1 && previousIndex < this.endToken.length()) { + ch = this.endToken.charAt(previousIndex++); + } else { ch = in.read(); } - if ( ch != -1 ) - { - key.append( (char) ch ); + if (ch != -1) { + key.append((char) ch); - if ( ch != this.endToken.charAt( endTokenMatchPos++ ) ) - { + if (ch != this.endToken.charAt(endTokenMatchPos++)) { ch = -1; // not really EOF but to trigger code below break; } - } - else - { + } else { break; } - } - while ( endTokenMatchPos < this.endToken.length() ); + } while (endTokenMatchPos < this.endToken.length()); } // There is nothing left to read so we have the situation where the begin/end token // are in fact the same and as there is nothing left to read we have got ourselves // end of a token boundary so let it pass through. - if ( ch == -1 ) - { + if (ch == -1) { replaceData = key.toString(); replaceIndex = 1; - return replaceData.charAt( 0 ); + return replaceData.charAt(0); } String value = null; - try - { + try { boolean escapeFound = false; - if ( useEscape ) - { - if ( key.toString().startsWith( escapeString + orginalBeginToken ) ) - { + if (useEscape) { + if (key.toString().startsWith(escapeString + orginalBeginToken)) { String keyStr = key.toString(); - if ( !preserveEscapeString ) - { - value = keyStr.substring( escapeString.length(), keyStr.length() ); - } - else - { + if (!preserveEscapeString) { + value = keyStr.substring(escapeString.length(), keyStr.length()); + } else { value = keyStr; } escapeFound = true; } } - if ( !escapeFound ) - { - if ( interpolateWithPrefixPattern ) - { - value = interpolator.interpolate( key.toString(), "", recursionInterceptor ); - } - else - { - value = interpolator.interpolate( key.toString(), recursionInterceptor ); + if (!escapeFound) { + if (interpolateWithPrefixPattern) { + value = interpolator.interpolate(key.toString(), "", recursionInterceptor); + } else { + value = interpolator.interpolate(key.toString(), recursionInterceptor); } } - } - catch ( InterpolationException e ) - { - IllegalArgumentException error = new IllegalArgumentException( e.getMessage() ); - error.initCause( e ); + } catch (InterpolationException e) { + IllegalArgumentException error = new IllegalArgumentException(e.getMessage()); + error.initCause(e); throw error; } - if ( value != null ) - { - if ( value.length() != 0 ) - { + if (value != null) { + if (value.length() != 0) { replaceData = value; replaceIndex = 0; } return read(); - } - else - { + } else { previousIndex = 0; - replaceData = key.substring( 0, key.length() - this.endToken.length() ); + replaceData = key.substring(0, key.length() - this.endToken.length()); replaceIndex = 0; - return this.beginToken.charAt( 0 ); + return this.beginToken.charAt(0); } } return ch; } - public boolean isInterpolateWithPrefixPattern() - { + public boolean isInterpolateWithPrefixPattern() { return interpolateWithPrefixPattern; } - public void setInterpolateWithPrefixPattern( boolean interpolateWithPrefixPattern ) - { + public void setInterpolateWithPrefixPattern(boolean interpolateWithPrefixPattern) { this.interpolateWithPrefixPattern = interpolateWithPrefixPattern; } - public String getEscapeString() - { + + public String getEscapeString() { return escapeString; } - public void setEscapeString( String escapeString ) - { + public void setEscapeString(String escapeString) { // TODO NPE if escapeString is null ? - if ( escapeString != null && escapeString.length() >= 1 ) - { + if (escapeString != null && escapeString.length() >= 1) { this.escapeString = escapeString; this.orginalBeginToken = beginToken; this.beginToken = escapeString + beginToken; @@ -427,23 +364,19 @@ public void setEscapeString( String escapeString ) } } - public boolean isPreserveEscapeString() - { + public boolean isPreserveEscapeString() { return preserveEscapeString; } - public void setPreserveEscapeString( boolean preserveEscapeString ) - { + public void setPreserveEscapeString(boolean preserveEscapeString) { this.preserveEscapeString = preserveEscapeString; } - public RecursionInterceptor getRecursionInterceptor() - { + public RecursionInterceptor getRecursionInterceptor() { return recursionInterceptor; } - public InterpolatorFilterReader setRecursionInterceptor( RecursionInterceptor recursionInterceptor ) - { + public InterpolatorFilterReader setRecursionInterceptor(RecursionInterceptor recursionInterceptor) { this.recursionInterceptor = recursionInterceptor; return this; } diff --git a/src/main/java/org/codehaus/plexus/interpolation/MapBasedValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/MapBasedValueSource.java index 917abc6..c9655f9 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/MapBasedValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/MapBasedValueSource.java @@ -22,9 +22,7 @@ * Wraps a Map, and looks up the whole expression as a single key, returning the * value mapped to it. */ -public class MapBasedValueSource - extends AbstractValueSource -{ +public class MapBasedValueSource extends AbstractValueSource { private final Map values; @@ -32,9 +30,8 @@ public class MapBasedValueSource * Construct a new value source to wrap the supplied map. * @param values key,value of mapping. */ - public MapBasedValueSource( Map values ) - { - super( false ); + public MapBasedValueSource(Map values) { + super(false); this.values = values; } @@ -42,9 +39,7 @@ public MapBasedValueSource( Map values ) * Lookup the supplied expression as a key in the wrapped Map, and return * its value. */ - public Object getValue( String expression ) - { - return values == null ? null : values.get( expression ); + public Object getValue(String expression) { + return values == null ? null : values.get(expression); } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/ObjectBasedValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/ObjectBasedValueSource.java index d95679b..4e4dcff 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/ObjectBasedValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/ObjectBasedValueSource.java @@ -24,9 +24,7 @@ * 'rootObject.getChild().getName()' for non-boolean properties, and * 'rootObject.getChild().isName()' for boolean properties. */ -public class ObjectBasedValueSource - extends AbstractValueSource -{ +public class ObjectBasedValueSource extends AbstractValueSource { private final Object root; @@ -36,9 +34,8 @@ public class ObjectBasedValueSource * the object graph beneath this root. * @param root the root of the graph. */ - public ObjectBasedValueSource( Object root ) - { - super( true ); + public ObjectBasedValueSource(Object root) { + super(true); this.root = root; } @@ -48,27 +45,21 @@ public ObjectBasedValueSource( Object root ) * to the object graph below this root, using either 'getXXX()' or 'isXXX()' * accessor types to resolve the value for each successive expression part. * Finally, return the result of the last expression part's resolution.

- * + * *

NOTE: The object-graph nagivation actually takes place via the * {@link ReflectionValueExtractor} class.

*/ - public Object getValue( String expression ) - { - if ( expression == null || expression.trim().length() < 1 ) - { + public Object getValue(String expression) { + if (expression == null || expression.trim().length() < 1) { return null; } - - try - { - return ReflectionValueExtractor.evaluate( expression, root, false ); - } - catch ( Exception e ) - { - addFeedback( "Failed to extract \'" + expression + "\' from: " + root, e ); + + try { + return ReflectionValueExtractor.evaluate(expression, root, false); + } catch (Exception e) { + addFeedback("Failed to extract \'" + expression + "\' from: " + root, e); } return null; } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/PrefixAwareRecursionInterceptor.java b/src/main/java/org/codehaus/plexus/interpolation/PrefixAwareRecursionInterceptor.java index dfdeb93..38a4e01 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/PrefixAwareRecursionInterceptor.java +++ b/src/main/java/org/codehaus/plexus/interpolation/PrefixAwareRecursionInterceptor.java @@ -16,13 +16,13 @@ * limitations under the License. */ -import org.codehaus.plexus.interpolation.util.ValueSourceUtils; - import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Stack; +import org.codehaus.plexus.interpolation.util.ValueSourceUtils; + /** * {@link RecursionInterceptor} implementation that provides support for expressions * with multiple synonyms, such as project.build.directory == pom.build.directory == @@ -30,9 +30,7 @@ * * @author jdcasey */ -public class PrefixAwareRecursionInterceptor - implements RecursionInterceptor -{ +public class PrefixAwareRecursionInterceptor implements RecursionInterceptor { public static final String DEFAULT_START_TOKEN = "\\$\\{"; @@ -51,9 +49,8 @@ public class PrefixAwareRecursionInterceptor * @param possiblePrefixes The collection of expression prefixes supported * @param watchUnprefixedExpressions Whether to consider unprefixed expressions as synonyms */ - public PrefixAwareRecursionInterceptor( Collection possiblePrefixes, boolean watchUnprefixedExpressions ) - { - this.possiblePrefixes = possiblePrefixes.toArray( new String[possiblePrefixes.size()]) ; + public PrefixAwareRecursionInterceptor(Collection possiblePrefixes, boolean watchUnprefixedExpressions) { + this.possiblePrefixes = possiblePrefixes.toArray(new String[possiblePrefixes.size()]); this.watchUnprefixedExpressions = watchUnprefixedExpressions; } @@ -63,27 +60,22 @@ public PrefixAwareRecursionInterceptor( Collection possiblePrefixes, boo * * @param possiblePrefixes The collection of expression prefixes supported */ - public PrefixAwareRecursionInterceptor( Collection possiblePrefixes ) - { - this.possiblePrefixes = possiblePrefixes.toArray( new String[possiblePrefixes.size()]) ; + public PrefixAwareRecursionInterceptor(Collection possiblePrefixes) { + this.possiblePrefixes = possiblePrefixes.toArray(new String[possiblePrefixes.size()]); } - public boolean hasRecursiveExpression( String expression ) - { - String realExpr = ValueSourceUtils.trimPrefix( expression, possiblePrefixes, watchUnprefixedExpressions ); - return realExpr != null && nakedExpressions.contains( realExpr ); - + public boolean hasRecursiveExpression(String expression) { + String realExpr = ValueSourceUtils.trimPrefix(expression, possiblePrefixes, watchUnprefixedExpressions); + return realExpr != null && nakedExpressions.contains(realExpr); } - public void expressionResolutionFinished( String expression ) - { + public void expressionResolutionFinished(String expression) { nakedExpressions.pop(); } - public void expressionResolutionStarted( String expression ) - { - String realExpr = ValueSourceUtils.trimPrefix( expression, possiblePrefixes, watchUnprefixedExpressions ); - nakedExpressions.push( realExpr ); + public void expressionResolutionStarted(String expression) { + String realExpr = ValueSourceUtils.trimPrefix(expression, possiblePrefixes, watchUnprefixedExpressions); + nakedExpressions.push(realExpr); } /** @@ -94,28 +86,22 @@ public void expressionResolutionStarted( String expression ) * prefix from this interceptor's list, and unprefixed expressions aren't allowed * then return {@link Collections#EMPTY_LIST}. */ - public List getExpressionCycle( String expression ) - { - String expr = ValueSourceUtils.trimPrefix( expression, possiblePrefixes, watchUnprefixedExpressions ); + public List getExpressionCycle(String expression) { + String expr = ValueSourceUtils.trimPrefix(expression, possiblePrefixes, watchUnprefixedExpressions); - if ( expr == null ) - { + if (expr == null) { return Collections.EMPTY_LIST; } - int idx = nakedExpressions.indexOf( expr ); - if ( idx < 0 ) - { + int idx = nakedExpressions.indexOf(expr); + if (idx < 0) { return Collections.EMPTY_LIST; - } - else - { - return nakedExpressions.subList( idx, nakedExpressions.size() ); + } else { + return nakedExpressions.subList(idx, nakedExpressions.size()); } } - public void clear() - { + public void clear() { nakedExpressions.clear(); } } diff --git a/src/main/java/org/codehaus/plexus/interpolation/PrefixedObjectValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/PrefixedObjectValueSource.java index a747a2c..81df33a 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/PrefixedObjectValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/PrefixedObjectValueSource.java @@ -27,19 +27,15 @@ * this class delegates all of its calls. * */ -public class PrefixedObjectValueSource - extends AbstractDelegatingValueSource - implements QueryEnabledValueSource -{ +public class PrefixedObjectValueSource extends AbstractDelegatingValueSource implements QueryEnabledValueSource { /** * Wrap the specified root object, allowing the specified expression prefix. * @param prefix the prefix. * @param root the root of the graph. */ - public PrefixedObjectValueSource( String prefix, Object root ) - { - super( new PrefixedValueSourceWrapper( new ObjectBasedValueSource( root ), prefix ) ); + public PrefixedObjectValueSource(String prefix, Object root) { + super(new PrefixedValueSourceWrapper(new ObjectBasedValueSource(root), prefix)); } /** @@ -50,17 +46,15 @@ public PrefixedObjectValueSource( String prefix, Object root ) * @param root The root of the graph. * @param allowUnprefixedExpressions if we allow undefined expressions or not. */ - public PrefixedObjectValueSource( List possiblePrefixes, Object root, boolean allowUnprefixedExpressions ) - { - super( new PrefixedValueSourceWrapper( new ObjectBasedValueSource( root ), possiblePrefixes, - allowUnprefixedExpressions ) ); + public PrefixedObjectValueSource(List possiblePrefixes, Object root, boolean allowUnprefixedExpressions) { + super(new PrefixedValueSourceWrapper( + new ObjectBasedValueSource(root), possiblePrefixes, allowUnprefixedExpressions)); } /** * {@inheritDoc} */ - public String getLastExpression() - { - return ( (QueryEnabledValueSource) getDelegate() ).getLastExpression(); + public String getLastExpression() { + return ((QueryEnabledValueSource) getDelegate()).getLastExpression(); } } diff --git a/src/main/java/org/codehaus/plexus/interpolation/PrefixedPropertiesValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/PrefixedPropertiesValueSource.java index f64a5f0..86025da 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/PrefixedPropertiesValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/PrefixedPropertiesValueSource.java @@ -29,10 +29,7 @@ * the properties value source and then wrapping it with a prefixed value-source wrapper.

* */ -public class PrefixedPropertiesValueSource - extends AbstractDelegatingValueSource - implements QueryEnabledValueSource -{ +public class PrefixedPropertiesValueSource extends AbstractDelegatingValueSource implements QueryEnabledValueSource { /** * Wrap the specified properties file with a new {@link PropertiesBasedValueSource}, then @@ -43,9 +40,8 @@ public class PrefixedPropertiesValueSource * @param prefix The expression prefix to trim * @param properties The properties instance to wrap */ - public PrefixedPropertiesValueSource( String prefix, Properties properties ) - { - super( new PrefixedValueSourceWrapper( new PropertiesBasedValueSource( properties ), prefix ) ); + public PrefixedPropertiesValueSource(String prefix, Properties properties) { + super(new PrefixedValueSourceWrapper(new PropertiesBasedValueSource(properties), prefix)); } /** @@ -58,19 +54,16 @@ public PrefixedPropertiesValueSource( String prefix, Properties properties ) * @param properties The properties instance to wrap * @param allowUnprefixedExpressions allow unprefixed expressions or not. */ - public PrefixedPropertiesValueSource( List possiblePrefixes, Properties properties, - boolean allowUnprefixedExpressions ) - { - super( new PrefixedValueSourceWrapper( new PropertiesBasedValueSource( properties ), possiblePrefixes, - allowUnprefixedExpressions ) ); + public PrefixedPropertiesValueSource( + List possiblePrefixes, Properties properties, boolean allowUnprefixedExpressions) { + super(new PrefixedValueSourceWrapper( + new PropertiesBasedValueSource(properties), possiblePrefixes, allowUnprefixedExpressions)); } /** * {@inheritDoc} */ - public String getLastExpression() - { - return ( (QueryEnabledValueSource) getDelegate() ).getLastExpression(); + public String getLastExpression() { + return ((QueryEnabledValueSource) getDelegate()).getLastExpression(); } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/PrefixedValueSourceWrapper.java b/src/main/java/org/codehaus/plexus/interpolation/PrefixedValueSourceWrapper.java index 0e2c522..407d847 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/PrefixedValueSourceWrapper.java +++ b/src/main/java/org/codehaus/plexus/interpolation/PrefixedValueSourceWrapper.java @@ -16,11 +16,11 @@ * limitations under the License. */ -import org.codehaus.plexus.interpolation.util.ValueSourceUtils; - import java.util.Collections; import java.util.List; +import org.codehaus.plexus.interpolation.util.ValueSourceUtils; + /** * {@link ValueSource} implementation which simply wraps another value source, * and trims any of a set of possible expression prefixes before delegating the @@ -28,9 +28,7 @@ * * @author jdcasey */ -public class PrefixedValueSourceWrapper - implements FeedbackEnabledValueSource, QueryEnabledValueSource -{ +public class PrefixedValueSourceWrapper implements FeedbackEnabledValueSource, QueryEnabledValueSource { private final ValueSource valueSource; @@ -48,10 +46,9 @@ public class PrefixedValueSourceWrapper * @param valueSource The {@link ValueSource} to wrap. * @param prefix The expression prefix to trim. */ - public PrefixedValueSourceWrapper( ValueSource valueSource, String prefix ) - { + public PrefixedValueSourceWrapper(ValueSource valueSource, String prefix) { this.valueSource = valueSource; - possiblePrefixes = new String[]{ prefix }; + possiblePrefixes = new String[] {prefix}; } /** @@ -67,10 +64,9 @@ public PrefixedValueSourceWrapper( ValueSource valueSource, String prefix ) * @param allowUnprefixedExpressions Flag telling the wrapper whether to * continue resolving expressions that don't start with the prefix it tracks. */ - public PrefixedValueSourceWrapper( ValueSource valueSource, String prefix, boolean allowUnprefixedExpressions ) - { + public PrefixedValueSourceWrapper(ValueSource valueSource, String prefix, boolean allowUnprefixedExpressions) { this.valueSource = valueSource; - possiblePrefixes = new String[]{ prefix }; + possiblePrefixes = new String[] {prefix}; this.allowUnprefixedExpressions = allowUnprefixedExpressions; } @@ -82,10 +78,9 @@ public PrefixedValueSourceWrapper( ValueSource valueSource, String prefix, boole * @param valueSource The {@link ValueSource} to wrap. * @param possiblePrefixes The List of expression prefixes to trim. */ - public PrefixedValueSourceWrapper( ValueSource valueSource, List possiblePrefixes ) - { + public PrefixedValueSourceWrapper(ValueSource valueSource, List possiblePrefixes) { this.valueSource = valueSource; - this.possiblePrefixes = possiblePrefixes.toArray( new String[possiblePrefixes.size()] ); + this.possiblePrefixes = possiblePrefixes.toArray(new String[possiblePrefixes.size()]); } /** @@ -101,11 +96,10 @@ public PrefixedValueSourceWrapper( ValueSource valueSource, List possibl * @param allowUnprefixedExpressions Flag telling the wrapper whether to * continue resolving expressions that don't start with one of the prefixes it tracks. */ - public PrefixedValueSourceWrapper( ValueSource valueSource, List possiblePrefixes, - boolean allowUnprefixedExpressions ) - { + public PrefixedValueSourceWrapper( + ValueSource valueSource, List possiblePrefixes, boolean allowUnprefixedExpressions) { this.valueSource = valueSource; - this.possiblePrefixes = possiblePrefixes.toArray( new String[possiblePrefixes.size()] ); + this.possiblePrefixes = possiblePrefixes.toArray(new String[possiblePrefixes.size()]); this.allowUnprefixedExpressions = allowUnprefixedExpressions; } @@ -116,27 +110,22 @@ public PrefixedValueSourceWrapper( ValueSource valueSource, List possibl * expressions are not allowed here), then return null; otherwise, return the * nested {@link ValueSource#getValue(String)} result. */ - public Object getValue( String expression ) - { - lastExpression = ValueSourceUtils.trimPrefix( expression, possiblePrefixes, allowUnprefixedExpressions ); + public Object getValue(String expression) { + lastExpression = ValueSourceUtils.trimPrefix(expression, possiblePrefixes, allowUnprefixedExpressions); - if ( lastExpression == null ) - { + if (lastExpression == null) { return null; } - return valueSource.getValue( lastExpression ); + return valueSource.getValue(lastExpression); } /** * If the nested {@link ValueSource} implements {@link FeedbackEnabledValueSource}, * then return that source's feedback list. Otherwise, return {@link Collections#EMPTY_LIST}. */ - public List getFeedback() - { - return ( valueSource instanceof FeedbackEnabledValueSource ) - ? valueSource.getFeedback() - : Collections.EMPTY_LIST; + public List getFeedback() { + return (valueSource instanceof FeedbackEnabledValueSource) ? valueSource.getFeedback() : Collections.EMPTY_LIST; } /** @@ -144,20 +133,17 @@ public List getFeedback() * then return that source's last expression. Otherwise, return the last expression * that was processed by the wrapper itself. */ - public String getLastExpression() - { - return ( valueSource instanceof QueryEnabledValueSource ) - ? ( (QueryEnabledValueSource) valueSource ).getLastExpression() - : lastExpression; + public String getLastExpression() { + return (valueSource instanceof QueryEnabledValueSource) + ? ((QueryEnabledValueSource) valueSource).getLastExpression() + : lastExpression; } /** * If the nested {@link ValueSource} implements {@link FeedbackEnabledValueSource}, * then clear that source's feedback list. */ - public void clearFeedback() - { + public void clearFeedback() { valueSource.clearFeedback(); } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/PropertiesBasedValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/PropertiesBasedValueSource.java index d4ee5b0..2f18c4c 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/PropertiesBasedValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/PropertiesBasedValueSource.java @@ -26,9 +26,7 @@ * * @author jdcasey */ -public class PropertiesBasedValueSource - extends AbstractValueSource -{ +public class PropertiesBasedValueSource extends AbstractValueSource { private final Properties properties; @@ -38,9 +36,8 @@ public class PropertiesBasedValueSource * * @param properties The properties instance to wrap. */ - public PropertiesBasedValueSource( Properties properties ) - { - super( false ); + public PropertiesBasedValueSource(Properties properties) { + super(false); this.properties = properties; } @@ -49,9 +46,7 @@ public PropertiesBasedValueSource( Properties properties ) * entire expression as the key to lookup. If the wrapped properties instance * is null, simply return null. */ - public Object getValue( String expression ) - { - return properties == null ? null : properties.getProperty( expression ); + public Object getValue(String expression) { + return properties == null ? null : properties.getProperty(expression); } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/QueryEnabledValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/QueryEnabledValueSource.java index 764dcac..c8be1fd 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/QueryEnabledValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/QueryEnabledValueSource.java @@ -21,13 +21,10 @@ * This can be useful if the most recent expression is meant to modify the current * one. */ -public interface QueryEnabledValueSource - extends ValueSource -{ +public interface QueryEnabledValueSource extends ValueSource { /** * @return the most recent expression processed by this value source, or null. */ String getLastExpression(); - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/RecursionInterceptor.java b/src/main/java/org/codehaus/plexus/interpolation/RecursionInterceptor.java index da6c86f..1c7a457 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/RecursionInterceptor.java +++ b/src/main/java/org/codehaus/plexus/interpolation/RecursionInterceptor.java @@ -26,8 +26,7 @@ * which is in the process of being resolved. If that happens, the expression * references are cyclical, and would otherwise result in an infinite loop. */ -public interface RecursionInterceptor -{ +public interface RecursionInterceptor { /** * Log the intention to start resolving the given expression. This signals @@ -36,7 +35,7 @@ public interface RecursionInterceptor * * @param expression The expression to be resolved. */ - void expressionResolutionStarted( String expression ); + void expressionResolutionStarted(String expression); /** * Signal to the interceptor that the all efforts to resolve the given @@ -45,7 +44,7 @@ public interface RecursionInterceptor * * @param expression The expression to stop tracking. */ - void expressionResolutionFinished( String expression ); + void expressionResolutionFinished(String expression); /** * Check whether the given value contains an expression that is currently @@ -55,18 +54,17 @@ public interface RecursionInterceptor * @param value The value to check for expression cycles. * @return True if the value contains tracked expressions; false otherwise. */ - boolean hasRecursiveExpression( String value ); + boolean hasRecursiveExpression(String value); /** * @return The list of expressions that participate in the cycle caused by * the given expression. * @param expression the expression to start with. */ - List getExpressionCycle( String expression ); + List getExpressionCycle(String expression); /** * Reset the interceptor */ public void clear(); - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/RegexBasedInterpolator.java b/src/main/java/org/codehaus/plexus/interpolation/RegexBasedInterpolator.java index 076312b..b286bb8 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/RegexBasedInterpolator.java +++ b/src/main/java/org/codehaus/plexus/interpolation/RegexBasedInterpolator.java @@ -33,52 +33,48 @@ * call, to allow the detection of cyclical expression references. * */ -public class RegexBasedInterpolator - implements Interpolator -{ +public class RegexBasedInterpolator implements Interpolator { private String startRegex; private String endRegex; - + private Map existingAnswers = new HashMap(); private List valueSources = new ArrayList(); - + private List postProcessors = new ArrayList(); - + private boolean reusePatterns = false; - + private boolean cacheAnswers = false; - + public static final String DEFAULT_REGEXP = "\\$\\{(.+?)\\}"; - + /** - * the key is the regex the value is the Pattern + * the key is the regex the value is the Pattern * At the class construction time the Map will contains the default Pattern */ - private Map compiledPatterns = new WeakHashMap(); - + private Map compiledPatterns = new WeakHashMap(); + /** * Setup a basic interpolator. *

NOTE: You will have to call

* {@link RegexBasedInterpolator#addValueSource(ValueSource)} at least once * if you use this constructor! */ - public RegexBasedInterpolator() - { - compiledPatterns.put( DEFAULT_REGEXP, Pattern.compile( DEFAULT_REGEXP ) ); + public RegexBasedInterpolator() { + compiledPatterns.put(DEFAULT_REGEXP, Pattern.compile(DEFAULT_REGEXP)); } - - /** + /** + * * @param reusePatterns already compiled patterns will be reused */ - public RegexBasedInterpolator( boolean reusePatterns ) - { + public RegexBasedInterpolator(boolean reusePatterns) { this(); this.reusePatterns = reusePatterns; - } + } /** * Setup an interpolator with no value sources, and the specified regex pattern @@ -90,8 +86,7 @@ public RegexBasedInterpolator( boolean reusePatterns ) * @param startRegex start of the regular expression to use * @param endRegex end of the regular expression to use */ - public RegexBasedInterpolator (String startRegex, String endRegex) - { + public RegexBasedInterpolator(String startRegex, String endRegex) { this(); this.startRegex = startRegex; this.endRegex = endRegex; @@ -102,10 +97,9 @@ public RegexBasedInterpolator (String startRegex, String endRegex) * * @param valueSources The list of value sources to use */ - public RegexBasedInterpolator( List valueSources ) - { + public RegexBasedInterpolator(List valueSources) { this(); - this.valueSources.addAll( valueSources ); + this.valueSources.addAll(valueSources); } /** @@ -116,44 +110,39 @@ public RegexBasedInterpolator( List valueSources ) * @param endRegex end of the regular expression to use * @param valueSources The list of value sources to use */ - public RegexBasedInterpolator (String startRegex, String endRegex, List valueSources ) - { + public RegexBasedInterpolator(String startRegex, String endRegex, List valueSources) { this(); this.startRegex = startRegex; this.endRegex = endRegex; - this.valueSources.addAll( valueSources ); + this.valueSources.addAll(valueSources); } /** * {@inheritDoc} */ - public void addValueSource( ValueSource valueSource ) - { - valueSources.add( valueSource ); + public void addValueSource(ValueSource valueSource) { + valueSources.add(valueSource); } /** * {@inheritDoc} */ - public void removeValuesSource( ValueSource valueSource ) - { - valueSources.remove( valueSource ); + public void removeValuesSource(ValueSource valueSource) { + valueSources.remove(valueSource); } /** * {@inheritDoc} */ - public void addPostProcessor( InterpolationPostProcessor postProcessor ) - { - postProcessors.add( postProcessor ); + public void addPostProcessor(InterpolationPostProcessor postProcessor) { + postProcessors.add(postProcessor); } /** * {@inheritDoc} */ - public void removePostProcessor( InterpolationPostProcessor postProcessor ) - { - postProcessors.remove( postProcessor ); + public void removePostProcessor(InterpolationPostProcessor postProcessor) { + postProcessors.remove(postProcessor); } /** @@ -172,85 +161,63 @@ public void removePostProcessor( InterpolationPostProcessor postProcessor ) * from expression cycles, and throw an * exception if one is detected. */ - public String interpolate( String input, - String thisPrefixPattern, - RecursionInterceptor recursionInterceptor ) - throws InterpolationException - { - if (input == null ) - { + public String interpolate(String input, String thisPrefixPattern, RecursionInterceptor recursionInterceptor) + throws InterpolationException { + if (input == null) { // return empty String to prevent NPE too return ""; } - if ( recursionInterceptor == null ) - { + if (recursionInterceptor == null) { recursionInterceptor = new SimpleRecursionInterceptor(); } - if ( thisPrefixPattern != null && thisPrefixPattern.length() == 0 ) - { + if (thisPrefixPattern != null && thisPrefixPattern.length() == 0) { thisPrefixPattern = null; } int realExprGroup = 2; Pattern expressionPattern; - if ( startRegex != null || endRegex != null ) - { - if ( thisPrefixPattern == null ) - { - expressionPattern = getPattern( startRegex + endRegex ); + if (startRegex != null || endRegex != null) { + if (thisPrefixPattern == null) { + expressionPattern = getPattern(startRegex + endRegex); realExprGroup = 1; - } - else - { - expressionPattern = getPattern( startRegex + thisPrefixPattern + endRegex ); + } else { + expressionPattern = getPattern(startRegex + thisPrefixPattern + endRegex); } - } - else if ( thisPrefixPattern != null ) - { - expressionPattern = getPattern( "\\$\\{(" + thisPrefixPattern + ")?(.+?)\\}" ); - } - else - { - expressionPattern = getPattern( DEFAULT_REGEXP ); + } else if (thisPrefixPattern != null) { + expressionPattern = getPattern("\\$\\{(" + thisPrefixPattern + ")?(.+?)\\}"); + } else { + expressionPattern = getPattern(DEFAULT_REGEXP); realExprGroup = 1; } - try - { - return interpolate( input, recursionInterceptor, expressionPattern, realExprGroup ); - } - finally - { - if ( !cacheAnswers ) - { + try { + return interpolate(input, recursionInterceptor, expressionPattern, realExprGroup); + } finally { + if (!cacheAnswers) { clearAnswers(); } } } - - private Pattern getPattern( String regExp ) - { - if ( !reusePatterns ) - { - return Pattern.compile( regExp ); + + private Pattern getPattern(String regExp) { + if (!reusePatterns) { + return Pattern.compile(regExp); } - + Pattern pattern; - synchronized( this ) - { - pattern = compiledPatterns.get( regExp ); - - if ( pattern != null ) - { + synchronized (this) { + pattern = compiledPatterns.get(regExp); + + if (pattern != null) { return pattern; } - pattern = Pattern.compile( regExp ); - compiledPatterns.put( regExp, pattern ); + pattern = Pattern.compile(regExp); + compiledPatterns.put(regExp, pattern); } - + return pattern; } @@ -260,59 +227,45 @@ private Pattern getPattern( String regExp ) * * @todo Ensure unresolvable expressions don't trigger infinite recursion. */ - private String interpolate( String input, - RecursionInterceptor recursionInterceptor, - Pattern expressionPattern, - int realExprGroup ) - throws InterpolationException - { - if (input == null ) - { + private String interpolate( + String input, RecursionInterceptor recursionInterceptor, Pattern expressionPattern, int realExprGroup) + throws InterpolationException { + if (input == null) { // return empty String to prevent NPE too return ""; - } + } String result = input; - - Matcher matcher = expressionPattern.matcher( result ); - while ( matcher.find() ) - { - String wholeExpr = matcher.group( 0 ); - String realExpr = matcher.group( realExprGroup ); + Matcher matcher = expressionPattern.matcher(result); - if ( realExpr.startsWith( "." ) ) - { - realExpr = realExpr.substring( 1 ); + while (matcher.find()) { + String wholeExpr = matcher.group(0); + String realExpr = matcher.group(realExprGroup); + + if (realExpr.startsWith(".")) { + realExpr = realExpr.substring(1); } - if ( recursionInterceptor.hasRecursiveExpression( realExpr ) ) - { - throw new InterpolationCycleException( recursionInterceptor, realExpr, wholeExpr ); + if (recursionInterceptor.hasRecursiveExpression(realExpr)) { + throw new InterpolationCycleException(recursionInterceptor, realExpr, wholeExpr); } - recursionInterceptor.expressionResolutionStarted( realExpr ); - try - { - Object value = existingAnswers.get( realExpr ); - for ( ValueSource vs : valueSources ) - { - if (value != null) break; + recursionInterceptor.expressionResolutionStarted(realExpr); + try { + Object value = existingAnswers.get(realExpr); + for (ValueSource vs : valueSources) { + if (value != null) break; - value = vs.getValue( realExpr ); + value = vs.getValue(realExpr); } - if ( value != null ) - { - value = - interpolate( String.valueOf( value ), recursionInterceptor, expressionPattern, realExprGroup ); - - if ( postProcessors != null && !postProcessors.isEmpty() ) - { - for ( InterpolationPostProcessor postProcessor : postProcessors ) - { - Object newVal = postProcessor.execute( realExpr, value ); - if ( newVal != null ) - { + if (value != null) { + value = interpolate(String.valueOf(value), recursionInterceptor, expressionPattern, realExprGroup); + + if (postProcessors != null && !postProcessors.isEmpty()) { + for (InterpolationPostProcessor postProcessor : postProcessors) { + Object newVal = postProcessor.execute(realExpr, value); + if (newVal != null) { value = newVal; break; } @@ -322,17 +275,15 @@ private String interpolate( String input, // could use: // result = matcher.replaceFirst( stringValue ); // but this could result in multiple lookups of stringValue, and replaceAll is not correct behaviour - result = StringUtils.replace( result, wholeExpr, String.valueOf( value ) ); + result = StringUtils.replace(result, wholeExpr, String.valueOf(value)); - matcher.reset( result ); + matcher.reset(result); } - } - finally - { - recursionInterceptor.expressionResolutionFinished( realExpr ); + } finally { + recursionInterceptor.expressionResolutionFinished(realExpr); } } - + return result; } @@ -345,16 +296,13 @@ private String interpolate( String input, * @return a {@link List} that may be interspersed with {@link String} and * {@link Throwable} instances. */ - public List getFeedback() - { + public List getFeedback() { List messages = new ArrayList(); - for ( Object valueSource : valueSources ) - { + for (Object valueSource : valueSources) { ValueSource vs = (ValueSource) valueSource; List feedback = vs.getFeedback(); - if ( feedback != null && !feedback.isEmpty() ) - { - messages.addAll( feedback ); + if (feedback != null && !feedback.isEmpty()) { + messages.addAll(feedback); } } @@ -364,10 +312,8 @@ public List getFeedback() /** * Clear the feedback messages from previous interpolate(..) calls. */ - public void clearFeedback() - { - for ( Object valueSource : valueSources ) - { + public void clearFeedback() { + for (Object valueSource : valueSources) { ValueSource vs = (ValueSource) valueSource; vs.clearFeedback(); } @@ -384,11 +330,8 @@ public void clearFeedback() * @param thisPrefixPattern An optional pattern that should be trimmed from * the start of any expressions found in the input. */ - public String interpolate( String input, - String thisPrefixPattern ) - throws InterpolationException - { - return interpolate( input, thisPrefixPattern, null ); + public String interpolate(String input, String thisPrefixPattern) throws InterpolationException { + return interpolate(input, thisPrefixPattern, null); } /** @@ -401,10 +344,8 @@ public String interpolate( String input, * * @param input The input string to interpolate */ - public String interpolate( String input ) - throws InterpolationException - { - return interpolate( input, null, null ); + public String interpolate(String input) throws InterpolationException { + return interpolate(input, null, null); } /** @@ -420,36 +361,27 @@ public String interpolate( String input ) * from expression cycles, and throw an * exception if one is detected. */ - public String interpolate( String input, - RecursionInterceptor recursionInterceptor ) - throws InterpolationException - { - return interpolate( input, null, recursionInterceptor ); + public String interpolate(String input, RecursionInterceptor recursionInterceptor) throws InterpolationException { + return interpolate(input, null, recursionInterceptor); } - public boolean isReusePatterns() - { + public boolean isReusePatterns() { return reusePatterns; } - public void setReusePatterns( boolean reusePatterns ) - { + public void setReusePatterns(boolean reusePatterns) { this.reusePatterns = reusePatterns; } - public boolean isCacheAnswers() - { + public boolean isCacheAnswers() { return cacheAnswers; } - public void setCacheAnswers( boolean cacheAnswers ) - { + public void setCacheAnswers(boolean cacheAnswers) { this.cacheAnswers = cacheAnswers; } - - public void clearAnswers() - { + + public void clearAnswers() { existingAnswers.clear(); } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/SimpleRecursionInterceptor.java b/src/main/java/org/codehaus/plexus/interpolation/SimpleRecursionInterceptor.java index 7bc076a..fc41e6a 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/SimpleRecursionInterceptor.java +++ b/src/main/java/org/codehaus/plexus/interpolation/SimpleRecursionInterceptor.java @@ -29,35 +29,30 @@ * * @author jdcasey */ -public class SimpleRecursionInterceptor - implements RecursionInterceptor -{ +public class SimpleRecursionInterceptor implements RecursionInterceptor { private Stack expressions = new Stack(); /** * {@inheritDoc} */ - public void expressionResolutionFinished( String expression ) - { + public void expressionResolutionFinished(String expression) { expressions.pop(); } /** * {@inheritDoc} */ - public void expressionResolutionStarted( String expression ) - { - expressions.push( expression ); + public void expressionResolutionStarted(String expression) { + expressions.push(expression); } /** * Check whether the current expression is already present in the in-process * stack. */ - public boolean hasRecursiveExpression( String expression ) - { - return expressions.contains( expression ); + public boolean hasRecursiveExpression(String expression) { + return expressions.contains(expression); } /** @@ -66,20 +61,16 @@ public boolean hasRecursiveExpression( String expression ) * Otherwise, if the expression isn't present in the in-process stack, return * {@link Collections#EMPTY_LIST}. */ - public List getExpressionCycle( String expression ) - { - int idx = expressions.indexOf( expression ); - if ( idx < 0 ) - { + public List getExpressionCycle(String expression) { + int idx = expressions.indexOf(expression); + if (idx < 0) { return Collections.EMPTY_LIST; - } - else - { - return expressions.subList( idx, expressions.size() ); + } else { + return expressions.subList(idx, expressions.size()); } } - public void clear(){ + public void clear() { expressions.clear(); } } diff --git a/src/main/java/org/codehaus/plexus/interpolation/SingleResponseValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/SingleResponseValueSource.java index f8a9a9f..90e60dd 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/SingleResponseValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/SingleResponseValueSource.java @@ -23,36 +23,27 @@ * If the expression matches, simply return the response object. * @since 1.12 */ -public class SingleResponseValueSource - implements ValueSource -{ - +public class SingleResponseValueSource implements ValueSource { + private final String expression; private final Object response; - public SingleResponseValueSource( String expression, Object response ) - { + public SingleResponseValueSource(String expression, Object response) { this.expression = expression; this.response = response; } - public void clearFeedback() - { - } + public void clearFeedback() {} - public List getFeedback() - { + public List getFeedback() { return Collections.EMPTY_LIST; } - public Object getValue( String expression ) - { - if ( this.expression.equals( expression ) ) - { + public Object getValue(String expression) { + if (this.expression.equals(expression)) { return response; } - + return null; } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/StringSearchInterpolator.java b/src/main/java/org/codehaus/plexus/interpolation/StringSearchInterpolator.java index 8565452..ffdd6bc 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/StringSearchInterpolator.java +++ b/src/main/java/org/codehaus/plexus/interpolation/StringSearchInterpolator.java @@ -23,11 +23,9 @@ import java.util.Map; import java.util.Set; -public class StringSearchInterpolator - implements Interpolator -{ +public class StringSearchInterpolator implements Interpolator { - private Map existingAnswers = new HashMap(); + private Map existingAnswers = new HashMap(); private List valueSources = new ArrayList(); @@ -45,67 +43,55 @@ public class StringSearchInterpolator private String escapeString; - public StringSearchInterpolator() - { + public StringSearchInterpolator() { this.startExpr = DEFAULT_START_EXPR; this.endExpr = DEFAULT_END_EXPR; } - public StringSearchInterpolator( String startExpr, String endExpr ) - { + public StringSearchInterpolator(String startExpr, String endExpr) { this.startExpr = startExpr; this.endExpr = endExpr; } - /** * {@inheritDoc} */ - public void addValueSource( ValueSource valueSource ) - { - valueSources.add( valueSource ); + public void addValueSource(ValueSource valueSource) { + valueSources.add(valueSource); } /** * {@inheritDoc} */ - public void removeValuesSource( ValueSource valueSource ) - { - valueSources.remove( valueSource ); + public void removeValuesSource(ValueSource valueSource) { + valueSources.remove(valueSource); } /** * {@inheritDoc} */ - public void addPostProcessor( InterpolationPostProcessor postProcessor ) - { - postProcessors.add( postProcessor ); + public void addPostProcessor(InterpolationPostProcessor postProcessor) { + postProcessors.add(postProcessor); } /** * {@inheritDoc} */ - public void removePostProcessor( InterpolationPostProcessor postProcessor ) - { - postProcessors.remove( postProcessor ); + public void removePostProcessor(InterpolationPostProcessor postProcessor) { + postProcessors.remove(postProcessor); } - public String interpolate( String input, String thisPrefixPattern ) - throws InterpolationException - { - return interpolate( input, new SimpleRecursionInterceptor() ); + public String interpolate(String input, String thisPrefixPattern) throws InterpolationException { + return interpolate(input, new SimpleRecursionInterceptor()); } - public String interpolate( String input, String thisPrefixPattern, RecursionInterceptor recursionInterceptor ) - throws InterpolationException - { - return interpolate( input, recursionInterceptor ); + public String interpolate(String input, String thisPrefixPattern, RecursionInterceptor recursionInterceptor) + throws InterpolationException { + return interpolate(input, recursionInterceptor); } - public String interpolate( String input ) - throws InterpolationException - { - return interpolate( input, new SimpleRecursionInterceptor() ); + public String interpolate(String input) throws InterpolationException { + return interpolate(input, new SimpleRecursionInterceptor()); } /** @@ -114,57 +100,43 @@ public String interpolate( String input ) * * TODO: Ensure unresolvable expressions don't trigger infinite recursion. */ - public String interpolate( String input, RecursionInterceptor recursionInterceptor ) - throws InterpolationException - { - try - { - return interpolate( input, recursionInterceptor, new HashSet() ); - } - finally - { - if ( !cacheAnswers ) - { + public String interpolate(String input, RecursionInterceptor recursionInterceptor) throws InterpolationException { + try { + return interpolate(input, recursionInterceptor, new HashSet()); + } finally { + if (!cacheAnswers) { existingAnswers.clear(); } } } - private String interpolate( String input, RecursionInterceptor recursionInterceptor, Set unresolvable ) - throws InterpolationException - { - if ( input == null ) - { + private String interpolate(String input, RecursionInterceptor recursionInterceptor, Set unresolvable) + throws InterpolationException { + if (input == null) { // return empty String to prevent NPE too return ""; } int startIdx; int endIdx = -1; - if ( ( startIdx = input.indexOf( startExpr, endIdx + 1 ) ) > -1 ) - { - StringBuilder result = new StringBuilder( input.length() * 2 ); - do - { - result.append( input, endIdx + 1, startIdx ); - - endIdx = input.indexOf( endExpr, startIdx + 1 ); - if ( endIdx < 0 ) - { + if ((startIdx = input.indexOf(startExpr, endIdx + 1)) > -1) { + StringBuilder result = new StringBuilder(input.length() * 2); + do { + result.append(input, endIdx + 1, startIdx); + + endIdx = input.indexOf(endExpr, startIdx + 1); + if (endIdx < 0) { break; } - final String wholeExpr = input.substring( startIdx, endIdx + endExpr.length() ); - String realExpr = wholeExpr.substring( startExpr.length(), wholeExpr.length() - endExpr.length() ); + final String wholeExpr = input.substring(startIdx, endIdx + endExpr.length()); + String realExpr = wholeExpr.substring(startExpr.length(), wholeExpr.length() - endExpr.length()); - if ( startIdx >= 0 && escapeString != null && escapeString.length() > 0 ) - { + if (startIdx >= 0 && escapeString != null && escapeString.length() > 0) { int startEscapeIdx = startIdx == 0 ? 0 : startIdx - escapeString.length(); - if ( startEscapeIdx >= 0 ) - { - String escape = input.substring( startEscapeIdx, startIdx ); - if ( escapeString.equals( escape ) ) - { + if (startEscapeIdx >= 0) { + String escape = input.substring(startEscapeIdx, startIdx); + if (escapeString.equals(escape)) { result.append(wholeExpr); result.replace(startEscapeIdx, startEscapeIdx + escapeString.length(), ""); continue; @@ -173,34 +145,27 @@ private String interpolate( String input, RecursionInterceptor recursionIntercep } boolean resolved = false; - if ( !unresolvable.contains( wholeExpr ) ) - { - if ( realExpr.startsWith( "." ) ) - { + if (!unresolvable.contains(wholeExpr)) { + if (realExpr.startsWith(".")) { realExpr = realExpr.substring(1); } - if ( recursionInterceptor.hasRecursiveExpression( realExpr ) ) - { - throw new InterpolationCycleException( recursionInterceptor, realExpr, wholeExpr ); + if (recursionInterceptor.hasRecursiveExpression(realExpr)) { + throw new InterpolationCycleException(recursionInterceptor, realExpr, wholeExpr); } - recursionInterceptor.expressionResolutionStarted( realExpr ); - try - { - Object value = existingAnswers.get( realExpr ); + recursionInterceptor.expressionResolutionStarted(realExpr); + try { + Object value = existingAnswers.get(realExpr); Object bestAnswer = null; - for ( ValueSource valueSource : valueSources ) - { - if ( value != null ) - { + for (ValueSource valueSource : valueSources) { + if (value != null) { break; } - value = valueSource.getValue( realExpr ); + value = valueSource.getValue(realExpr); - if ( value != null && value.toString().contains( wholeExpr ) ) - { + if (value != null && value.toString().contains(wholeExpr)) { bestAnswer = value; value = null; } @@ -209,22 +174,17 @@ private String interpolate( String input, RecursionInterceptor recursionIntercep // this is the simplest recursion check to catch exact recursion // (non synonym), and avoid the extra effort of more string // searching. - if ( value == null && bestAnswer != null ) - { - throw new InterpolationCycleException( recursionInterceptor, realExpr, wholeExpr ); + if (value == null && bestAnswer != null) { + throw new InterpolationCycleException(recursionInterceptor, realExpr, wholeExpr); } - if ( value != null ) - { - value = interpolate( String.valueOf(value), recursionInterceptor, unresolvable ); - - if ( postProcessors != null && !postProcessors.isEmpty() ) - { - for ( InterpolationPostProcessor postProcessor : postProcessors ) - { - Object newVal = postProcessor.execute( realExpr, value ); - if ( newVal != null ) - { + if (value != null) { + value = interpolate(String.valueOf(value), recursionInterceptor, unresolvable); + + if (postProcessors != null && !postProcessors.isEmpty()) { + for (InterpolationPostProcessor postProcessor : postProcessors) { + Object newVal = postProcessor.execute(realExpr, value); + if (newVal != null) { value = newVal; break; } @@ -235,45 +195,33 @@ private String interpolate( String input, RecursionInterceptor recursionIntercep // result = matcher.replaceFirst( stringValue ); // but this could result in multiple lookups of stringValue, and replaceAll is not correct // behaviour - result.append( String.valueOf( value ) ); + result.append(String.valueOf(value)); resolved = true; + } else { + unresolvable.add(wholeExpr); } - else - { - unresolvable.add( wholeExpr ); - } - } - finally - { - recursionInterceptor.expressionResolutionFinished( realExpr ); + } finally { + recursionInterceptor.expressionResolutionFinished(realExpr); } } - if (!resolved) - { - result.append( wholeExpr ); + if (!resolved) { + result.append(wholeExpr); } - if ( endIdx > -1 ) - { + if (endIdx > -1) { endIdx += endExpr.length() - 1; } - } - while ( ( startIdx = input.indexOf( startExpr, endIdx + 1 ) ) > -1); + } while ((startIdx = input.indexOf(startExpr, endIdx + 1)) > -1); - if ( endIdx == -1 && startIdx > -1 ) - { - result.append( input, startIdx, input.length()); - } - else if ( endIdx < input.length() ) - { - result.append( input, endIdx + 1, input.length() ); + if (endIdx == -1 && startIdx > -1) { + result.append(input, startIdx, input.length()); + } else if (endIdx < input.length()) { + result.append(input, endIdx + 1, input.length()); } return result.toString(); - } - else - { + } else { return input; } } @@ -287,15 +235,12 @@ else if ( endIdx < input.length() ) * @return a {@link List} that may be interspersed with {@link String} and * {@link Throwable} instances. */ - public List getFeedback() - { + public List getFeedback() { List messages = new ArrayList(); - for ( ValueSource vs : valueSources ) - { + for (ValueSource vs : valueSources) { List feedback = vs.getFeedback(); - if ( feedback != null && !feedback.isEmpty() ) - { - messages.addAll( feedback ); + if (feedback != null && !feedback.isEmpty()) { + messages.addAll(feedback); } } @@ -305,37 +250,29 @@ public List getFeedback() /** * Clear the feedback messages from previous interpolate(..) calls. */ - public void clearFeedback() - { - for ( ValueSource vs : valueSources ) - { + public void clearFeedback() { + for (ValueSource vs : valueSources) { vs.clearFeedback(); } } - public boolean isCacheAnswers() - { + public boolean isCacheAnswers() { return cacheAnswers; } - public void setCacheAnswers( boolean cacheAnswers ) - { + public void setCacheAnswers(boolean cacheAnswers) { this.cacheAnswers = cacheAnswers; } - public void clearAnswers() - { + public void clearAnswers() { existingAnswers.clear(); } - public String getEscapeString() - { + public String getEscapeString() { return escapeString; } - public void setEscapeString( String escapeString ) - { + public void setEscapeString(String escapeString) { this.escapeString = escapeString; } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/ValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/ValueSource.java index b4fef3c..347b738 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/ValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/ValueSource.java @@ -22,14 +22,13 @@ * Supplies one strategy for resolving a value for an interpolation expression. * ValueSources may be stacked. */ -public interface ValueSource -{ +public interface ValueSource { /** * @param expression The string expression. * @return the value related to the expression, or null if not found. */ - public Object getValue( String expression ); + public Object getValue(String expression); /** * Return the feedback about resolution failures for a particular expression. diff --git a/src/main/java/org/codehaus/plexus/interpolation/fixed/AbstractDelegatingValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/fixed/AbstractDelegatingValueSource.java index eff85a6..9c0ae75 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/fixed/AbstractDelegatingValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/fixed/AbstractDelegatingValueSource.java @@ -16,28 +16,23 @@ * limitations under the License. */ -public abstract class AbstractDelegatingValueSource - implements FixedValueSource -{ - +public abstract class AbstractDelegatingValueSource implements FixedValueSource { + private final FixedValueSource delegate; - protected AbstractDelegatingValueSource( FixedValueSource delegate ) - { - if ( delegate == null ) - { - throw new NullPointerException( "Delegate ValueSource cannot be null." ); + protected AbstractDelegatingValueSource(FixedValueSource delegate) { + if (delegate == null) { + throw new NullPointerException("Delegate ValueSource cannot be null."); } - + this.delegate = delegate; } - - protected FixedValueSource getDelegate() - { + + protected FixedValueSource getDelegate() { return delegate; } - public Object getValue( String expression, InterpolationState interpolationState ){ - return getDelegate().getValue( expression, interpolationState ); + public Object getValue(String expression, InterpolationState interpolationState) { + return getDelegate().getValue(expression, interpolationState); } } diff --git a/src/main/java/org/codehaus/plexus/interpolation/fixed/EnvarBasedValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/fixed/EnvarBasedValueSource.java index 08efc28..a0759eb 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/fixed/EnvarBasedValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/fixed/EnvarBasedValueSource.java @@ -16,11 +16,11 @@ * limitations under the License. */ -import org.codehaus.plexus.interpolation.os.OperatingSystemUtils; - import java.io.IOException; import java.util.Properties; +import org.codehaus.plexus.interpolation.os.OperatingSystemUtils; + /** * {@link org.codehaus.plexus.interpolation.ValueSource} which resolves expressions against the environment variables * available from the underlying operating system (and possibly, the shell environment @@ -28,9 +28,7 @@ * this prefix is trimmed before resolving the rest as an environment variable name. * */ -public class EnvarBasedValueSource - implements FixedValueSource -{ +public class EnvarBasedValueSource implements FixedValueSource { private static Properties envarsCaseSensitive; private static Properties envarsCaseInsensitive; @@ -44,9 +42,8 @@ public class EnvarBasedValueSource * * @throws java.io.IOException in case of an error. */ - public EnvarBasedValueSource() throws IOException - { - this( true ); + public EnvarBasedValueSource() throws IOException { + this(true); } /** @@ -56,28 +53,20 @@ public EnvarBasedValueSource() throws IOException * case-sensitive manner for lookups * @throws java.io.IOException in case of an error. */ - public EnvarBasedValueSource( boolean caseSensitive ) throws IOException - { + public EnvarBasedValueSource(boolean caseSensitive) throws IOException { this.caseSensitive = caseSensitive; - this.envars = getEnvars( caseSensitive ); + this.envars = getEnvars(caseSensitive); } - private static synchronized Properties getEnvars( boolean caseSensitive ) - throws IOException - { - if ( caseSensitive ) - { - if ( envarsCaseSensitive == null ) - { - envarsCaseSensitive = OperatingSystemUtils.getSystemEnvVars( caseSensitive ); + private static synchronized Properties getEnvars(boolean caseSensitive) throws IOException { + if (caseSensitive) { + if (envarsCaseSensitive == null) { + envarsCaseSensitive = OperatingSystemUtils.getSystemEnvVars(caseSensitive); } return envarsCaseSensitive; - } - else - { - if ( envarsCaseInsensitive == null ) - { - envarsCaseInsensitive = OperatingSystemUtils.getSystemEnvVars( caseSensitive ); + } else { + if (envarsCaseInsensitive == null) { + envarsCaseInsensitive = OperatingSystemUtils.getSystemEnvVars(caseSensitive); } return envarsCaseInsensitive; } @@ -92,30 +81,25 @@ private static synchronized Properties getEnvars( boolean caseSensitive ) * @param expression envar expression, like 'HOME' or 'env.HOME' * @return the environment variable value for the given expression */ - public Object getValue( String expression, InterpolationState interpolationState ) - { + public Object getValue(String expression, InterpolationState interpolationState) { String expr = expression; - if ( expr.startsWith( "env." ) ) - { - expr = expr.substring( "env.".length() ); + if (expr.startsWith("env.")) { + expr = expr.substring("env.".length()); } - if ( !caseSensitive ) - { + if (!caseSensitive) { expr = expr.toUpperCase(); } - return envars.getProperty( expr ); + return envars.getProperty(expr); } /** * reset static variables acting as a cache for testing purposes only */ - static void resetStatics() - { + static void resetStatics() { envarsCaseSensitive = null; envarsCaseInsensitive = null; } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/fixed/FixedStringSearchInterpolator.java b/src/main/java/org/codehaus/plexus/interpolation/fixed/FixedStringSearchInterpolator.java index 33990dd..cbffe0c 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/fixed/FixedStringSearchInterpolator.java +++ b/src/main/java/org/codehaus/plexus/interpolation/fixed/FixedStringSearchInterpolator.java @@ -16,15 +16,14 @@ * limitations under the License. */ +import java.util.ArrayList; +import java.util.List; import org.codehaus.plexus.interpolation.BasicInterpolator; import org.codehaus.plexus.interpolation.InterpolationException; import org.codehaus.plexus.interpolation.InterpolationPostProcessor; import org.codehaus.plexus.interpolation.RecursionInterceptor; -import java.util.ArrayList; -import java.util.List; - /** *

* A fixed string search interpolator is permanently bound to a given set of value sources, @@ -41,9 +40,7 @@ * underlying objects.

*

The fixed interpolator can be a valuesource

*/ -public class FixedStringSearchInterpolator - implements FixedValueSource -{ +public class FixedStringSearchInterpolator implements FixedValueSource { private final FixedValueSource[] valueSources; @@ -59,21 +56,21 @@ public class FixedStringSearchInterpolator private final String escapeString; - private FixedStringSearchInterpolator( String startExpr, String endExpr, String escapeString, - InterpolationPostProcessor postProcessor, FixedValueSource... valueSources ) - { + private FixedStringSearchInterpolator( + String startExpr, + String endExpr, + String escapeString, + InterpolationPostProcessor postProcessor, + FixedValueSource... valueSources) { this.startExpr = startExpr; this.endExpr = endExpr; this.escapeString = escapeString; - if ( valueSources == null ) - { - throw new IllegalArgumentException( "valueSources cannot be null" ); + if (valueSources == null) { + throw new IllegalArgumentException("valueSources cannot be null"); } - for ( int i = 0; i < valueSources.length; i++ ) - { - if ( valueSources[i] == null ) - { - throw new IllegalArgumentException( "valueSources[" + i + "] is null" ); + for (int i = 0; i < valueSources.length; i++) { + if (valueSources[i] == null) { + throw new IllegalArgumentException("valueSources[" + i + "] is null"); } } @@ -81,217 +78,172 @@ private FixedStringSearchInterpolator( String startExpr, String endExpr, String this.postProcessor = postProcessor; } - public static FixedStringSearchInterpolator create( String startExpr, String endExpr, - FixedValueSource... valueSources ) - { - return new FixedStringSearchInterpolator( startExpr, endExpr, null, null, valueSources ); + public static FixedStringSearchInterpolator create( + String startExpr, String endExpr, FixedValueSource... valueSources) { + return new FixedStringSearchInterpolator(startExpr, endExpr, null, null, valueSources); } - - public static FixedStringSearchInterpolator create( FixedValueSource... valueSources ) - { - return new FixedStringSearchInterpolator( DEFAULT_START_EXPR, DEFAULT_END_EXPR, null, null, valueSources ); + public static FixedStringSearchInterpolator create(FixedValueSource... valueSources) { + return new FixedStringSearchInterpolator(DEFAULT_START_EXPR, DEFAULT_END_EXPR, null, null, valueSources); } - public static FixedStringSearchInterpolator createWithPermittedNulls( FixedValueSource... valueSources ) - { - List nonnulls = new ArrayList( ); - for ( FixedValueSource item : valueSources ) - { - if (item != null) nonnulls.add( item); + public static FixedStringSearchInterpolator createWithPermittedNulls(FixedValueSource... valueSources) { + List nonnulls = new ArrayList(); + for (FixedValueSource item : valueSources) { + if (item != null) nonnulls.add(item); } - return new FixedStringSearchInterpolator( DEFAULT_START_EXPR, DEFAULT_END_EXPR, null, null, nonnulls.toArray(new FixedValueSource[nonnulls.size()]) ); + return new FixedStringSearchInterpolator( + DEFAULT_START_EXPR, + DEFAULT_END_EXPR, + null, + null, + nonnulls.toArray(new FixedValueSource[nonnulls.size()])); } - public FixedStringSearchInterpolator withExpressionMarkers( String startExpr, String endExpr ) - { - return new FixedStringSearchInterpolator( startExpr, endExpr, escapeString, postProcessor, valueSources ); + public FixedStringSearchInterpolator withExpressionMarkers(String startExpr, String endExpr) { + return new FixedStringSearchInterpolator(startExpr, endExpr, escapeString, postProcessor, valueSources); } - public FixedStringSearchInterpolator withPostProcessor( InterpolationPostProcessor postProcessor ) - { - return new FixedStringSearchInterpolator( startExpr, endExpr, escapeString, postProcessor, valueSources ); + public FixedStringSearchInterpolator withPostProcessor(InterpolationPostProcessor postProcessor) { + return new FixedStringSearchInterpolator(startExpr, endExpr, escapeString, postProcessor, valueSources); } - - public FixedStringSearchInterpolator withEscapeString( String escapeString ) - { - return new FixedStringSearchInterpolator( startExpr, endExpr, escapeString, postProcessor, valueSources ); + public FixedStringSearchInterpolator withEscapeString(String escapeString) { + return new FixedStringSearchInterpolator(startExpr, endExpr, escapeString, postProcessor, valueSources); } - public String interpolate( String input ) - throws InterpolationCycleException - { - return interpolate( input, new InterpolationState() ); + public String interpolate(String input) throws InterpolationCycleException { + return interpolate(input, new InterpolationState()); } - public static FixedStringSearchInterpolator empty(){ - return create( ); + public static FixedStringSearchInterpolator empty() { + return create(); } // Find out how to return null when we cannot interpolate this expression // At this point we should always be a ${expr} - public Object getValue( String realExpr, InterpolationState interpolationState ) - { + public Object getValue(String realExpr, InterpolationState interpolationState) { - interpolationState.recursionInterceptor.expressionResolutionStarted( realExpr ); + interpolationState.recursionInterceptor.expressionResolutionStarted(realExpr); - try - { + try { Object value = null; - for ( FixedValueSource valueSource : valueSources ) - { - value = valueSource.getValue( realExpr, interpolationState ); - if ( value != null ) - { + for (FixedValueSource valueSource : valueSources) { + value = valueSource.getValue(realExpr, interpolationState); + if (value != null) { break; } } - if ( value != null ) - { - if ( interpolationState.root != null ) - { - value = interpolationState.root.interpolate( String.valueOf( value ), interpolationState ); + if (value != null) { + if (interpolationState.root != null) { + value = interpolationState.root.interpolate(String.valueOf(value), interpolationState); } - return String.valueOf( value ); - } - else - { + return String.valueOf(value); + } else { return null; } - } - finally - { - interpolationState.recursionInterceptor.expressionResolutionFinished( realExpr ); + } finally { + interpolationState.recursionInterceptor.expressionResolutionFinished(realExpr); } } - public BasicInterpolator asBasicInterpolator() - { + public BasicInterpolator asBasicInterpolator() { final InterpolationState is = new InterpolationState(); - return new BasicInterpolator() - { + return new BasicInterpolator() { - public String interpolate( String input ) - throws InterpolationException - { - return FixedStringSearchInterpolator.this.interpolate( input, is ); + public String interpolate(String input) throws InterpolationException { + return FixedStringSearchInterpolator.this.interpolate(input, is); } - public String interpolate( String input, RecursionInterceptor recursionInterceptor ) - throws InterpolationException - { - is.setRecursionInterceptor( recursionInterceptor ); - return FixedStringSearchInterpolator.this.interpolate( input, is ); + public String interpolate(String input, RecursionInterceptor recursionInterceptor) + throws InterpolationException { + is.setRecursionInterceptor(recursionInterceptor); + return FixedStringSearchInterpolator.this.interpolate(input, is); } }; } - public String interpolate( String input, InterpolationState interpolationState ) - throws InterpolationCycleException - { - if ( interpolationState.root == null ) - { + public String interpolate(String input, InterpolationState interpolationState) throws InterpolationCycleException { + if (interpolationState.root == null) { interpolationState.root = this; } - if ( input == null ) - { + if (input == null) { // return empty String to prevent NPE too return ""; } - StringBuilder result = new StringBuilder( input.length() * 2 ); + StringBuilder result = new StringBuilder(input.length() * 2); int startIdx; int endIdx = -1; - while ( ( startIdx = input.indexOf( startExpr, endIdx + 1 ) ) > -1 ) - { - result.append( input, endIdx + 1, startIdx ); + while ((startIdx = input.indexOf(startExpr, endIdx + 1)) > -1) { + result.append(input, endIdx + 1, startIdx); - endIdx = input.indexOf( endExpr, startIdx + 1 ); - if ( endIdx < 0 ) - { + endIdx = input.indexOf(endExpr, startIdx + 1); + if (endIdx < 0) { break; } - final String wholeExpr = input.substring( startIdx, endIdx + endExpr.length() ); - String realExpr = wholeExpr.substring( startExpr.length(), wholeExpr.length() - endExpr.length() ); + final String wholeExpr = input.substring(startIdx, endIdx + endExpr.length()); + String realExpr = wholeExpr.substring(startExpr.length(), wholeExpr.length() - endExpr.length()); - if ( startIdx >= 0 && escapeString != null && escapeString.length() > 0 ) - { + if (startIdx >= 0 && escapeString != null && escapeString.length() > 0) { int startEscapeIdx = startIdx == 0 ? 0 : startIdx - escapeString.length(); - if ( startEscapeIdx >= 0 ) - { - String escape = input.substring( startEscapeIdx, startIdx ); - if ( escapeString.equals( escape ) ) - { - result.append( wholeExpr ); - result.replace( startEscapeIdx, startEscapeIdx + escapeString.length(), "" ); + if (startEscapeIdx >= 0) { + String escape = input.substring(startEscapeIdx, startIdx); + if (escapeString.equals(escape)) { + result.append(wholeExpr); + result.replace(startEscapeIdx, startEscapeIdx + escapeString.length(), ""); continue; } } } boolean resolved = false; - if ( !interpolationState.unresolvable.contains( wholeExpr ) ) - { - if ( realExpr.startsWith( "." ) ) - { - realExpr = realExpr.substring( 1 ); + if (!interpolationState.unresolvable.contains(wholeExpr)) { + if (realExpr.startsWith(".")) { + realExpr = realExpr.substring(1); } - if ( interpolationState.recursionInterceptor.hasRecursiveExpression( realExpr ) ) - { - throw new InterpolationCycleException( interpolationState.recursionInterceptor, realExpr, - wholeExpr ); + if (interpolationState.recursionInterceptor.hasRecursiveExpression(realExpr)) { + throw new InterpolationCycleException(interpolationState.recursionInterceptor, realExpr, wholeExpr); } - Object value = getValue( realExpr, interpolationState ); - if ( value != null ) - { - value = interpolate( String.valueOf( value ), interpolationState ); + Object value = getValue(realExpr, interpolationState); + if (value != null) { + value = interpolate(String.valueOf(value), interpolationState); - if ( postProcessor != null ) - { - Object newVal = postProcessor.execute( realExpr, value ); - if ( newVal != null ) - { + if (postProcessor != null) { + Object newVal = postProcessor.execute(realExpr, value); + if (newVal != null) { value = newVal; } } - result.append( String.valueOf( value ) ); + result.append(String.valueOf(value)); resolved = true; - } - else - { - interpolationState.unresolvable.add( wholeExpr ); + } else { + interpolationState.unresolvable.add(wholeExpr); } } - if ( !resolved ) - { - result.append( wholeExpr ); + if (!resolved) { + result.append(wholeExpr); } - if ( endIdx > -1 ) - { + if (endIdx > -1) { endIdx += endExpr.length() - 1; } } - if ( endIdx == -1 && startIdx > -1 ) - { - result.append( input, startIdx, input.length() ); - } - else if ( endIdx < input.length() ) - { - result.append( input, endIdx + 1, input.length() ); + if (endIdx == -1 && startIdx > -1) { + result.append(input, startIdx, input.length()); + } else if (endIdx < input.length()) { + result.append(input, endIdx + 1, input.length()); } return result.toString(); } } - diff --git a/src/main/java/org/codehaus/plexus/interpolation/fixed/FixedValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/fixed/FixedValueSource.java index 3224b98..63ed9b9 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/fixed/FixedValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/fixed/FixedValueSource.java @@ -16,14 +16,12 @@ * limitations under the License. */ -public interface FixedValueSource -{ +public interface FixedValueSource { /** * @param expression The expression. * @param interpolationState {@link InterpolationState}. * @return the value related to the expression, or null if not found (not available * from this source) */ - public Object getValue( String expression, InterpolationState interpolationState ); - + public Object getValue(String expression, InterpolationState interpolationState); } diff --git a/src/main/java/org/codehaus/plexus/interpolation/fixed/InterpolationCycleException.java b/src/main/java/org/codehaus/plexus/interpolation/fixed/InterpolationCycleException.java index fe3742a..db68bbb 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/fixed/InterpolationCycleException.java +++ b/src/main/java/org/codehaus/plexus/interpolation/fixed/InterpolationCycleException.java @@ -18,17 +18,12 @@ import org.codehaus.plexus.interpolation.RecursionInterceptor; -public class InterpolationCycleException - extends RuntimeException -{ - +public class InterpolationCycleException extends RuntimeException { + private static final long serialVersionUID = 1L; - public InterpolationCycleException( RecursionInterceptor recursionInterceptor, String realExpr, String wholeExpr ) - { - super( "Detected the following recursive expression cycle in '" + realExpr + "': " - + recursionInterceptor.getExpressionCycle( realExpr ) + wholeExpr ); - + public InterpolationCycleException(RecursionInterceptor recursionInterceptor, String realExpr, String wholeExpr) { + super("Detected the following recursive expression cycle in '" + realExpr + "': " + + recursionInterceptor.getExpressionCycle(realExpr) + wholeExpr); } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/fixed/InterpolationState.java b/src/main/java/org/codehaus/plexus/interpolation/fixed/InterpolationState.java index dc1282e..a2a3ef8 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/fixed/InterpolationState.java +++ b/src/main/java/org/codehaus/plexus/interpolation/fixed/InterpolationState.java @@ -16,42 +16,39 @@ * limitations under the License. */ -import org.codehaus.plexus.interpolation.RecursionInterceptor; -import org.codehaus.plexus.interpolation.SimpleRecursionInterceptor; - import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; +import org.codehaus.plexus.interpolation.RecursionInterceptor; +import org.codehaus.plexus.interpolation.SimpleRecursionInterceptor; + /** * AN error collector contains the errors accumulated during an interpolation. * It is stateful. */ -public class InterpolationState -{ - private final List messages = new ArrayList( ); - private final List causes = new ArrayList( ); +public class InterpolationState { + private final List messages = new ArrayList(); + private final List causes = new ArrayList(); - public void addFeedback( String message, Throwable cause ) - { - messages.add( message); + public void addFeedback(String message, Throwable cause) { + messages.add(message); causes.add(cause); } - public List asList(){ - ArrayList items = new ArrayList( ); - for (int i = 0; i < messages.size(); i++){ + public List asList() { + ArrayList items = new ArrayList(); + for (int i = 0; i < messages.size(); i++) { String msg = messages.get(i); - if (msg != null ) items.add( msg); + if (msg != null) items.add(msg); Throwable cause = causes.get(i); if (cause != null) items.add(cause); } - return items.size() > 0 ? items: null; + return items.size() > 0 ? items : null; } - public void clear() - { + public void clear() { messages.clear(); causes.clear(); unresolvable.clear(); @@ -59,11 +56,10 @@ public void clear() root = null; } - final Set unresolvable = new HashSet( ); + final Set unresolvable = new HashSet(); RecursionInterceptor recursionInterceptor = new SimpleRecursionInterceptor(); - public void setRecursionInterceptor( RecursionInterceptor recursionInterceptor ) - { + public void setRecursionInterceptor(RecursionInterceptor recursionInterceptor) { this.recursionInterceptor = recursionInterceptor; } diff --git a/src/main/java/org/codehaus/plexus/interpolation/fixed/MapBasedValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/fixed/MapBasedValueSource.java index 4065dca..b51a827 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/fixed/MapBasedValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/fixed/MapBasedValueSource.java @@ -22,9 +22,7 @@ * Wraps a Map, and looks up the whole expression as a single key, returning the * value mapped to it. */ -public class MapBasedValueSource - implements FixedValueSource -{ +public class MapBasedValueSource implements FixedValueSource { private final Map values; @@ -32,8 +30,7 @@ public class MapBasedValueSource * Construct a new value source to wrap the supplied map. * @param values the key/value pairs. */ - public MapBasedValueSource( Map values ) - { + public MapBasedValueSource(Map values) { this.values = values; } @@ -41,9 +38,7 @@ public MapBasedValueSource( Map values ) * Lookup the supplied expression as a key in the wrapped Map, and return * its value. */ - public Object getValue( String expression, InterpolationState interpolationState ) - { - return values == null ? null : values.get( expression ); + public Object getValue(String expression, InterpolationState interpolationState) { + return values == null ? null : values.get(expression); } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/fixed/ObjectBasedValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/fixed/ObjectBasedValueSource.java index a86ac78..d4ab063 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/fixed/ObjectBasedValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/fixed/ObjectBasedValueSource.java @@ -16,7 +16,6 @@ * limitations under the License. */ - import org.codehaus.plexus.interpolation.reflection.ReflectionValueExtractor; /** @@ -25,9 +24,7 @@ * 'rootObject.getChild().getName()' for non-boolean properties, and * 'rootObject.getChild().isName()' for boolean properties. */ -public class ObjectBasedValueSource - implements FixedValueSource -{ +public class ObjectBasedValueSource implements FixedValueSource { private final Object root; @@ -37,8 +34,7 @@ public class ObjectBasedValueSource * the object graph beneath this root. * @param root The root of the graph. */ - public ObjectBasedValueSource( Object root ) - { + public ObjectBasedValueSource(Object root) { this.root = root; } @@ -51,23 +47,17 @@ public ObjectBasedValueSource( Object root ) *

NOTE: The object-graph nagivation actually takes place via the * {@link org.codehaus.plexus.interpolation.reflection.ReflectionValueExtractor} class.

*/ - public Object getValue( String expression, InterpolationState interpolationState ) - { - if ( expression == null || expression.trim().length() < 1 ) - { + public Object getValue(String expression, InterpolationState interpolationState) { + if (expression == null || expression.trim().length() < 1) { return null; } - - try - { - return ReflectionValueExtractor.evaluate( expression, root, false ); - } - catch ( Exception e ) - { - interpolationState.addFeedback( "Failed to extract \'" + expression + "\' from: " + root, e ); + + try { + return ReflectionValueExtractor.evaluate(expression, root, false); + } catch (Exception e) { + interpolationState.addFeedback("Failed to extract \'" + expression + "\' from: " + root, e); } return null; } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/fixed/PrefixedObjectValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/fixed/PrefixedObjectValueSource.java index 576c792..70548f5 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/fixed/PrefixedObjectValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/fixed/PrefixedObjectValueSource.java @@ -16,8 +16,6 @@ * limitations under the License. */ - - import java.util.List; /** @@ -25,18 +23,15 @@ * wraps that source with a {@link org.codehaus.plexus.interpolation.fixed.PrefixedValueSourceWrapper} instance, to which * this class delegates all of its calls. */ -public class PrefixedObjectValueSource - extends AbstractDelegatingValueSource -{ +public class PrefixedObjectValueSource extends AbstractDelegatingValueSource { /** * Wrap the specified root object, allowing the specified expression prefix. * @param prefix the prefix. * @param root The root of the graph. */ - public PrefixedObjectValueSource( String prefix, Object root ) - { - super( new PrefixedValueSourceWrapper( new ObjectBasedValueSource( root ), prefix ) ); + public PrefixedObjectValueSource(String prefix, Object root) { + super(new PrefixedValueSourceWrapper(new ObjectBasedValueSource(root), prefix)); } /** @@ -47,9 +42,8 @@ public PrefixedObjectValueSource( String prefix, Object root ) * @param root The root of the graph. * @param allowUnprefixedExpressions allow unrefixed expressions or not. */ - public PrefixedObjectValueSource( List possiblePrefixes, Object root, boolean allowUnprefixedExpressions ) - { - super( new PrefixedValueSourceWrapper( new ObjectBasedValueSource( root ), possiblePrefixes, - allowUnprefixedExpressions ) ); + public PrefixedObjectValueSource(List possiblePrefixes, Object root, boolean allowUnprefixedExpressions) { + super(new PrefixedValueSourceWrapper( + new ObjectBasedValueSource(root), possiblePrefixes, allowUnprefixedExpressions)); } } diff --git a/src/main/java/org/codehaus/plexus/interpolation/fixed/PrefixedPropertiesValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/fixed/PrefixedPropertiesValueSource.java index b56ba04..40c891d 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/fixed/PrefixedPropertiesValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/fixed/PrefixedPropertiesValueSource.java @@ -29,9 +29,7 @@ * the properties value source and then wrapping it with a prefixed value-source wrapper.

* */ -public class PrefixedPropertiesValueSource - extends AbstractDelegatingValueSource -{ +public class PrefixedPropertiesValueSource extends AbstractDelegatingValueSource { /** * Wrap the specified properties file with a new {@link org.codehaus.plexus.interpolation.PropertiesBasedValueSource}, then @@ -42,9 +40,8 @@ public class PrefixedPropertiesValueSource * @param prefix The expression prefix to trim * @param properties The properties instance to wrap */ - public PrefixedPropertiesValueSource( String prefix, Properties properties ) - { - super( new PrefixedValueSourceWrapper( new PropertiesBasedValueSource( properties ), prefix ) ); + public PrefixedPropertiesValueSource(String prefix, Properties properties) { + super(new PrefixedValueSourceWrapper(new PropertiesBasedValueSource(properties), prefix)); } /** @@ -57,10 +54,9 @@ public PrefixedPropertiesValueSource( String prefix, Properties properties ) * @param properties The properties instance to wrap * @param allowUnprefixedExpressions allow unprefixed expressions or not. */ - public PrefixedPropertiesValueSource( List possiblePrefixes, Properties properties, - boolean allowUnprefixedExpressions ) - { - super( new PrefixedValueSourceWrapper( new PropertiesBasedValueSource( properties ), possiblePrefixes, - allowUnprefixedExpressions ) ); + public PrefixedPropertiesValueSource( + List possiblePrefixes, Properties properties, boolean allowUnprefixedExpressions) { + super(new PrefixedValueSourceWrapper( + new PropertiesBasedValueSource(properties), possiblePrefixes, allowUnprefixedExpressions)); } } diff --git a/src/main/java/org/codehaus/plexus/interpolation/fixed/PrefixedValueSourceWrapper.java b/src/main/java/org/codehaus/plexus/interpolation/fixed/PrefixedValueSourceWrapper.java index 7475070..bca5f91 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/fixed/PrefixedValueSourceWrapper.java +++ b/src/main/java/org/codehaus/plexus/interpolation/fixed/PrefixedValueSourceWrapper.java @@ -16,10 +16,10 @@ * limitations under the License. */ -import org.codehaus.plexus.interpolation.util.ValueSourceUtils; - import java.util.List; +import org.codehaus.plexus.interpolation.util.ValueSourceUtils; + /** * {@link org.codehaus.plexus.interpolation.fixed.FixedValueSource} implementation which simply wraps another * value source, and trims any of a set of possible expression prefixes before delegating the @@ -28,8 +28,7 @@ * @author jdcasey * @author krosenvold */ -public class PrefixedValueSourceWrapper implements FixedValueSource -{ +public class PrefixedValueSourceWrapper implements FixedValueSource { private final FixedValueSource valueSource; @@ -47,10 +46,9 @@ public class PrefixedValueSourceWrapper implements FixedValueSource * @param valueSource The {@link org.codehaus.plexus.interpolation.ValueSource} to wrap. * @param prefix The expression prefix to trim. */ - public PrefixedValueSourceWrapper( FixedValueSource valueSource, String prefix ) - { + public PrefixedValueSourceWrapper(FixedValueSource valueSource, String prefix) { this.valueSource = valueSource; - possiblePrefixes = new String[]{ prefix }; + possiblePrefixes = new String[] {prefix}; } /** @@ -66,10 +64,9 @@ public PrefixedValueSourceWrapper( FixedValueSource valueSource, String prefix ) * @param allowUnprefixedExpressions Flag telling the wrapper whether to * continue resolving expressions that don't start with the prefix it tracks. */ - public PrefixedValueSourceWrapper( FixedValueSource valueSource, String prefix, boolean allowUnprefixedExpressions ) - { + public PrefixedValueSourceWrapper(FixedValueSource valueSource, String prefix, boolean allowUnprefixedExpressions) { this.valueSource = valueSource; - possiblePrefixes = new String[]{ prefix }; + possiblePrefixes = new String[] {prefix}; this.allowUnprefixedExpressions = allowUnprefixedExpressions; } @@ -81,10 +78,9 @@ public PrefixedValueSourceWrapper( FixedValueSource valueSource, String prefix, * @param valueSource The {@link org.codehaus.plexus.interpolation.ValueSource} to wrap. * @param possiblePrefixes The List of expression prefixes to trim. */ - public PrefixedValueSourceWrapper( FixedValueSource valueSource, List possiblePrefixes ) - { + public PrefixedValueSourceWrapper(FixedValueSource valueSource, List possiblePrefixes) { this.valueSource = valueSource; - this.possiblePrefixes = possiblePrefixes.toArray( new String[possiblePrefixes.size()] ); + this.possiblePrefixes = possiblePrefixes.toArray(new String[possiblePrefixes.size()]); } /** @@ -100,24 +96,20 @@ public PrefixedValueSourceWrapper( FixedValueSource valueSource, List po * @param allowUnprefixedExpressions Flag telling the wrapper whether to * continue resolving expressions that don't start with one of the prefixes it tracks. */ - public PrefixedValueSourceWrapper( FixedValueSource valueSource, List possiblePrefixes, - boolean allowUnprefixedExpressions ) - { + public PrefixedValueSourceWrapper( + FixedValueSource valueSource, List possiblePrefixes, boolean allowUnprefixedExpressions) { this.valueSource = valueSource; - this.possiblePrefixes = possiblePrefixes.toArray( new String[possiblePrefixes.size()] ); + this.possiblePrefixes = possiblePrefixes.toArray(new String[possiblePrefixes.size()]); this.allowUnprefixedExpressions = allowUnprefixedExpressions; } + public Object getValue(String expression, InterpolationState interpolationState) { + expression = ValueSourceUtils.trimPrefix(expression, possiblePrefixes, allowUnprefixedExpressions); - public Object getValue( String expression, InterpolationState interpolationState ) - { - expression = ValueSourceUtils.trimPrefix( expression, possiblePrefixes, allowUnprefixedExpressions ); - - if ( expression == null ) - { + if (expression == null) { return null; } - return valueSource.getValue( expression, interpolationState ); + return valueSource.getValue(expression, interpolationState); } } diff --git a/src/main/java/org/codehaus/plexus/interpolation/fixed/PropertiesBasedValueSource.java b/src/main/java/org/codehaus/plexus/interpolation/fixed/PropertiesBasedValueSource.java index ff4a98f..3b5d089 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/fixed/PropertiesBasedValueSource.java +++ b/src/main/java/org/codehaus/plexus/interpolation/fixed/PropertiesBasedValueSource.java @@ -16,7 +16,6 @@ * limitations under the License. */ - import java.util.Properties; /** @@ -27,9 +26,7 @@ * * @author jdcasey */ -public class PropertiesBasedValueSource - implements FixedValueSource -{ +public class PropertiesBasedValueSource implements FixedValueSource { private final Properties properties; @@ -39,8 +36,7 @@ public class PropertiesBasedValueSource * * @param properties The properties instance to wrap. */ - public PropertiesBasedValueSource( Properties properties ) - { + public PropertiesBasedValueSource(Properties properties) { this.properties = properties; } @@ -49,10 +45,7 @@ public PropertiesBasedValueSource( Properties properties ) * entire expression as the key to lookup. If the wrapped properties instance * is null, simply return null. */ - - public Object getValue( String expression, InterpolationState interpolationState ) - { - return properties == null ? null : properties.getProperty( expression ); + public Object getValue(String expression, InterpolationState interpolationState) { + return properties == null ? null : properties.getProperty(expression); } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/multi/DelimiterSpecification.java b/src/main/java/org/codehaus/plexus/interpolation/multi/DelimiterSpecification.java index 194d954..c44d21f 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/multi/DelimiterSpecification.java +++ b/src/main/java/org/codehaus/plexus/interpolation/multi/DelimiterSpecification.java @@ -16,109 +16,81 @@ * limitations under the License. */ -public final class DelimiterSpecification -{ - public static final DelimiterSpecification DEFAULT_SPEC = DelimiterSpecification.parse( "${*}" ); - +public final class DelimiterSpecification { + public static final DelimiterSpecification DEFAULT_SPEC = DelimiterSpecification.parse("${*}"); + private String begin; - + private String end; private int nextStart; - - public DelimiterSpecification( String begin, String end ) - { + + public DelimiterSpecification(String begin, String end) { this.begin = begin; this.end = end; } - - public int getNextStartIndex() - { + + public int getNextStartIndex() { return nextStart; } - - public void setNextStartIndex( int nextStart ) - { + + public void setNextStartIndex(int nextStart) { this.nextStart = nextStart; } - - public void clearNextStart() - { + + public void clearNextStart() { nextStart = -1; } - public static DelimiterSpecification parse( String delimiterSpec ) - { + public static DelimiterSpecification parse(String delimiterSpec) { final String[] spec = new String[2]; - - int splitIdx = delimiterSpec.indexOf( '*' ); - if ( splitIdx < 0 ) - { + + int splitIdx = delimiterSpec.indexOf('*'); + if (splitIdx < 0) { spec[0] = delimiterSpec; spec[1] = spec[0]; - } - else if ( splitIdx == delimiterSpec.length() - 1 ) - { - spec[0] = delimiterSpec.substring( 0, delimiterSpec.length() - 1 ); + } else if (splitIdx == delimiterSpec.length() - 1) { + spec[0] = delimiterSpec.substring(0, delimiterSpec.length() - 1); spec[1] = spec[0]; + } else { + spec[0] = delimiterSpec.substring(0, splitIdx); + spec[1] = delimiterSpec.substring(splitIdx + 1); } - else - { - spec[0] = delimiterSpec.substring( 0, splitIdx ); - spec[1] = delimiterSpec.substring( splitIdx + 1 ); - } - - return new DelimiterSpecification( spec[0], spec[1] ); + + return new DelimiterSpecification(spec[0], spec[1]); } - public String getBegin() - { + public String getBegin() { return begin; } - public String getEnd() - { + public String getEnd() { return end; } - public int hashCode() - { + public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ( ( begin == null ) ? 0 : begin.hashCode() ); - result = prime * result + ( ( end == null ) ? 0 : end.hashCode() ); + result = prime * result + ((begin == null) ? 0 : begin.hashCode()); + result = prime * result + ((end == null) ? 0 : end.hashCode()); return result; } - public boolean equals( Object obj ) - { - if ( this == obj ) - return true; - if ( obj == null ) - return false; - if ( getClass() != obj.getClass() ) - return false; + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; DelimiterSpecification other = (DelimiterSpecification) obj; - if ( begin == null ) - { - if ( other.begin != null ) - return false; - } - else if ( !begin.equals( other.begin ) ) - return false; - if ( end == null ) - { - if ( other.end != null ) - return false; - } - else if ( !end.equals( other.end ) ) - return false; + if (begin == null) { + if (other.begin != null) return false; + } else if (!begin.equals(other.begin)) return false; + if (end == null) { + if (other.end != null) return false; + } else if (!end.equals(other.end)) return false; return true; } - - public String toString() - { + + public String toString() { return "Interpolation delimiter [begin: '" + begin + "', end: '" + end + "']"; } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterInterpolatorFilterReader.java b/src/main/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterInterpolatorFilterReader.java index e8b57f8..b86dc52 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterInterpolatorFilterReader.java +++ b/src/main/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterInterpolatorFilterReader.java @@ -54,29 +54,27 @@ package org.codehaus.plexus.interpolation.multi; -import org.codehaus.plexus.interpolation.InterpolationException; -import org.codehaus.plexus.interpolation.Interpolator; -import org.codehaus.plexus.interpolation.RecursionInterceptor; -import org.codehaus.plexus.interpolation.SimpleRecursionInterceptor; - import java.io.FilterReader; import java.io.IOException; import java.io.Reader; import java.util.LinkedHashSet; +import org.codehaus.plexus.interpolation.InterpolationException; +import org.codehaus.plexus.interpolation.Interpolator; +import org.codehaus.plexus.interpolation.RecursionInterceptor; +import org.codehaus.plexus.interpolation.SimpleRecursionInterceptor; + /** * A FilterReader implementation, that works with Interpolator interface instead of it's own interpolation * implementation. This implementation is heavily based on org.codehaus.plexus.util.InterpolationFilterReader. * * @author cstamas */ -public class MultiDelimiterInterpolatorFilterReader - extends FilterReader -{ +public class MultiDelimiterInterpolatorFilterReader extends FilterReader { /** Interpolator used to interpolate */ private Interpolator interpolator; - + /** * @since 1.12 */ @@ -96,19 +94,19 @@ public class MultiDelimiterInterpolatorFilterReader /** Default end token. */ public static final String DEFAULT_END_TOKEN = "}"; - + /** true by default to preserve backward comp */ private boolean interpolateWithPrefixPattern = true; private String escapeString; - + private boolean useEscape = false; - + /** if true escapeString will be preserved \{foo} -> \{foo} */ private boolean preserveEscapeString = false; - + private LinkedHashSet delimiters = new LinkedHashSet(); - + private DelimiterSpecification currentSpec; private String beginToken; @@ -116,71 +114,62 @@ public class MultiDelimiterInterpolatorFilterReader private String originalBeginToken; private String endToken; - + /** - * this constructor use default begin token ${ and default end token } + * this constructor use default begin token ${ and default end token } * @param in reader to use * @param interpolator interpolator instance to use */ - public MultiDelimiterInterpolatorFilterReader( Reader in, Interpolator interpolator ) - { - this( in, interpolator, new SimpleRecursionInterceptor() ); + public MultiDelimiterInterpolatorFilterReader(Reader in, Interpolator interpolator) { + this(in, interpolator, new SimpleRecursionInterceptor()); } - + /** * @param in reader to use * @param interpolator interpolator instance to use * @param ri The {@link RecursionInterceptor} to use to prevent recursive expressions. * @since 1.12 */ - public MultiDelimiterInterpolatorFilterReader( Reader in, Interpolator interpolator, RecursionInterceptor ri ) - { - super( in ); + public MultiDelimiterInterpolatorFilterReader(Reader in, Interpolator interpolator, RecursionInterceptor ri) { + super(in); this.interpolator = interpolator; - + // always cache answers, since we'll be sending in pure expressions, not mixed text. - this.interpolator.setCacheAnswers( true ); - + this.interpolator.setCacheAnswers(true); + recursionInterceptor = ri; - - delimiters.add( DelimiterSpecification.DEFAULT_SPEC ); - } - - public MultiDelimiterInterpolatorFilterReader addDelimiterSpec( String delimiterSpec ) - { - if ( delimiterSpec == null ) - { + + delimiters.add(DelimiterSpecification.DEFAULT_SPEC); + } + + public MultiDelimiterInterpolatorFilterReader addDelimiterSpec(String delimiterSpec) { + if (delimiterSpec == null) { return this; - } - delimiters.add( DelimiterSpecification.parse( delimiterSpec ) ); + } + delimiters.add(DelimiterSpecification.parse(delimiterSpec)); return this; } - - public boolean removeDelimiterSpec( String delimiterSpec ) - { - if ( delimiterSpec == null ) - { + + public boolean removeDelimiterSpec(String delimiterSpec) { + if (delimiterSpec == null) { return false; - } - return delimiters.remove( DelimiterSpecification.parse( delimiterSpec ) ); + } + return delimiters.remove(DelimiterSpecification.parse(delimiterSpec)); } - - public MultiDelimiterInterpolatorFilterReader setDelimiterSpecs( LinkedHashSet specs ) - { + + public MultiDelimiterInterpolatorFilterReader setDelimiterSpecs(LinkedHashSet specs) { delimiters.clear(); - for ( String spec : specs ) - { - if ( spec == null ) - { + for (String spec : specs) { + if (spec == null) { continue; } - delimiters.add( DelimiterSpecification.parse( spec ) ); + delimiters.add(DelimiterSpecification.parse(spec)); } - + return this; } - + /** * Skips characters. This method will block until some characters are available, an I/O error occurs, or the end of * the stream is reached. @@ -190,18 +179,13 @@ public MultiDelimiterInterpolatorFilterReader setDelimiterSpecs( LinkedHashSetn is negative. * @exception IOException If an I/O error occurs */ - public long skip( long n ) - throws IOException - { - if ( n < 0L ) - { - throw new IllegalArgumentException( "skip value is negative" ); + public long skip(long n) throws IOException { + if (n < 0L) { + throw new IllegalArgumentException("skip value is negative"); } - for ( long i = 0; i < n; i++ ) - { - if ( read() == -1 ) - { + for (long i = 0; i < n; i++) { + if (read() == -1) { return i; } } @@ -218,20 +202,13 @@ public long skip( long n ) * @return the number of characters read, or -1 if the end of the stream has been reached * @exception IOException If an I/O error occurs */ - public int read( char cbuf[], int off, int len ) - throws IOException - { - for ( int i = 0; i < len; i++ ) - { + public int read(char cbuf[], int off, int len) throws IOException { + for (int i = 0; i < len; i++) { int ch = read(); - if ( ch == -1 ) - { - if ( i == 0 ) - { + if (ch == -1) { + if (i == 0) { return -1; - } - else - { + } else { return i; } } @@ -246,218 +223,163 @@ public int read( char cbuf[], int off, int len ) * @return the next character in the resulting stream, or -1 if the end of the resulting stream has been reached * @exception IOException if the underlying stream throws an IOException during reading */ - public int read() - throws IOException - { - if ( replaceIndex != -1 && replaceIndex < replaceData.length() ) - { - int ch = replaceData.charAt( replaceIndex++ ); - if ( replaceIndex >= replaceData.length() ) - { + public int read() throws IOException { + if (replaceIndex != -1 && replaceIndex < replaceData.length()) { + int ch = replaceData.charAt(replaceIndex++); + if (replaceIndex >= replaceData.length()) { replaceIndex = -1; } return ch; } int ch = -1; - if ( previousIndex != -1 && previousIndex < this.endToken.length() ) - { - ch = this.endToken.charAt( previousIndex++ ); - } - else - { + if (previousIndex != -1 && previousIndex < this.endToken.length()) { + ch = this.endToken.charAt(previousIndex++); + } else { ch = in.read(); } - + boolean inEscape = false; - - if ( ( inEscape = ( useEscape && ch == escapeString.charAt( 0 ) ) ) || reselectDelimiterSpec( ch ) ) - { - StringBuilder key = new StringBuilder( ); - key.append( (char) ch ); - + if ((inEscape = (useEscape && ch == escapeString.charAt(0))) || reselectDelimiterSpec(ch)) { + StringBuilder key = new StringBuilder(); + + key.append((char) ch); + // this will happen when we're using an escape string, and ONLY then. boolean atEnd = false; - if ( inEscape ) - { - for( int i = 0; i < escapeString.length() - 1; i++ ) - { + if (inEscape) { + for (int i = 0; i < escapeString.length() - 1; i++) { ch = in.read(); - if ( ch == -1 ) - { + if (ch == -1) { atEnd = true; break; } - - key.append( (char) ch ); + + key.append((char) ch); } - - if ( !atEnd ) - { + + if (!atEnd) { ch = in.read(); - if ( !reselectDelimiterSpec( ch ) ) - { + if (!reselectDelimiterSpec(ch)) { replaceData = key.toString(); replaceIndex = 1; - return replaceData.charAt( 0 ); - } - else - { - key.append( (char) ch ); + return replaceData.charAt(0); + } else { + key.append((char) ch); } } } int beginTokenMatchPos = 1; - do - { - if ( atEnd ) - { + do { + if (atEnd) { // didn't finish reading the escape string. break; } - - if ( previousIndex != -1 && previousIndex < this.endToken.length() ) - { - ch = this.endToken.charAt( previousIndex++ ); - } - else - { + + if (previousIndex != -1 && previousIndex < this.endToken.length()) { + ch = this.endToken.charAt(previousIndex++); + } else { ch = in.read(); } - if ( ch != -1 ) - { - key.append( (char) ch ); - if ( ( beginTokenMatchPos < this.originalBeginToken.length() ) - && ( ch != this.originalBeginToken.charAt( beginTokenMatchPos ) ) ) - { + if (ch != -1) { + key.append((char) ch); + if ((beginTokenMatchPos < this.originalBeginToken.length()) + && (ch != this.originalBeginToken.charAt(beginTokenMatchPos))) { ch = -1; // not really EOF but to trigger code below break; } - } - else - { + } else { break; } - + beginTokenMatchPos++; - } - while ( ch != this.endToken.charAt( 0 ) ); + } while (ch != this.endToken.charAt(0)); // now test endToken - if ( ch != -1 && this.endToken.length() > 1 ) - { + if (ch != -1 && this.endToken.length() > 1) { int endTokenMatchPos = 1; - do - { - if ( previousIndex != -1 && previousIndex < this.endToken.length() ) - { - ch = this.endToken.charAt( previousIndex++ ); - } - else - { + do { + if (previousIndex != -1 && previousIndex < this.endToken.length()) { + ch = this.endToken.charAt(previousIndex++); + } else { ch = in.read(); } - if ( ch != -1 ) - { - key.append( (char) ch ); + if (ch != -1) { + key.append((char) ch); - if ( ch != this.endToken.charAt( endTokenMatchPos++ ) ) - { + if (ch != this.endToken.charAt(endTokenMatchPos++)) { ch = -1; // not really EOF but to trigger code below break; } - } - else - { + } else { break; } - } - while ( endTokenMatchPos < this.endToken.length() ); + } while (endTokenMatchPos < this.endToken.length()); } // There is nothing left to read so we have the situation where the begin/end token // are in fact the same and as there is nothing left to read we have got ourselves // end of a token boundary so let it pass through. - if ( ch == -1 ) - { + if (ch == -1) { replaceData = key.toString(); replaceIndex = 1; - return replaceData.charAt( 0 ); + return replaceData.charAt(0); } String value = null; - try - { + try { boolean escapeFound = false; - if ( useEscape ) - { - if ( key.toString().startsWith( beginToken ) ) - { + if (useEscape) { + if (key.toString().startsWith(beginToken)) { String keyStr = key.toString(); - if ( !preserveEscapeString ) - { - value = keyStr.substring( escapeString.length(), keyStr.length() ); - } - else - { + if (!preserveEscapeString) { + value = keyStr.substring(escapeString.length(), keyStr.length()); + } else { value = keyStr; } escapeFound = true; } } - if ( !escapeFound ) - { - if ( interpolateWithPrefixPattern ) - { - value = interpolator.interpolate( key.toString(), "", recursionInterceptor ); - } - else - { - value = interpolator.interpolate( key.toString(), recursionInterceptor ); + if (!escapeFound) { + if (interpolateWithPrefixPattern) { + value = interpolator.interpolate(key.toString(), "", recursionInterceptor); + } else { + value = interpolator.interpolate(key.toString(), recursionInterceptor); } } - } - catch ( InterpolationException e ) - { - IllegalArgumentException error = new IllegalArgumentException( e.getMessage() ); - error.initCause( e ); + } catch (InterpolationException e) { + IllegalArgumentException error = new IllegalArgumentException(e.getMessage()); + error.initCause(e); throw error; } - if ( value != null ) - { - if ( value.length() != 0 ) - { + if (value != null) { + if (value.length() != 0) { replaceData = value; replaceIndex = 0; } return read(); - } - else - { + } else { previousIndex = 0; - replaceData = key.substring( 0, key.length() - this.endToken.length() ); + replaceData = key.substring(0, key.length() - this.endToken.length()); replaceIndex = 0; - return this.beginToken.charAt( 0 ); + return this.beginToken.charAt(0); } } return ch; } - private boolean reselectDelimiterSpec( int ch ) - { - for ( DelimiterSpecification spec : delimiters ) - { - if ( ch == spec.getBegin().charAt( 0 ) ) - { + private boolean reselectDelimiterSpec(int ch) { + for (DelimiterSpecification spec : delimiters) { + if (ch == spec.getBegin().charAt(0)) { currentSpec = spec; originalBeginToken = currentSpec.getBegin(); beginToken = useEscape ? escapeString + originalBeginToken : originalBeginToken; @@ -466,51 +388,43 @@ private boolean reselectDelimiterSpec( int ch ) return true; } } - + return false; } - public boolean isInterpolateWithPrefixPattern() - { + public boolean isInterpolateWithPrefixPattern() { return interpolateWithPrefixPattern; } - public void setInterpolateWithPrefixPattern( boolean interpolateWithPrefixPattern ) - { + public void setInterpolateWithPrefixPattern(boolean interpolateWithPrefixPattern) { this.interpolateWithPrefixPattern = interpolateWithPrefixPattern; } - public String getEscapeString() - { + + public String getEscapeString() { return escapeString; } - public void setEscapeString( String escapeString ) - { + public void setEscapeString(String escapeString) { // TODO NPE if escapeString is null ? - if ( escapeString != null && escapeString.length() >= 1 ) - { + if (escapeString != null && escapeString.length() >= 1) { this.escapeString = escapeString; this.useEscape = escapeString != null && escapeString.length() >= 1; } } - public boolean isPreserveEscapeString() - { + public boolean isPreserveEscapeString() { return preserveEscapeString; } - public void setPreserveEscapeString( boolean preserveEscapeString ) - { + public void setPreserveEscapeString(boolean preserveEscapeString) { this.preserveEscapeString = preserveEscapeString; } - public RecursionInterceptor getRecursionInterceptor() - { + public RecursionInterceptor getRecursionInterceptor() { return recursionInterceptor; } - public MultiDelimiterInterpolatorFilterReader setRecursionInterceptor( RecursionInterceptor recursionInterceptor ) - { + public MultiDelimiterInterpolatorFilterReader setRecursionInterceptor(RecursionInterceptor recursionInterceptor) { this.recursionInterceptor = recursionInterceptor; return this; } diff --git a/src/main/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterStringSearchInterpolator.java b/src/main/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterStringSearchInterpolator.java index c3d13d4..fc472e2 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterStringSearchInterpolator.java +++ b/src/main/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterStringSearchInterpolator.java @@ -16,14 +16,6 @@ * limitations under the License. */ -import org.codehaus.plexus.interpolation.InterpolationCycleException; -import org.codehaus.plexus.interpolation.InterpolationException; -import org.codehaus.plexus.interpolation.InterpolationPostProcessor; -import org.codehaus.plexus.interpolation.Interpolator; -import org.codehaus.plexus.interpolation.RecursionInterceptor; -import org.codehaus.plexus.interpolation.SimpleRecursionInterceptor; -import org.codehaus.plexus.interpolation.ValueSource; - import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -32,12 +24,18 @@ import java.util.Map; import java.util.Set; -public class MultiDelimiterStringSearchInterpolator - implements Interpolator -{ +import org.codehaus.plexus.interpolation.InterpolationCycleException; +import org.codehaus.plexus.interpolation.InterpolationException; +import org.codehaus.plexus.interpolation.InterpolationPostProcessor; +import org.codehaus.plexus.interpolation.Interpolator; +import org.codehaus.plexus.interpolation.RecursionInterceptor; +import org.codehaus.plexus.interpolation.SimpleRecursionInterceptor; +import org.codehaus.plexus.interpolation.ValueSource; + +public class MultiDelimiterStringSearchInterpolator implements Interpolator { private static final int MAX_TRIES = 10; - + private Map existingAnswers = new HashMap(); private List valueSources = new ArrayList(); @@ -50,199 +48,162 @@ public class MultiDelimiterStringSearchInterpolator private String escapeString; - public MultiDelimiterStringSearchInterpolator() - { - delimiters.add( DelimiterSpecification.DEFAULT_SPEC ); + public MultiDelimiterStringSearchInterpolator() { + delimiters.add(DelimiterSpecification.DEFAULT_SPEC); } - - public MultiDelimiterStringSearchInterpolator addDelimiterSpec( String delimiterSpec ) - { - if ( delimiterSpec == null ) - { + + public MultiDelimiterStringSearchInterpolator addDelimiterSpec(String delimiterSpec) { + if (delimiterSpec == null) { return this; } - delimiters.add( DelimiterSpecification.parse( delimiterSpec ) ); + delimiters.add(DelimiterSpecification.parse(delimiterSpec)); return this; } - - public boolean removeDelimiterSpec( String delimiterSpec ) - { - if ( delimiterSpec == null ) - { + + public boolean removeDelimiterSpec(String delimiterSpec) { + if (delimiterSpec == null) { return false; - } - return delimiters.remove( DelimiterSpecification.parse( delimiterSpec ) ); + } + return delimiters.remove(DelimiterSpecification.parse(delimiterSpec)); } - - public MultiDelimiterStringSearchInterpolator withValueSource( ValueSource vs ) - { - addValueSource( vs ); + + public MultiDelimiterStringSearchInterpolator withValueSource(ValueSource vs) { + addValueSource(vs); return this; } - - public MultiDelimiterStringSearchInterpolator withPostProcessor( InterpolationPostProcessor postProcessor ) - { - addPostProcessor( postProcessor ); + + public MultiDelimiterStringSearchInterpolator withPostProcessor(InterpolationPostProcessor postProcessor) { + addPostProcessor(postProcessor); return this; } /** * {@inheritDoc} */ - public void addValueSource( ValueSource valueSource ) - { - valueSources.add( valueSource ); + public void addValueSource(ValueSource valueSource) { + valueSources.add(valueSource); } /** * {@inheritDoc} */ - public void removeValuesSource( ValueSource valueSource ) - { - valueSources.remove( valueSource ); + public void removeValuesSource(ValueSource valueSource) { + valueSources.remove(valueSource); } /** * {@inheritDoc} */ - public void addPostProcessor( InterpolationPostProcessor postProcessor ) - { - postProcessors.add( postProcessor ); + public void addPostProcessor(InterpolationPostProcessor postProcessor) { + postProcessors.add(postProcessor); } /** * {@inheritDoc} */ - public void removePostProcessor( InterpolationPostProcessor postProcessor ) - { - postProcessors.remove( postProcessor ); + public void removePostProcessor(InterpolationPostProcessor postProcessor) { + postProcessors.remove(postProcessor); } - public String interpolate( String input, String thisPrefixPattern ) - throws InterpolationException - { - return interpolate( input, new SimpleRecursionInterceptor() ); + public String interpolate(String input, String thisPrefixPattern) throws InterpolationException { + return interpolate(input, new SimpleRecursionInterceptor()); } - public String interpolate( String input, String thisPrefixPattern, RecursionInterceptor recursionInterceptor ) - throws InterpolationException - { - return interpolate( input, recursionInterceptor ); + public String interpolate(String input, String thisPrefixPattern, RecursionInterceptor recursionInterceptor) + throws InterpolationException { + return interpolate(input, recursionInterceptor); } - public String interpolate( String input ) - throws InterpolationException - { - return interpolate( input, new SimpleRecursionInterceptor() ); + public String interpolate(String input) throws InterpolationException { + return interpolate(input, new SimpleRecursionInterceptor()); } /** * Entry point for recursive resolution of an expression and all of its nested expressions. - * + * * TODO: Ensure unresolvable expressions don't trigger infinite recursion. */ - public String interpolate( String input, RecursionInterceptor recursionInterceptor ) - throws InterpolationException - { - try - { - return interpolate( input, recursionInterceptor, new HashSet() ); - } - finally - { - if ( !cacheAnswers ) - { + public String interpolate(String input, RecursionInterceptor recursionInterceptor) throws InterpolationException { + try { + return interpolate(input, recursionInterceptor, new HashSet()); + } finally { + if (!cacheAnswers) { existingAnswers.clear(); } } } - private String interpolate( String input, RecursionInterceptor recursionInterceptor, Set unresolvable ) - throws InterpolationException - { - if ( input == null ) - { + private String interpolate(String input, RecursionInterceptor recursionInterceptor, Set unresolvable) + throws InterpolationException { + if (input == null) { // return empty String to prevent NPE too return ""; } - StringBuilder result = new StringBuilder( input.length() * 2 ); + StringBuilder result = new StringBuilder(input.length() * 2); String lastResult = input; int tries = 0; - do - { + do { tries++; - if ( result.length() > 0 ) - { + if (result.length() > 0) { lastResult = result.toString(); - result.setLength( 0 ); + result.setLength(0); } - + int startIdx = -1; int endIdx = -1; - + DelimiterSpecification selectedSpec = null; - while( ( selectedSpec = select( input, endIdx ) ) != null ) - { + while ((selectedSpec = select(input, endIdx)) != null) { String startExpr = selectedSpec.getBegin(); String endExpr = selectedSpec.getEnd(); - + startIdx = selectedSpec.getNextStartIndex(); - result.append( input, endIdx + 1, startIdx ); + result.append(input, endIdx + 1, startIdx); - endIdx = input.indexOf( endExpr, startIdx + 1 ); - if ( endIdx < 0 ) - { + endIdx = input.indexOf(endExpr, startIdx + 1); + if (endIdx < 0) { break; } - String wholeExpr = input.substring( startIdx, endIdx + endExpr.length() ); - String realExpr = wholeExpr.substring( startExpr.length(), wholeExpr.length() - endExpr.length() ); - - if ( startIdx >= 0 && escapeString != null && escapeString.length() > 0 ) - { - int startEscapeIdx = ( startIdx == 0 ) ? 0 : startIdx - escapeString.length(); - if ( startEscapeIdx >= 0 ) - { - String escape = input.substring( startEscapeIdx, startIdx ); - if ( escape != null && escapeString.equals( escape ) ) - { - result.append( wholeExpr ); - if ( startEscapeIdx > 0 ) - { + String wholeExpr = input.substring(startIdx, endIdx + endExpr.length()); + String realExpr = wholeExpr.substring(startExpr.length(), wholeExpr.length() - endExpr.length()); + + if (startIdx >= 0 && escapeString != null && escapeString.length() > 0) { + int startEscapeIdx = (startIdx == 0) ? 0 : startIdx - escapeString.length(); + if (startEscapeIdx >= 0) { + String escape = input.substring(startEscapeIdx, startIdx); + if (escape != null && escapeString.equals(escape)) { + result.append(wholeExpr); + if (startEscapeIdx > 0) { --startEscapeIdx; } - result.replace( startEscapeIdx, startEscapeIdx + escapeString.length(), "" ); + result.replace(startEscapeIdx, startEscapeIdx + escapeString.length(), ""); continue; } } } boolean resolved = false; - if ( !unresolvable.contains( wholeExpr ) ) - { - if ( realExpr.startsWith( "." ) ) - { - realExpr = realExpr.substring( 1 ); + if (!unresolvable.contains(wholeExpr)) { + if (realExpr.startsWith(".")) { + realExpr = realExpr.substring(1); } - if ( recursionInterceptor.hasRecursiveExpression( realExpr ) ) - { - throw new InterpolationCycleException( recursionInterceptor, realExpr, wholeExpr ); + if (recursionInterceptor.hasRecursiveExpression(realExpr)) { + throw new InterpolationCycleException(recursionInterceptor, realExpr, wholeExpr); } - recursionInterceptor.expressionResolutionStarted( realExpr ); + recursionInterceptor.expressionResolutionStarted(realExpr); - Object value = existingAnswers.get( realExpr ); + Object value = existingAnswers.get(realExpr); Object bestAnswer = null; - for ( ValueSource vs : valueSources ) - { - if (value != null ) break; + for (ValueSource vs : valueSources) { + if (value != null) break; - value = vs.getValue( realExpr ); + value = vs.getValue(realExpr); - if ( value != null && value.toString().contains( wholeExpr ) ) - { + if (value != null && value.toString().contains(wholeExpr)) { bestAnswer = value; value = null; } @@ -251,23 +212,18 @@ private String interpolate( String input, RecursionInterceptor recursionIntercep // this is the simplest recursion check to catch exact recursion // (non synonym), and avoid the extra effort of more string // searching. - if ( value == null && bestAnswer != null ) - { - throw new InterpolationCycleException( recursionInterceptor, realExpr, wholeExpr ); + if (value == null && bestAnswer != null) { + throw new InterpolationCycleException(recursionInterceptor, realExpr, wholeExpr); } - if ( value != null ) - { - value = interpolate( String.valueOf( value ), recursionInterceptor, unresolvable ); + if (value != null) { + value = interpolate(String.valueOf(value), recursionInterceptor, unresolvable); - if ( postProcessors != null && !postProcessors.isEmpty() ) - { - for ( Object postProcessor1 : postProcessors ) - { + if (postProcessors != null && !postProcessors.isEmpty()) { + for (Object postProcessor1 : postProcessors) { InterpolationPostProcessor postProcessor = (InterpolationPostProcessor) postProcessor1; - Object newVal = postProcessor.execute( realExpr, value ); - if ( newVal != null ) - { + Object newVal = postProcessor.execute(realExpr, value); + if (newVal != null) { value = newVal; break; } @@ -276,62 +232,51 @@ private String interpolate( String input, RecursionInterceptor recursionIntercep // could use: // result = matcher.replaceFirst( stringValue ); - // but this could result in multiple lookups of stringValue, and replaceAll is not correct behaviour - result.append( String.valueOf( value ) ); + // but this could result in multiple lookups of stringValue, and replaceAll is not correct + // behaviour + result.append(String.valueOf(value)); resolved = true; - } - else - { - unresolvable.add( wholeExpr ); + } else { + unresolvable.add(wholeExpr); } - recursionInterceptor.expressionResolutionFinished( realExpr ); + recursionInterceptor.expressionResolutionFinished(realExpr); } - if ( !resolved ) - { - result.append( wholeExpr ); + if (!resolved) { + result.append(wholeExpr); } - if ( endIdx > -1 ) - { + if (endIdx > -1) { endIdx += endExpr.length() - 1; } } - if ( endIdx == -1 && startIdx > -1 ) - { - result.append( input, startIdx, input.length() ); + if (endIdx == -1 && startIdx > -1) { + result.append(input, startIdx, input.length()); + } else if (endIdx < input.length()) { + result.append(input, endIdx + 1, input.length()); } - else if ( endIdx < input.length() ) - { - result.append( input, endIdx + 1, input.length() ); - } - } - while( !lastResult.equals( result.toString() ) && tries < MAX_TRIES ); + } while (!lastResult.equals(result.toString()) && tries < MAX_TRIES); return result.toString(); } - private DelimiterSpecification select( String input, int lastEndIdx ) - { + private DelimiterSpecification select(String input, int lastEndIdx) { DelimiterSpecification selected = null; - for ( DelimiterSpecification spec : delimiters ) - { + for (DelimiterSpecification spec : delimiters) { spec.clearNextStart(); - if ( selected == null ) - { - int idx = input.indexOf( spec.getBegin(), lastEndIdx + 1 ); - if ( idx > -1 ) - { - spec.setNextStartIndex( idx ); + if (selected == null) { + int idx = input.indexOf(spec.getBegin(), lastEndIdx + 1); + if (idx > -1) { + spec.setNextStartIndex(idx); selected = spec; } } } - + return selected; } @@ -339,18 +284,15 @@ private DelimiterSpecification select( String input, int lastEndIdx ) * Return any feedback messages and errors that were generated - but suppressed - during the interpolation process. * Since unresolvable expressions will be left in the source string as-is, this feedback is optional, and will only * be useful for debugging interpolation problems. - * + * * @return a {@link List} that may be interspersed with {@link String} and {@link Throwable} instances. */ - public List getFeedback() - { + public List getFeedback() { List messages = new ArrayList(); - for ( ValueSource vs : valueSources ) - { + for (ValueSource vs : valueSources) { List feedback = vs.getFeedback(); - if ( feedback != null && !feedback.isEmpty() ) - { - messages.addAll( feedback ); + if (feedback != null && !feedback.isEmpty()) { + messages.addAll(feedback); } } @@ -360,58 +302,46 @@ public List getFeedback() /** * Clear the feedback messages from previous interpolate(..) calls. */ - public void clearFeedback() - { - for ( ValueSource vs : valueSources ) - { + public void clearFeedback() { + for (ValueSource vs : valueSources) { vs.clearFeedback(); } } - public boolean isCacheAnswers() - { + public boolean isCacheAnswers() { return cacheAnswers; } - public void setCacheAnswers( boolean cacheAnswers ) - { + public void setCacheAnswers(boolean cacheAnswers) { this.cacheAnswers = cacheAnswers; } - public void clearAnswers() - { + public void clearAnswers() { existingAnswers.clear(); } - public String getEscapeString() - { + public String getEscapeString() { return escapeString; } - public void setEscapeString( String escapeString ) - { + public void setEscapeString(String escapeString) { this.escapeString = escapeString; } - public MultiDelimiterStringSearchInterpolator escapeString( String escapeString ) - { + public MultiDelimiterStringSearchInterpolator escapeString(String escapeString) { this.escapeString = escapeString; return this; } - - public MultiDelimiterStringSearchInterpolator setDelimiterSpecs( LinkedHashSet specs ) - { + + public MultiDelimiterStringSearchInterpolator setDelimiterSpecs(LinkedHashSet specs) { delimiters.clear(); - for ( String spec : specs ) - { - if ( spec == null ) - { + for (String spec : specs) { + if (spec == null) { continue; } - delimiters.add( DelimiterSpecification.parse( spec ) ); + delimiters.add(DelimiterSpecification.parse(spec)); } - + return this; } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/object/FieldBasedObjectInterpolator.java b/src/main/java/org/codehaus/plexus/interpolation/object/FieldBasedObjectInterpolator.java index fca47d1..a25a8c9 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/object/FieldBasedObjectInterpolator.java +++ b/src/main/java/org/codehaus/plexus/interpolation/object/FieldBasedObjectInterpolator.java @@ -16,12 +16,6 @@ * limitations under the License. */ -import org.codehaus.plexus.interpolation.BasicInterpolator; -import org.codehaus.plexus.interpolation.InterpolationException; -import org.codehaus.plexus.interpolation.Interpolator; -import org.codehaus.plexus.interpolation.RecursionInterceptor; -import org.codehaus.plexus.interpolation.SimpleRecursionInterceptor; - import java.lang.reflect.Array; import java.lang.reflect.Field; import java.security.AccessController; @@ -36,6 +30,12 @@ import java.util.Set; import java.util.WeakHashMap; +import org.codehaus.plexus.interpolation.BasicInterpolator; +import org.codehaus.plexus.interpolation.InterpolationException; +import org.codehaus.plexus.interpolation.Interpolator; +import org.codehaus.plexus.interpolation.RecursionInterceptor; +import org.codehaus.plexus.interpolation.SimpleRecursionInterceptor; + /** * Reflectively traverses an object graph and uses an {@link Interpolator} instance to resolve any String fields in the * graph. @@ -46,9 +46,7 @@ * * @author jdcasey */ -public class FieldBasedObjectInterpolator - implements ObjectInterpolator -{ +public class FieldBasedObjectInterpolator implements ObjectInterpolator { public static final Set DEFAULT_BLACKLISTED_FIELD_NAMES; public static final Set DEFAULT_BLACKLISTED_PACKAGE_PREFIXES; @@ -57,25 +55,23 @@ public class FieldBasedObjectInterpolator private static final Map fieldIsPrimitiveByClass = new WeakHashMap(); - static - { + static { Set blacklistedFields = new HashSet(); - blacklistedFields.add( "parent" ); + blacklistedFields.add("parent"); - DEFAULT_BLACKLISTED_FIELD_NAMES = Collections.unmodifiableSet( blacklistedFields ); + DEFAULT_BLACKLISTED_FIELD_NAMES = Collections.unmodifiableSet(blacklistedFields); Set blacklistedPackages = new HashSet(); - blacklistedPackages.add( "java" ); + blacklistedPackages.add("java"); - DEFAULT_BLACKLISTED_PACKAGE_PREFIXES = Collections.unmodifiableSet( blacklistedPackages ); + DEFAULT_BLACKLISTED_PACKAGE_PREFIXES = Collections.unmodifiableSet(blacklistedPackages); } /** * Clear out the Reflection caches kept for the most expensive operations encountered: field lookup and primitive * queries for fields. These caches are static since they apply at the class level, not the instance level. */ - public static void clearCaches() - { + public static void clearCaches() { fieldsByClass.clear(); fieldIsPrimitiveByClass.clear(); } @@ -90,8 +86,7 @@ public static void clearCaches() * Use the default settings for blacklisted fields and packages, where fields named 'parent' and classes in packages * starting with 'java' will not be interpolated. */ - public FieldBasedObjectInterpolator() - { + public FieldBasedObjectInterpolator() { this.blacklistedFieldNames = DEFAULT_BLACKLISTED_FIELD_NAMES; this.blacklistedPackagePrefixes = DEFAULT_BLACKLISTED_PACKAGE_PREFIXES; } @@ -102,8 +97,7 @@ public FieldBasedObjectInterpolator() * @param blacklistedFieldNames The list of field names to ignore * @param blacklistedPackagePrefixes The list of package prefixes whose classes should be ignored */ - public FieldBasedObjectInterpolator( Set blacklistedFieldNames, Set blacklistedPackagePrefixes ) - { + public FieldBasedObjectInterpolator(Set blacklistedFieldNames, Set blacklistedPackagePrefixes) { this.blacklistedFieldNames = blacklistedFieldNames; this.blacklistedPackagePrefixes = blacklistedPackagePrefixes; } @@ -111,8 +105,7 @@ public FieldBasedObjectInterpolator( Set blacklistedFieldNames, Set getWarnings() - { - return new ArrayList( warnings ); + public List getWarnings() { + return new ArrayList(warnings); } /** @@ -134,10 +126,8 @@ public List getWarnings() * @param interpolator The {@link Interpolator} used to resolve any Strings encountered during traversal. * NOTE: Uses {@link SimpleRecursionInterceptor}. */ - public void interpolate( Object target, BasicInterpolator interpolator ) - throws InterpolationException - { - interpolate( target, interpolator, new SimpleRecursionInterceptor() ); + public void interpolate(Object target, BasicInterpolator interpolator) throws InterpolationException { + interpolate(target, interpolator, new SimpleRecursionInterceptor()); } /** @@ -149,26 +139,26 @@ public void interpolate( Object target, BasicInterpolator interpolator ) * @param interpolator The {@link Interpolator} used to resolve any Strings encountered during traversal. * @param recursionInterceptor The {@link RecursionInterceptor} used to detect cyclical expressions in the graph */ - public void interpolate( Object target, BasicInterpolator interpolator, RecursionInterceptor recursionInterceptor ) - throws InterpolationException - { + public void interpolate(Object target, BasicInterpolator interpolator, RecursionInterceptor recursionInterceptor) + throws InterpolationException { warnings.clear(); - InterpolateObjectAction action = - new InterpolateObjectAction( target, interpolator, recursionInterceptor, blacklistedFieldNames, - blacklistedPackagePrefixes, warnings ); + InterpolateObjectAction action = new InterpolateObjectAction( + target, + interpolator, + recursionInterceptor, + blacklistedFieldNames, + blacklistedPackagePrefixes, + warnings); - InterpolationException error = (InterpolationException) AccessController.doPrivileged( action ); + InterpolationException error = (InterpolationException) AccessController.doPrivileged(action); - if ( error != null ) - { + if (error != null) { throw error; } } - private static final class InterpolateObjectAction - implements PrivilegedAction - { + private static final class InterpolateObjectAction implements PrivilegedAction { private final LinkedList interpolationTargets; @@ -186,18 +176,21 @@ private static final class InterpolateObjectAction * Setup an object graph traversal for the given target starting point. This will initialize a queue of objects * to traverse and interpolate by adding the target object. */ - public InterpolateObjectAction( Object target, BasicInterpolator interpolator, - RecursionInterceptor recursionInterceptor, Set blacklistedFieldNames, - Set blacklistedPackagePrefixes, - List warningCollector ) - { + public InterpolateObjectAction( + Object target, + BasicInterpolator interpolator, + RecursionInterceptor recursionInterceptor, + Set blacklistedFieldNames, + Set blacklistedPackagePrefixes, + List warningCollector) { this.recursionInterceptor = recursionInterceptor; this.blacklistedFieldNames = blacklistedFieldNames; this.warningCollector = warningCollector; - this.blacklistedPackagePrefixes = (String[]) blacklistedPackagePrefixes.toArray( new String[blacklistedPackagePrefixes.size()] ); + this.blacklistedPackagePrefixes = + (String[]) blacklistedPackagePrefixes.toArray(new String[blacklistedPackagePrefixes.size()]); this.interpolationTargets = new LinkedList(); - interpolationTargets.add( new InterpolationTarget( target, "" ) ); + interpolationTargets.add(new InterpolationTarget(target, "")); this.interpolator = interpolator; } @@ -206,18 +199,13 @@ public InterpolateObjectAction( Object target, BasicInterpolator interpolator, * As long as the traversal queue is non-empty, traverse the next object in the queue. If an interpolation error * occurs, return it immediately. */ - public Object run() - { - while ( !interpolationTargets.isEmpty() ) - { + public Object run() { + while (!interpolationTargets.isEmpty()) { InterpolationTarget target = interpolationTargets.removeFirst(); - try - { - traverseObjectWithParents( target.value.getClass(), target ); - } - catch ( InterpolationException e ) - { + try { + traverseObjectWithParents(target.value.getClass(), target); + } catch (InterpolationException e) { return e; } } @@ -229,148 +217,106 @@ public Object run() * Traverse the given object, interpolating any String fields and adding non-primitive field values to the * interpolation queue for later processing. */ - private void traverseObjectWithParents( Class cls, InterpolationTarget target ) - throws InterpolationException - { + private void traverseObjectWithParents(Class cls, InterpolationTarget target) throws InterpolationException { Object obj = target.value; String basePath = target.path; - if ( cls == null ) - { + if (cls == null) { return; } - if ( cls.isArray() ) - { - evaluateArray( obj, basePath ); - } - else if ( isQualifiedForInterpolation( cls ) ) - { - Field[] fields = fieldsByClass.get( cls ); - if ( fields == null ) - { + if (cls.isArray()) { + evaluateArray(obj, basePath); + } else if (isQualifiedForInterpolation(cls)) { + Field[] fields = fieldsByClass.get(cls); + if (fields == null) { fields = cls.getDeclaredFields(); - fieldsByClass.put( cls, fields ); + fieldsByClass.put(cls, fields); } - for ( Field field : fields ) - { + for (Field field : fields) { Class type = field.getType(); - if ( isQualifiedForInterpolation( field, type ) ) - { + if (isQualifiedForInterpolation(field, type)) { boolean isAccessible = field.isAccessible(); - synchronized ( cls ) - { - field.setAccessible( true ); - try - { - try - { - if ( String.class == type ) - { - interpolateString( obj, field ); - } - else if ( Collection.class.isAssignableFrom( type ) ) - { - if ( interpolateCollection( obj, basePath, field ) ) - { + synchronized (cls) { + field.setAccessible(true); + try { + try { + if (String.class == type) { + interpolateString(obj, field); + } else if (Collection.class.isAssignableFrom(type)) { + if (interpolateCollection(obj, basePath, field)) { continue; } + } else if (Map.class.isAssignableFrom(type)) { + interpolateMap(obj, basePath, field); + } else { + interpolateObject(obj, basePath, field); } - else if ( Map.class.isAssignableFrom( type ) ) - { - interpolateMap( obj, basePath, field ); - } - else - { - interpolateObject( obj, basePath, field ); - } - } - catch ( IllegalArgumentException e ) - { - warningCollector.add( - new ObjectInterpolationWarning( "Failed to interpolate field. Skipping.", - basePath + "." + field.getName(), e ) ); - } - catch ( IllegalAccessException e ) - { - warningCollector.add( - new ObjectInterpolationWarning( "Failed to interpolate field. Skipping.", - basePath + "." + field.getName(), e ) ); + } catch (IllegalArgumentException e) { + warningCollector.add(new ObjectInterpolationWarning( + "Failed to interpolate field. Skipping.", + basePath + "." + field.getName(), + e)); + } catch (IllegalAccessException e) { + warningCollector.add(new ObjectInterpolationWarning( + "Failed to interpolate field. Skipping.", + basePath + "." + field.getName(), + e)); } - } - finally - { - field.setAccessible( isAccessible ); + } finally { + field.setAccessible(isAccessible); } } } } - traverseObjectWithParents( cls.getSuperclass(), target ); + traverseObjectWithParents(cls.getSuperclass(), target); } } - private void interpolateObject( Object obj, String basePath, Field field ) - throws IllegalAccessException, InterpolationException - { - Object value = field.get( obj ); - if ( value != null ) - { - if ( field.getType().isArray() ) - { - evaluateArray( value, basePath + "." + field.getName() ); - } - else - { - interpolationTargets.add( new InterpolationTarget( value, basePath + "." + field.getName() ) ); + private void interpolateObject(Object obj, String basePath, Field field) + throws IllegalAccessException, InterpolationException { + Object value = field.get(obj); + if (value != null) { + if (field.getType().isArray()) { + evaluateArray(value, basePath + "." + field.getName()); + } else { + interpolationTargets.add(new InterpolationTarget(value, basePath + "." + field.getName())); } } } - private void interpolateMap( Object obj, String basePath, Field field ) - throws IllegalAccessException, InterpolationException - { - Map m = (Map) field.get( obj ); - if ( m != null && !m.isEmpty() ) - { - for ( Object o : m.entrySet() ) - { + private void interpolateMap(Object obj, String basePath, Field field) + throws IllegalAccessException, InterpolationException { + Map m = (Map) field.get(obj); + if (m != null && !m.isEmpty()) { + for (Object o : m.entrySet()) { Map.Entry entry = (Map.Entry) o; Object value = entry.getValue(); - if ( value != null ) - { - if ( String.class == value.getClass() ) - { - String interpolated = interpolator.interpolate( (String) value, recursionInterceptor ); - - if ( !interpolated.equals( value ) ) - { - try - { - entry.setValue( interpolated ); - } - catch ( UnsupportedOperationException e ) - { - warningCollector.add( new ObjectInterpolationWarning( - "Field is an unmodifiable collection. Skipping interpolation.", - basePath + "." + field.getName(), e ) ); + if (value != null) { + if (String.class == value.getClass()) { + String interpolated = interpolator.interpolate((String) value, recursionInterceptor); + + if (!interpolated.equals(value)) { + try { + entry.setValue(interpolated); + } catch (UnsupportedOperationException e) { + warningCollector.add(new ObjectInterpolationWarning( + "Field is an unmodifiable collection. Skipping interpolation.", + basePath + "." + field.getName(), + e)); continue; } } - } - else - { - if ( value.getClass().isArray() ) - { - evaluateArray( value, basePath + "." + field.getName() ); - } - else - { + } else { + if (value.getClass().isArray()) { + evaluateArray(value, basePath + "." + field.getName()); + } else { interpolationTargets.add( - new InterpolationTarget( value, basePath + "." + field.getName() ) ); + new InterpolationTarget(value, basePath + "." + field.getName())); } } } @@ -378,77 +324,56 @@ private void interpolateMap( Object obj, String basePath, Field field ) } } - private boolean interpolateCollection( Object obj, String basePath, Field field ) - throws IllegalAccessException, InterpolationException - { - Collection c = (Collection) field.get( obj ); - if ( c != null && !c.isEmpty() ) - { - List originalValues = new ArrayList( c ); - try - { + private boolean interpolateCollection(Object obj, String basePath, Field field) + throws IllegalAccessException, InterpolationException { + Collection c = (Collection) field.get(obj); + if (c != null && !c.isEmpty()) { + List originalValues = new ArrayList(c); + try { c.clear(); - } - catch ( UnsupportedOperationException e ) - { - warningCollector.add( - new ObjectInterpolationWarning( "Field is an unmodifiable collection. Skipping interpolation.", - basePath + "." + field.getName(), e ) ); + } catch (UnsupportedOperationException e) { + warningCollector.add(new ObjectInterpolationWarning( + "Field is an unmodifiable collection. Skipping interpolation.", + basePath + "." + field.getName(), + e)); return true; } - for ( Object value : originalValues ) - { - if ( value != null ) - { - if ( String.class == value.getClass() ) - { - String interpolated = interpolator.interpolate( (String) value, recursionInterceptor ); - - if ( !interpolated.equals( value ) ) - { - c.add( interpolated ); - } - else - { - c.add( value ); - } - } - else - { - c.add( value ); - if ( value.getClass().isArray() ) - { - evaluateArray( value, basePath + "." + field.getName() ); + for (Object value : originalValues) { + if (value != null) { + if (String.class == value.getClass()) { + String interpolated = interpolator.interpolate((String) value, recursionInterceptor); + + if (!interpolated.equals(value)) { + c.add(interpolated); + } else { + c.add(value); } - else - { + } else { + c.add(value); + if (value.getClass().isArray()) { + evaluateArray(value, basePath + "." + field.getName()); + } else { interpolationTargets.add( - new InterpolationTarget( value, basePath + "." + field.getName() ) ); + new InterpolationTarget(value, basePath + "." + field.getName())); } } - } - else - { + } else { // add the null back in...not sure what else to do... - c.add( value ); + c.add(value); } } } return false; } - private void interpolateString( Object obj, Field field ) - throws IllegalAccessException, InterpolationException - { - String value = (String) field.get( obj ); - if ( value != null ) - { - String interpolated = interpolator.interpolate( value, recursionInterceptor ); - - if ( !interpolated.equals( value ) ) - { - field.set( obj, interpolated ); + private void interpolateString(Object obj, Field field) throws IllegalAccessException, InterpolationException { + String value = (String) field.get(obj); + if (value != null) { + String interpolated = interpolator.interpolate(value, recursionInterceptor); + + if (!interpolated.equals(value)) { + field.set(obj, interpolated); } } } @@ -457,13 +382,10 @@ private void interpolateString( Object obj, Field field ) * Using the package-prefix blacklist, determine whether the given class is qualified for interpolation, or * whether it should be ignored. */ - private boolean isQualifiedForInterpolation( Class cls ) - { + private boolean isQualifiedForInterpolation(Class cls) { String pkgName = cls.getPackage().getName(); - for ( String prefix : blacklistedPackagePrefixes ) - { - if ( pkgName.startsWith( prefix ) ) - { + for (String prefix : blacklistedPackagePrefixes) { + if (pkgName.startsWith(prefix)) { return false; } } @@ -477,61 +399,47 @@ private boolean isQualifiedForInterpolation( Class cls ) * The primitive-field cache is used to improve the performance of the reflective operations in this method, * since this method is a hotspot. */ - private boolean isQualifiedForInterpolation( Field field, Class fieldType ) - { - if ( !fieldIsPrimitiveByClass.containsKey( fieldType ) ) - { - fieldIsPrimitiveByClass.put( fieldType, fieldType.isPrimitive() ); + private boolean isQualifiedForInterpolation(Field field, Class fieldType) { + if (!fieldIsPrimitiveByClass.containsKey(fieldType)) { + fieldIsPrimitiveByClass.put(fieldType, fieldType.isPrimitive()); } //noinspection UnnecessaryUnboxing - if ( fieldIsPrimitiveByClass.get( fieldType ) ) - { + if (fieldIsPrimitiveByClass.get(fieldType)) { return false; } - return !blacklistedFieldNames.contains( field.getName() ); - + return !blacklistedFieldNames.contains(field.getName()); } /** * Traverse the elements of an array, and interpolate any qualified objects or add them to the traversal queue. */ - private void evaluateArray( Object target, String basePath ) - throws InterpolationException - { - int len = Array.getLength( target ); - for ( int i = 0; i < len; i++ ) - { - Object value = Array.get( target, i ); - if ( value != null ) - { - if ( String.class == value.getClass() ) - { - String interpolated = interpolator.interpolate( (String) value, recursionInterceptor ); - - if ( !interpolated.equals( value ) ) - { - Array.set( target, i, interpolated ); + private void evaluateArray(Object target, String basePath) throws InterpolationException { + int len = Array.getLength(target); + for (int i = 0; i < len; i++) { + Object value = Array.get(target, i); + if (value != null) { + if (String.class == value.getClass()) { + String interpolated = interpolator.interpolate((String) value, recursionInterceptor); + + if (!interpolated.equals(value)) { + Array.set(target, i, interpolated); } - } - else - { - interpolationTargets.add( new InterpolationTarget( value, basePath + "[" + i + "]" ) ); + } else { + interpolationTargets.add(new InterpolationTarget(value, basePath + "[" + i + "]")); } } } } } - private static final class InterpolationTarget - { + private static final class InterpolationTarget { private Object value; private String path; - private InterpolationTarget( Object value, String path ) - { + private InterpolationTarget(Object value, String path) { this.value = value; this.path = path; } diff --git a/src/main/java/org/codehaus/plexus/interpolation/object/ObjectInterpolationWarning.java b/src/main/java/org/codehaus/plexus/interpolation/object/ObjectInterpolationWarning.java index 74b358c..02fd25c 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/object/ObjectInterpolationWarning.java +++ b/src/main/java/org/codehaus/plexus/interpolation/object/ObjectInterpolationWarning.java @@ -25,63 +25,52 @@ * thrown. Each warning contains the path through the object graph from the point * of entry to the place where the warning occurred, along with a message containing * the actual warning and possibly a {@link Throwable} cause. - * + * * @author jdcasey */ -public class ObjectInterpolationWarning -{ - +public class ObjectInterpolationWarning { + private final String message; private Throwable cause; private final String path; - public ObjectInterpolationWarning( String path, String message ) - { + public ObjectInterpolationWarning(String path, String message) { this.path = path; this.message = message; } - public ObjectInterpolationWarning( String path, String message, Throwable cause ) - { + public ObjectInterpolationWarning(String path, String message, Throwable cause) { this.path = path; this.message = message; this.cause = cause; } - - public String getPath() - { + + public String getPath() { return path; } - public String getMessage() - { + public String getMessage() { return message; } - public Throwable getCause() - { + public Throwable getCause() { return cause; } - - public String toString() - { - if ( cause == null ) - { + + public String toString() { + if (cause == null) { return path + ": " + message; - } - else - { + } else { StringWriter w = new StringWriter(); - PrintWriter pw = new PrintWriter( w ); - - pw.print( path ); - pw.print( ": " ); - pw.println( message ); - pw.println( "Cause: " ); - cause.printStackTrace( pw ); - + PrintWriter pw = new PrintWriter(w); + + pw.print(path); + pw.print(": "); + pw.println(message); + pw.println("Cause: "); + cause.printStackTrace(pw); + return w.toString(); } } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/object/ObjectInterpolator.java b/src/main/java/org/codehaus/plexus/interpolation/object/ObjectInterpolator.java index 188fe99..e258353 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/object/ObjectInterpolator.java +++ b/src/main/java/org/codehaus/plexus/interpolation/object/ObjectInterpolator.java @@ -25,47 +25,44 @@ /** * Traverses an object graph and uses an {@link Interpolator} instance to resolve any String values in the - * graph. - * + * graph. + * * @author jdcasey */ -public interface ObjectInterpolator -{ - +public interface ObjectInterpolator { + /** - * Traverse the object graph from the given starting point and interpolate + * Traverse the object graph from the given starting point and interpolate * any Strings found in that graph using the given {@link Interpolator}. - * + * * @param target The starting point of the object graph to traverse * @param interpolator The {@link Interpolator} used to resolve any Strings encountered during traversal. * @throws InterpolationException in case of an error. */ - void interpolate( Object target, BasicInterpolator interpolator ) - throws InterpolationException; - + void interpolate(Object target, BasicInterpolator interpolator) throws InterpolationException; + /** - * Traverse the object graph from the given starting point and interpolate + * Traverse the object graph from the given starting point and interpolate * any Strings found in that graph using the given {@link Interpolator}. - * + * * @param target The starting point of the object graph to traverse * @param interpolator The {@link Interpolator} used to resolve any Strings encountered during traversal. * @param recursionInterceptor The {@link RecursionInterceptor} used to detect cyclical expressions in the graph * @throws InterpolationException in case of an error. */ - void interpolate( Object target, BasicInterpolator interpolator, RecursionInterceptor recursionInterceptor ) - throws InterpolationException; + void interpolate(Object target, BasicInterpolator interpolator, RecursionInterceptor recursionInterceptor) + throws InterpolationException; /** * Returns true if the last interpolation execution generated warnings. * @return true/false. */ boolean hasWarnings(); - + /** * Retrieve the {@link List} of warnings ({@link ObjectInterpolationWarning} * instances) generated during the last interpolation execution. * @return The list of warnings. */ List getWarnings(); - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/os/OperatingSystemUtils.java b/src/main/java/org/codehaus/plexus/interpolation/os/OperatingSystemUtils.java index d0a49df..0138753 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/os/OperatingSystemUtils.java +++ b/src/main/java/org/codehaus/plexus/interpolation/os/OperatingSystemUtils.java @@ -32,22 +32,17 @@ /** * NOTE: This class was copied from plexus-utils, to allow this library * to stand completely self-contained. - * + * * @author Trygve Laugstøl */ -public final class OperatingSystemUtils -{ +public final class OperatingSystemUtils { private static EnvVarSource envVarSource = new DefaultEnvVarSource(); - private OperatingSystemUtils() - { - } + private OperatingSystemUtils() {} - public static Properties getSystemEnvVars() - throws IOException - { - return getSystemEnvVars( true ); + public static Properties getSystemEnvVars() throws IOException { + return getSystemEnvVars(true); } /** @@ -58,43 +53,36 @@ public static Properties getSystemEnvVars() * @return Properties object of (possibly modified) envar keys mapped to their values. * @throws IOException in case of an error. */ - - public static Properties getSystemEnvVars( boolean caseSensitive ) - throws IOException - { + public static Properties getSystemEnvVars(boolean caseSensitive) throws IOException { Properties envVars = new Properties(); Map envs = envVarSource.getEnvMap(); - for ( String key : envs.keySet() ) - { - String value = envs.get( key ); - if ( !caseSensitive ) - { - key = key.toUpperCase( Locale.ENGLISH ); + for (String key : envs.keySet()) { + String value = envs.get(key); + if (!caseSensitive) { + key = key.toUpperCase(Locale.ENGLISH); } - envVars.put( key, value ); + envVars.put(key, value); } return envVars; } /** * Set the source object to load the environment variables from. - * Default implementation should suffice. This is mostly for testing. + * Default implementation should suffice. This is mostly for testing. * @param source the EnvVarSource instance that loads the environment variables. - * + * * @since 3.1.2 */ - public static void setEnvVarSource( EnvVarSource source ) - { + public static void setEnvVarSource(EnvVarSource source) { envVarSource = source; } /** * Defines the functionality to load a Map of environment variables. - * + * * @since 3.1.2 */ - public interface EnvVarSource - { + public interface EnvVarSource { public Map getEnvMap(); } @@ -103,14 +91,10 @@ public interface EnvVarSource * * @since 3.1.2 */ - public static class DefaultEnvVarSource - implements EnvVarSource - { + public static class DefaultEnvVarSource implements EnvVarSource { - public Map getEnvMap() - { + public Map getEnvMap() { return System.getenv(); } - } } diff --git a/src/main/java/org/codehaus/plexus/interpolation/os/Os.java b/src/main/java/org/codehaus/plexus/interpolation/os/Os.java index 529d401..8ca85f6 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/os/Os.java +++ b/src/main/java/org/codehaus/plexus/interpolation/os/Os.java @@ -68,8 +68,7 @@ * @author Brian Fox * @since 1.0 */ -public class Os -{ +public class Os { // define the families for easier reference public static final String FAMILY_DOS = "dos"; @@ -97,13 +96,13 @@ public class Os private static final Set validFamilies = setValidFamilies(); // get the current info - private static final String PATH_SEP = System.getProperty( "path.separator" ); + private static final String PATH_SEP = System.getProperty("path.separator"); - public static final String OS_NAME = System.getProperty( "os.name" ).toLowerCase( Locale.US ); + public static final String OS_NAME = System.getProperty("os.name").toLowerCase(Locale.US); - public static final String OS_ARCH = System.getProperty( "os.arch" ).toLowerCase( Locale.US ); + public static final String OS_ARCH = System.getProperty("os.arch").toLowerCase(Locale.US); - public static final String OS_VERSION = System.getProperty( "os.version" ).toLowerCase( Locale.US ); + public static final String OS_VERSION = System.getProperty("os.version").toLowerCase(Locale.US); // Make sure this method is called after static fields it depends on have been set! public static final String OS_FAMILY = getOsFamily(); @@ -119,37 +118,33 @@ public class Os /** * Default constructor */ - public Os() - { - } + public Os() {} /** * Constructor that sets the family attribute * * @param family a String value */ - public Os( String family ) - { - setFamily( family ); + public Os(String family) { + setFamily(family); } /** * Initializes the set of valid families. */ - private static Set setValidFamilies() - { + private static Set setValidFamilies() { Set valid = new HashSet(); - valid.add( FAMILY_DOS ); - valid.add( FAMILY_MAC ); - valid.add( FAMILY_NETWARE ); - valid.add( FAMILY_OS2 ); - valid.add( FAMILY_TANDEM ); - valid.add( FAMILY_UNIX ); - valid.add( FAMILY_WINDOWS ); - valid.add( FAMILY_WIN9X ); - valid.add( FAMILY_ZOS ); - valid.add( FAMILY_OS400 ); - valid.add( FAMILY_OPENVMS ); + valid.add(FAMILY_DOS); + valid.add(FAMILY_MAC); + valid.add(FAMILY_NETWARE); + valid.add(FAMILY_OS2); + valid.add(FAMILY_TANDEM); + valid.add(FAMILY_UNIX); + valid.add(FAMILY_WINDOWS); + valid.add(FAMILY_WIN9X); + valid.add(FAMILY_ZOS); + valid.add(FAMILY_OS400); + valid.add(FAMILY_OPENVMS); return valid; } @@ -173,9 +168,8 @@ private static Set setValidFamilies() *
  • openvms
  • * */ - public void setFamily( String f ) - { - family = f.toLowerCase( Locale.US ); + public void setFamily(String f) { + family = f.toLowerCase(Locale.US); } /** @@ -183,9 +177,8 @@ public void setFamily( String f ) * * @param name The OS name */ - public void setName( String name ) - { - this.name = name.toLowerCase( Locale.US ); + public void setName(String name) { + this.name = name.toLowerCase(Locale.US); } /** @@ -193,9 +186,8 @@ public void setName( String name ) * * @param arch The OS architecture */ - public void setArch( String arch ) - { - this.arch = arch.toLowerCase( Locale.US ); + public void setArch(String arch) { + this.arch = arch.toLowerCase(Locale.US); } /** @@ -203,9 +195,8 @@ public void setArch( String arch ) * * @param version The OS version */ - public void setVersion( String version ) - { - this.version = version.toLowerCase( Locale.US ); + public void setVersion(String version) { + this.version = version.toLowerCase(Locale.US); } /** @@ -216,10 +207,8 @@ public void setVersion( String version ) * @return true/false. * @throws Exception in case of an error. */ - public boolean eval() - throws Exception - { - return isOs( family, name, arch, version ); + public boolean eval() throws Exception { + return isOs(family, name, arch, version); } /** @@ -230,9 +219,8 @@ public boolean eval() * @return true if the OS matches * @since 1.0 */ - public static boolean isFamily( String family ) - { - return isOs( family, null, null, null ); + public static boolean isFamily(String family) { + return isOs(family, null, null, null); } /** @@ -243,9 +231,8 @@ public static boolean isFamily( String family ) * @return true if the OS matches * @since 1.0 */ - public static boolean isName( String name ) - { - return isOs( null, name, null, null ); + public static boolean isName(String name) { + return isOs(null, name, null, null); } /** @@ -256,9 +243,8 @@ public static boolean isName( String name ) * @return true if the OS matches * @since 1.0 */ - public static boolean isArch( String arch ) - { - return isOs( null, null, arch, null ); + public static boolean isArch(String arch) { + return isOs(null, null, arch, null); } /** @@ -269,9 +255,8 @@ public static boolean isArch( String arch ) * @return true if the OS matches * @since 1.0 */ - public static boolean isVersion( String version ) - { - return isOs( null, null, null, version ); + public static boolean isVersion(String version) { + return isOs(null, null, null, version); } /** @@ -289,83 +274,57 @@ public static boolean isVersion( String version ) * @return true if the OS matches * @since 1.0 */ - public static boolean isOs( String family, String name, String arch, String version ) - { + public static boolean isOs(String family, String name, String arch, String version) { boolean retValue = false; - if ( family != null || name != null || arch != null || version != null ) - { + if (family != null || name != null || arch != null || version != null) { boolean isFamily = true; boolean isName = true; boolean isArch = true; boolean isVersion = true; - if ( family != null ) - { - if ( family.equalsIgnoreCase( FAMILY_WINDOWS ) ) - { - isFamily = OS_NAME.contains( FAMILY_WINDOWS ); - } - else if ( family.equalsIgnoreCase( FAMILY_OS2 ) ) - { - isFamily = OS_NAME.contains( FAMILY_OS2 ); - } - else if ( family.equalsIgnoreCase( FAMILY_NETWARE ) ) - { - isFamily = OS_NAME.contains( FAMILY_NETWARE ); - } - else if ( family.equalsIgnoreCase( FAMILY_DOS ) ) - { - isFamily = PATH_SEP.equals( ";" ) && !isFamily( FAMILY_NETWARE ); - } - else if ( family.equalsIgnoreCase( FAMILY_MAC ) ) - { - isFamily = OS_NAME.contains( FAMILY_MAC ); - } - else if ( family.equalsIgnoreCase( FAMILY_TANDEM ) ) - { - isFamily = OS_NAME.contains( "nonstop_kernel" ); - } - else if ( family.equalsIgnoreCase( FAMILY_UNIX ) ) - { - isFamily = PATH_SEP.equals( ":" ) && !isFamily( FAMILY_OPENVMS ) - && ( !isFamily( FAMILY_MAC ) || OS_NAME.endsWith( "x" ) ); - } - else if ( family.equalsIgnoreCase( FAMILY_WIN9X ) ) - { - isFamily = isFamily( FAMILY_WINDOWS ) - && ( OS_NAME.contains( "95" ) || OS_NAME.contains( "98" ) - || OS_NAME.contains( "me" ) || OS_NAME.contains( "ce" ) ); - } - else if ( family.equalsIgnoreCase( FAMILY_ZOS ) ) - { - isFamily = OS_NAME.contains( FAMILY_ZOS ) || OS_NAME.contains( "os/390" ); - } - else if ( family.equalsIgnoreCase( FAMILY_OS400 ) ) - { - isFamily = OS_NAME.contains( FAMILY_OS400 ); - } - else if ( family.equalsIgnoreCase( FAMILY_OPENVMS ) ) - { - isFamily = OS_NAME.contains( FAMILY_OPENVMS ); - } - else - { - isFamily = OS_NAME.contains( family.toLowerCase( Locale.US ) ); + if (family != null) { + if (family.equalsIgnoreCase(FAMILY_WINDOWS)) { + isFamily = OS_NAME.contains(FAMILY_WINDOWS); + } else if (family.equalsIgnoreCase(FAMILY_OS2)) { + isFamily = OS_NAME.contains(FAMILY_OS2); + } else if (family.equalsIgnoreCase(FAMILY_NETWARE)) { + isFamily = OS_NAME.contains(FAMILY_NETWARE); + } else if (family.equalsIgnoreCase(FAMILY_DOS)) { + isFamily = PATH_SEP.equals(";") && !isFamily(FAMILY_NETWARE); + } else if (family.equalsIgnoreCase(FAMILY_MAC)) { + isFamily = OS_NAME.contains(FAMILY_MAC); + } else if (family.equalsIgnoreCase(FAMILY_TANDEM)) { + isFamily = OS_NAME.contains("nonstop_kernel"); + } else if (family.equalsIgnoreCase(FAMILY_UNIX)) { + isFamily = PATH_SEP.equals(":") + && !isFamily(FAMILY_OPENVMS) + && (!isFamily(FAMILY_MAC) || OS_NAME.endsWith("x")); + } else if (family.equalsIgnoreCase(FAMILY_WIN9X)) { + isFamily = isFamily(FAMILY_WINDOWS) + && (OS_NAME.contains("95") + || OS_NAME.contains("98") + || OS_NAME.contains("me") + || OS_NAME.contains("ce")); + } else if (family.equalsIgnoreCase(FAMILY_ZOS)) { + isFamily = OS_NAME.contains(FAMILY_ZOS) || OS_NAME.contains("os/390"); + } else if (family.equalsIgnoreCase(FAMILY_OS400)) { + isFamily = OS_NAME.contains(FAMILY_OS400); + } else if (family.equalsIgnoreCase(FAMILY_OPENVMS)) { + isFamily = OS_NAME.contains(FAMILY_OPENVMS); + } else { + isFamily = OS_NAME.contains(family.toLowerCase(Locale.US)); } } - if ( name != null ) - { - isName = name.toLowerCase( Locale.US ).equals( OS_NAME ); + if (name != null) { + isName = name.toLowerCase(Locale.US).equals(OS_NAME); } - if ( arch != null ) - { - isArch = arch.toLowerCase( Locale.US ).equals( OS_ARCH ); + if (arch != null) { + isArch = arch.toLowerCase(Locale.US).equals(OS_ARCH); } - if ( version != null ) - { - isVersion = version.toLowerCase( Locale.US ).equals( OS_VERSION ); + if (version != null) { + isVersion = version.toLowerCase(Locale.US).equals(OS_VERSION); } retValue = isFamily && isName && isArch && isVersion; } @@ -378,24 +337,18 @@ else if ( family.equalsIgnoreCase( FAMILY_OPENVMS ) ) * @return name of current OS family. * @since 1.4.2 */ - private static String getOsFamily() - { + private static String getOsFamily() { // in case the order of static initialization is // wrong, get the list // safely. Set families = null; - if ( !validFamilies.isEmpty() ) - { + if (!validFamilies.isEmpty()) { families = validFamilies; - } - else - { + } else { families = setValidFamilies(); } - for ( String fam : families ) - { - if ( Os.isFamily( fam ) ) - { + for (String fam : families) { + if (Os.isFamily(fam)) { return fam; } } @@ -423,17 +376,15 @@ private static String getOsFamily() * @return true if one of the valid families. * @since 1.4.2 */ - public static boolean isValidFamily( String theFamily ) - { - return ( validFamilies.contains( theFamily ) ); + public static boolean isValidFamily(String theFamily) { + return (validFamilies.contains(theFamily)); } /** * @return a copy of the valid families * @since 1.4.2 */ - public static Set getValidFamilies() - { - return new HashSet( validFamilies ); + public static Set getValidFamilies() { + return new HashSet(validFamilies); } } diff --git a/src/main/java/org/codehaus/plexus/interpolation/reflection/ClassMap.java b/src/main/java/org/codehaus/plexus/interpolation/reflection/ClassMap.java index afb029f..0a50d3d 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/reflection/ClassMap.java +++ b/src/main/java/org/codehaus/plexus/interpolation/reflection/ClassMap.java @@ -34,11 +34,8 @@ * @author Attila Szegedi * @author Geir Magnusson Jr. */ -public class ClassMap -{ - private static final class CacheMiss - { - } +public class ClassMap { + private static final class CacheMiss {} private static final CacheMiss CACHE_MISS = new CacheMiss(); private static final Object OBJECT = new Object(); @@ -61,8 +58,7 @@ private static final class CacheMiss * Standard constructor * @param clazz The class to be analyzed. */ - public ClassMap( Class clazz ) - { + public ClassMap(Class clazz) { this.clazz = clazz; populateMethodCache(); } @@ -70,8 +66,7 @@ public ClassMap( Class clazz ) /** * @return the class object whose methods are cached by this map. */ - Class getCachedClass() - { + Class getCachedClass() { return clazz; } @@ -89,41 +84,31 @@ Class getCachedClass() * @return {@link Method}. * @throws MethodMap.AmbiguousException in case of an error. */ - public Method findMethod( String name, Object[] params ) - throws MethodMap.AmbiguousException - { - String methodKey = makeMethodKey( name, params ); - Object cacheEntry = methodCache.get( methodKey ); - - if ( cacheEntry == CACHE_MISS ) - { + public Method findMethod(String name, Object[] params) throws MethodMap.AmbiguousException { + String methodKey = makeMethodKey(name, params); + Object cacheEntry = methodCache.get(methodKey); + + if (cacheEntry == CACHE_MISS) { return null; } - if ( cacheEntry == null ) - { - try - { - cacheEntry = methodMap.find( name, params ); - } - catch ( MethodMap.AmbiguousException ae ) - { + if (cacheEntry == null) { + try { + cacheEntry = methodMap.find(name, params); + } catch (MethodMap.AmbiguousException ae) { /* * that's a miss :) */ - methodCache.put( methodKey, CACHE_MISS ); + methodCache.put(methodKey, CACHE_MISS); throw ae; } - if ( cacheEntry == null ) - { - methodCache.put( methodKey, CACHE_MISS ); - } - else - { - methodCache.put( methodKey, cacheEntry ); + if (cacheEntry == null) { + methodCache.put(methodKey, CACHE_MISS); + } else { + methodCache.put(methodKey, cacheEntry); } } @@ -137,27 +122,25 @@ public Method findMethod( String name, Object[] params ) * are taken from all the public methods * that our class provides. */ - private void populateMethodCache() - { + private void populateMethodCache() { /* * get all publicly accessible methods */ - Method[] methods = getAccessibleMethods( clazz ); + Method[] methods = getAccessibleMethods(clazz); /* * map and cache them */ - for ( Method method : methods ) - { + for (Method method : methods) { /* * now get the 'public method', the method declared by a * public interface or class. (because the actual implementing * class may be a facade... */ - Method publicMethod = getPublicMethod( method ); + Method publicMethod = getPublicMethod(method); /* * it is entirely possible that there is no public method for @@ -166,10 +149,9 @@ private void populateMethodCache() * in which case, ignore it. Otherwise, map and cache */ - if ( publicMethod != null ) - { - methodMap.add( publicMethod ); - methodCache.put( makeMethodKey( publicMethod ), publicMethod ); + if (publicMethod != null) { + methodMap.add(publicMethod); + methodCache.put(makeMethodKey(publicMethod), publicMethod); } } } @@ -179,81 +161,57 @@ private void populateMethodCache() * the concatenation of the name and the * types of the method parameters. */ - private String makeMethodKey( Method method ) - { + private String makeMethodKey(Method method) { Class[] parameterTypes = method.getParameterTypes(); - StringBuilder methodKey = new StringBuilder( method.getName() ); + StringBuilder methodKey = new StringBuilder(method.getName()); - for ( Class parameterType : parameterTypes ) - { + for (Class parameterType : parameterTypes) { /* * If the argument type is primitive then we want * to convert our primitive type signature to the * corresponding Object type so introspection for * methods with primitive types will work correctly. */ - if ( parameterType.isPrimitive() ) - { - if ( parameterType.equals( Boolean.TYPE ) ) - { - methodKey.append( "java.lang.Boolean" ); - } - else if ( parameterType.equals( Byte.TYPE ) ) - { - methodKey.append( "java.lang.Byte" ); - } - else if ( parameterType.equals( Character.TYPE ) ) - { - methodKey.append( "java.lang.Character" ); - } - else if ( parameterType.equals( Double.TYPE ) ) - { - methodKey.append( "java.lang.Double" ); - } - else if ( parameterType.equals( Float.TYPE ) ) - { - methodKey.append( "java.lang.Float" ); + if (parameterType.isPrimitive()) { + if (parameterType.equals(Boolean.TYPE)) { + methodKey.append("java.lang.Boolean"); + } else if (parameterType.equals(Byte.TYPE)) { + methodKey.append("java.lang.Byte"); + } else if (parameterType.equals(Character.TYPE)) { + methodKey.append("java.lang.Character"); + } else if (parameterType.equals(Double.TYPE)) { + methodKey.append("java.lang.Double"); + } else if (parameterType.equals(Float.TYPE)) { + methodKey.append("java.lang.Float"); + } else if (parameterType.equals(Integer.TYPE)) { + methodKey.append("java.lang.Integer"); + } else if (parameterType.equals(Long.TYPE)) { + methodKey.append("java.lang.Long"); + } else if (parameterType.equals(Short.TYPE)) { + methodKey.append("java.lang.Short"); } - else if ( parameterType.equals( Integer.TYPE ) ) - { - methodKey.append( "java.lang.Integer" ); - } - else if ( parameterType.equals( Long.TYPE ) ) - { - methodKey.append( "java.lang.Long" ); - } - else if ( parameterType.equals( Short.TYPE ) ) - { - methodKey.append( "java.lang.Short" ); - } - } - else - { - methodKey.append( parameterType.getName() ); + } else { + methodKey.append(parameterType.getName()); } } return methodKey.toString(); } - private static String makeMethodKey( String method, Object[] params ) - { - if (params.length == 0) - { + private static String makeMethodKey(String method, Object[] params) { + if (params.length == 0) { return method; } - StringBuilder methodKey = new StringBuilder().append( method ); + StringBuilder methodKey = new StringBuilder().append(method); - for ( Object arg : params ) - { - if ( arg == null ) - { + for (Object arg : params) { + if (arg == null) { arg = OBJECT; } - methodKey.append( arg.getClass().getName() ); + methodKey.append(arg.getClass().getName()); } return methodKey.toString(); @@ -265,8 +223,7 @@ private static String makeMethodKey( String method, Object[] params ) * from public superclasses and interfaces (if they exist). Basically * upcasts every method to the nearest acccessible method. */ - private static Method[] getAccessibleMethods( Class clazz ) - { + private static Method[] getAccessibleMethods(Class clazz) { Method[] methods = clazz.getMethods(); /* @@ -274,8 +231,7 @@ private static Method[] getAccessibleMethods( Class clazz ) * clazz is public */ - if ( Modifier.isPublic( clazz.getModifiers() ) ) - { + if (Modifier.isPublic(clazz.getModifiers())) { return methods; } @@ -285,27 +241,23 @@ private static Method[] getAccessibleMethods( Class clazz ) MethodInfo[] methodInfos = new MethodInfo[methods.length]; - for ( int i = methods.length; i-- > 0; ) - { - methodInfos[i] = new MethodInfo( methods[i] ); + for (int i = methods.length; i-- > 0; ) { + methodInfos[i] = new MethodInfo(methods[i]); } - int upcastCount = getAccessibleMethods( clazz, methodInfos, 0 ); + int upcastCount = getAccessibleMethods(clazz, methodInfos, 0); /* * Reallocate array in case some method had no accessible counterpart. */ - if ( upcastCount < methods.length ) - { + if (upcastCount < methods.length) { methods = new Method[upcastCount]; } int j = 0; - for ( MethodInfo methodInfo : methodInfos ) - { - if ( methodInfo.upcast ) - { + for (MethodInfo methodInfo : methodInfos) { + if (methodInfo.upcast) { methods[j++] = methodInfo.method; } } @@ -321,8 +273,7 @@ private static Method[] getAccessibleMethods( Class clazz ) * @param upcastCount current number of methods we have matched * @return count of matched methods */ - private static int getAccessibleMethods( Class clazz, MethodInfo[] methodInfos, int upcastCount ) - { + private static int getAccessibleMethods(Class clazz, MethodInfo[] methodInfos, int upcastCount) { int l = methodInfos.length; /* @@ -330,22 +281,16 @@ private static int getAccessibleMethods( Class clazz, MethodInfo[] methodInfo * 'non-upcasted' methods to see if we have a match */ - if ( Modifier.isPublic( clazz.getModifiers() ) ) - { - for ( int i = 0; i < l && upcastCount < l; ++i ) - { - try - { + if (Modifier.isPublic(clazz.getModifiers())) { + for (int i = 0; i < l && upcastCount < l; ++i) { + try { MethodInfo methodInfo = methodInfos[i]; - if ( !methodInfo.upcast ) - { - methodInfo.tryUpcasting( clazz ); + if (!methodInfo.upcast) { + methodInfo.tryUpcasting(clazz); upcastCount++; } - } - catch ( NoSuchMethodException e ) - { + } catch (NoSuchMethodException e) { /* * Intentionally ignored - it means * it wasn't found in the current class @@ -357,8 +302,7 @@ private static int getAccessibleMethods( Class clazz, MethodInfo[] methodInfo * Short circuit if all methods were upcast */ - if ( upcastCount == l ) - { + if (upcastCount == l) { return upcastCount; } } @@ -369,16 +313,14 @@ private static int getAccessibleMethods( Class clazz, MethodInfo[] methodInfo Class superclazz = clazz.getSuperclass(); - if ( superclazz != null ) - { - upcastCount = getAccessibleMethods( superclazz, methodInfos, upcastCount ); + if (superclazz != null) { + upcastCount = getAccessibleMethods(superclazz, methodInfos, upcastCount); /* * Short circuit if all methods were upcast */ - if ( upcastCount == l ) - { + if (upcastCount == l) { return upcastCount; } } @@ -391,16 +333,14 @@ private static int getAccessibleMethods( Class clazz, MethodInfo[] methodInfo Class[] interfaces = clazz.getInterfaces(); - for ( int i = interfaces.length; i-- > 0; ) - { - upcastCount = getAccessibleMethods( interfaces[i], methodInfos, upcastCount ); + for (int i = interfaces.length; i-- > 0; ) { + upcastCount = getAccessibleMethods(interfaces[i], methodInfos, upcastCount); /* * Short circuit if all methods were upcast */ - if ( upcastCount == l ) - { + if (upcastCount == l) { return upcastCount; } } @@ -419,8 +359,7 @@ private static int getAccessibleMethods( Class clazz, MethodInfo[] methodInfo * method is itself declared by a public class, this method is an identity * function. */ - public static Method getPublicMethod( Method method ) - { + public static Method getPublicMethod(Method method) { Class clazz = method.getDeclaringClass(); /* @@ -428,12 +367,11 @@ public static Method getPublicMethod( Method method ) * class is public. */ - if ( ( clazz.getModifiers() & Modifier.PUBLIC ) != 0 ) - { + if ((clazz.getModifiers() & Modifier.PUBLIC) != 0) { return method; } - return getPublicMethod( clazz, method.getName(), method.getParameterTypes() ); + return getPublicMethod(clazz, method.getName(), method.getParameterTypes()); } /** @@ -444,20 +382,15 @@ public static Method getPublicMethod( Method method ) * @param name the name of the method * @param paramTypes the classes of method parameters */ - private static Method getPublicMethod( Class clazz, String name, Class[] paramTypes ) - { + private static Method getPublicMethod(Class clazz, String name, Class[] paramTypes) { /* * if this class is public, then try to get it */ - if ( ( clazz.getModifiers() & Modifier.PUBLIC ) != 0 ) - { - try - { - return clazz.getMethod( name, paramTypes ); - } - catch ( NoSuchMethodException e ) - { + if ((clazz.getModifiers() & Modifier.PUBLIC) != 0) { + try { + return clazz.getMethod(name, paramTypes); + } catch (NoSuchMethodException e) { /* * If the class does not have the method, then neither its * superclass nor any of its interfaces has it so quickly return @@ -471,15 +404,12 @@ private static Method getPublicMethod( Class clazz, String name, Class[] p * try the superclass */ - Class superclazz = clazz.getSuperclass(); - if ( superclazz != null ) - { - Method superclazzMethod = getPublicMethod( superclazz, name, paramTypes ); + if (superclazz != null) { + Method superclazzMethod = getPublicMethod(superclazz, name, paramTypes); - if ( superclazzMethod != null ) - { + if (superclazzMethod != null) { return superclazzMethod; } } @@ -488,12 +418,10 @@ private static Method getPublicMethod( Class clazz, String name, Class[] p * and interfaces */ - for ( Class interface_ : clazz.getInterfaces() ) - { - Method interfaceMethod = getPublicMethod( interface_, name, paramTypes ); + for (Class interface_ : clazz.getInterfaces()) { + Method interfaceMethod = getPublicMethod(interface_, name, paramTypes); - if ( interfaceMethod != null ) - { + if (interfaceMethod != null) { return interfaceMethod; } } @@ -504,25 +432,21 @@ private static Method getPublicMethod( Class clazz, String name, Class[] p /** * Used for the iterative discovery process for public methods. */ - private static final class MethodInfo - { + private static final class MethodInfo { Method method; String name; Class[] parameterTypes; boolean upcast; - MethodInfo( Method method ) - { + MethodInfo(Method method) { this.method = null; name = method.getName(); parameterTypes = method.getParameterTypes(); upcast = false; } - void tryUpcasting( Class clazz ) - throws NoSuchMethodException - { - method = clazz.getMethod( name, parameterTypes ); + void tryUpcasting(Class clazz) throws NoSuchMethodException { + method = clazz.getMethod(name, parameterTypes); name = null; parameterTypes = null; upcast = true; diff --git a/src/main/java/org/codehaus/plexus/interpolation/reflection/MethodMap.java b/src/main/java/org/codehaus/plexus/interpolation/reflection/MethodMap.java index d2ddd3d..2db1710 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/reflection/MethodMap.java +++ b/src/main/java/org/codehaus/plexus/interpolation/reflection/MethodMap.java @@ -34,8 +34,7 @@ * @author Geir Magnusson Jr. * @author Attila Szegedi */ -public class MethodMap -{ +public class MethodMap { private static final int MORE_SPECIFIC = 0; private static final int LESS_SPECIFIC = 1; private static final int INCOMPARABLE = 2; @@ -51,20 +50,17 @@ public class MethodMap * of all the methods with the same name. * @param method {@link Method} */ - public void add( Method method ) - { + public void add(Method method) { String methodName = method.getName(); - List l = get( methodName ); + List l = get(methodName); - if ( l == null) - { + if (l == null) { l = new ArrayList(); - methodByNameMap.put( methodName, l ); + methodByNameMap.put(methodName, l); } - l.add( method ); - + l.add(method); } /** @@ -73,9 +69,8 @@ public void add( Method method ) * @param key the key * @return list of methods */ - public List get( String key ) - { - return methodByNameMap.get( key ); + public List get(String key) { + return methodByNameMap.get(key); } /** @@ -106,21 +101,17 @@ public List get( String key ) * @throws AmbiguousException if there is more than one maximally * specific applicable method */ - public Method find( String methodName, Object[] args ) - throws AmbiguousException - { - List methodList = get( methodName ); + public Method find(String methodName, Object[] args) throws AmbiguousException { + List methodList = get(methodName); - if ( methodList == null ) - { + if (methodList == null) { return null; } int l = args.length; Class[] classes = new Class[l]; - for ( int i = 0; i < l; ++i ) - { + for (int i = 0; i < l; ++i) { Object arg = args[i]; /* @@ -130,31 +121,23 @@ public Method find( String methodName, Object[] args ) classes[i] = arg == null ? null : arg.getClass(); } - return getMostSpecific( methodList, classes ); + return getMostSpecific(methodList, classes); } /** * simple distinguishable exception, used when * we run across ambiguous overloading */ - public static class AmbiguousException - extends Exception - { - } - + public static class AmbiguousException extends Exception {} - private static Method getMostSpecific( List methods, Class[] classes ) - throws AmbiguousException - { - LinkedList applicables = getApplicables( methods, classes ); + private static Method getMostSpecific(List methods, Class[] classes) throws AmbiguousException { + LinkedList applicables = getApplicables(methods, classes); - if ( applicables.isEmpty() ) - { + if (applicables.isEmpty()) { return null; } - if ( applicables.size() == 1 ) - { + if (applicables.size() == 1) { return applicables.getFirst(); } @@ -166,19 +149,15 @@ private static Method getMostSpecific( List methods, Class[] classes LinkedList maximals = new LinkedList(); - for ( Method app : applicables ) - { + for (Method app : applicables) { Class[] appArgs = app.getParameterTypes(); boolean lessSpecific = false; - for ( Iterator maximal = maximals.iterator(); !lessSpecific && maximal.hasNext(); ) - { + for (Iterator maximal = maximals.iterator(); !lessSpecific && maximal.hasNext(); ) { Method max = maximal.next(); - switch ( moreSpecific( appArgs, max.getParameterTypes() ) ) - { - case MORE_SPECIFIC: - { + switch (moreSpecific(appArgs, max.getParameterTypes())) { + case MORE_SPECIFIC: { /* * This method is more specific than the previously * known maximally specific, so remove the old maximum. @@ -188,8 +167,7 @@ private static Method getMostSpecific( List methods, Class[] classes break; } - case LESS_SPECIFIC: - { + case LESS_SPECIFIC: { /* * This method is less specific than some of the * currently known maximally specific methods, so we @@ -203,14 +181,12 @@ private static Method getMostSpecific( List methods, Class[] classes } } - if ( !lessSpecific ) - { - maximals.addLast( app ); + if (!lessSpecific) { + maximals.addLast(app); } } - if ( maximals.size() > 1 ) - { + if (maximals.size() > 1) { // We have more than one maximally specific method throw new AmbiguousException(); } @@ -226,24 +202,19 @@ private static Method getMostSpecific( List methods, Class[] classes * @return MORE_SPECIFIC if c1 is more specific than c2, LESS_SPECIFIC if * c1 is less specific than c2, INCOMPARABLE if they are incomparable. */ - private static int moreSpecific( Class[] c1, Class[] c2 ) - { + private static int moreSpecific(Class[] c1, Class[] c2) { boolean c1MoreSpecific = false; boolean c2MoreSpecific = false; - for ( int i = 0; i < c1.length; ++i ) - { - if ( c1[i] != c2[i] ) - { - c1MoreSpecific = c1MoreSpecific || isStrictMethodInvocationConvertible( c2[i], c1[i] ); - c2MoreSpecific = c2MoreSpecific || isStrictMethodInvocationConvertible( c1[i], c2[i] ); + for (int i = 0; i < c1.length; ++i) { + if (c1[i] != c2[i]) { + c1MoreSpecific = c1MoreSpecific || isStrictMethodInvocationConvertible(c2[i], c1[i]); + c2MoreSpecific = c2MoreSpecific || isStrictMethodInvocationConvertible(c1[i], c2[i]); } } - if ( c1MoreSpecific ) - { - if ( c2MoreSpecific ) - { + if (c1MoreSpecific) { + if (c2MoreSpecific) { /* * Incomparable due to cross-assignable arguments (i.e. * foo(String, Object) vs. foo(Object, String)) @@ -255,8 +226,7 @@ private static int moreSpecific( Class[] c1, Class[] c2 ) return MORE_SPECIFIC; } - if ( c2MoreSpecific ) - { + if (c2MoreSpecific) { return LESS_SPECIFIC; } @@ -276,15 +246,12 @@ private static int moreSpecific( Class[] c1, Class[] c2 ) * formal and actual arguments matches, and argument types are assignable * to formal types through a method invocation conversion). */ - private static LinkedList getApplicables( List methods, Class[] classes ) - { + private static LinkedList getApplicables(List methods, Class[] classes) { LinkedList list = new LinkedList(); - for ( Method method : methods ) - { - if ( isApplicable( method, classes ) ) - { - list.add( method ); + for (Method method : methods) { + if (isApplicable(method, classes)) { + list.add(method); } } return list; @@ -294,19 +261,15 @@ private static LinkedList getApplicables( List methods, Class * Returns true if the supplied method is applicable to actual * argument types. */ - private static boolean isApplicable( Method method, Class[] classes ) - { + private static boolean isApplicable(Method method, Class[] classes) { Class[] methodArgs = method.getParameterTypes(); - if ( methodArgs.length != classes.length ) - { + if (methodArgs.length != classes.length) { return false; } - for ( int i = 0; i < classes.length; ++i ) - { - if ( !isMethodInvocationConvertible( methodArgs[i], classes[i] ) ) - { + for (int i = 0; i < classes.length; ++i) { + if (!isMethodInvocationConvertible(methodArgs[i], classes[i])) { return false; } } @@ -332,13 +295,11 @@ private static boolean isApplicable( Method method, Class[] classes ) * type or an object type of a primitive type that can be converted to * the formal type. */ - private static boolean isMethodInvocationConvertible( Class formal, Class actual ) - { + private static boolean isMethodInvocationConvertible(Class formal, Class actual) { /* * if it's a null, it means the arg was null */ - if ( actual == null && !formal.isPrimitive() ) - { + if (actual == null && !formal.isPrimitive()) { return true; } @@ -346,8 +307,7 @@ private static boolean isMethodInvocationConvertible( Class formal, Class * Check for identity or widening reference conversion */ - if ( actual != null && formal.isAssignableFrom( actual ) ) - { + if (actual != null && formal.isAssignableFrom(actual)) { return true; } @@ -356,41 +316,39 @@ private static boolean isMethodInvocationConvertible( Class formal, Class * actual parameters are never primitives. */ - if ( formal.isPrimitive() ) - { - if ( formal == Boolean.TYPE ) - { + if (formal.isPrimitive()) { + if (formal == Boolean.TYPE) { return actual == Boolean.class; } - if ( formal == Character.TYPE ) - { + if (formal == Character.TYPE) { return actual == Character.class; } - if ( formal == Byte.TYPE ) - { + if (formal == Byte.TYPE) { return actual == Byte.class; } - if ( formal == Short.TYPE ) - { + if (formal == Short.TYPE) { return actual == Short.class || actual == Byte.class; } - if ( formal == Integer.TYPE ) - { + if (formal == Integer.TYPE) { return actual == Integer.class || actual == Short.class || actual == Byte.class; } - if ( formal == Long.TYPE ) - { + if (formal == Long.TYPE) { return actual == Long.class || actual == Integer.class || actual == Short.class || actual == Byte.class; } - if ( formal == Float.TYPE ) - { - return actual == Float.class || actual == Long.class || actual == Integer.class - || actual == Short.class || actual == Byte.class; + if (formal == Float.TYPE) { + return actual == Float.class + || actual == Long.class + || actual == Integer.class + || actual == Short.class + || actual == Byte.class; } - if ( formal == Double.TYPE ) - { - return actual == Double.class || actual == Float.class || actual == Long.class - || actual == Integer.class || actual == Short.class || actual == Byte.class; + if (formal == Double.TYPE) { + return actual == Double.class + || actual == Float.class + || actual == Long.class + || actual == Integer.class + || actual == Short.class + || actual == Byte.class; } } @@ -411,13 +369,11 @@ private static boolean isMethodInvocationConvertible( Class formal, Class * or formal and actual are both primitive types and actual can be * subject to widening conversion to formal. */ - private static boolean isStrictMethodInvocationConvertible( Class formal, Class actual ) - { + private static boolean isStrictMethodInvocationConvertible(Class formal, Class actual) { /* * we shouldn't get a null into, but if so */ - if ( actual == null && !formal.isPrimitive() ) - { + if (actual == null && !formal.isPrimitive()) { return true; } @@ -425,8 +381,7 @@ private static boolean isStrictMethodInvocationConvertible( Class formal, Cla * Check for identity or widening reference conversion */ - if ( formal.isAssignableFrom( actual ) ) - { + if (formal.isAssignableFrom(actual)) { return true; } @@ -434,28 +389,25 @@ private static boolean isStrictMethodInvocationConvertible( Class formal, Cla * Check for widening primitive conversion. */ - if ( formal.isPrimitive() ) - { - if ( formal == Short.TYPE ) - { + if (formal.isPrimitive()) { + if (formal == Short.TYPE) { return actual == Byte.TYPE; } - if ( formal == Integer.TYPE ) - { + if (formal == Integer.TYPE) { return actual == Short.TYPE || actual == Byte.TYPE; } - if ( formal == Long.TYPE ) - { + if (formal == Long.TYPE) { return actual == Integer.TYPE || actual == Short.TYPE || actual == Byte.TYPE; } - if ( formal == Float.TYPE ) - { + if (formal == Float.TYPE) { return actual == Long.TYPE || actual == Integer.TYPE || actual == Short.TYPE || actual == Byte.TYPE; } - if ( formal == Double.TYPE ) - { - return actual == Float.TYPE || actual == Long.TYPE || actual == Integer.TYPE || actual == Short.TYPE - || actual == Byte.TYPE; + if (formal == Double.TYPE) { + return actual == Float.TYPE + || actual == Long.TYPE + || actual == Integer.TYPE + || actual == Short.TYPE + || actual == Byte.TYPE; } } return false; diff --git a/src/main/java/org/codehaus/plexus/interpolation/reflection/ReflectionValueExtractor.java b/src/main/java/org/codehaus/plexus/interpolation/reflection/ReflectionValueExtractor.java index 4213732..c9db516 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/reflection/ReflectionValueExtractor.java +++ b/src/main/java/org/codehaus/plexus/interpolation/reflection/ReflectionValueExtractor.java @@ -15,8 +15,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import org.codehaus.plexus.interpolation.util.StringUtils; - import java.lang.ref.WeakReference; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; @@ -25,6 +23,8 @@ import java.util.Map; import java.util.WeakHashMap; +import org.codehaus.plexus.interpolation.util.StringUtils; + /** * NOTE: This class was copied from plexus-utils, to allow this library to stand completely self-contained. *

    Using simple dotted expressions extract the values from a MavenProject instance, For example we might want to extract @@ -32,8 +32,7 @@ * * @author Jason van Zyl */ -public class ReflectionValueExtractor -{ +public class ReflectionValueExtractor { private static final Class[] CLASS_ARGS = new Class[0]; private static final Object[] OBJECT_ARGS = new Object[0]; @@ -43,7 +42,7 @@ public class ReflectionValueExtractor * space overflows due to retention of discarded classloaders. */ private static final Map, WeakReference> classMaps = - new WeakHashMap, WeakReference>(); + new WeakHashMap, WeakReference>(); static final int EOF = -1; @@ -57,79 +56,65 @@ public class ReflectionValueExtractor static final char MAPPED_END = ')'; - static class Tokenizer - { + static class Tokenizer { final String expression; int idx; - public Tokenizer( String expression ) - { + public Tokenizer(String expression) { this.expression = expression; } - public int peekChar() - { - return idx < expression.length() ? expression.charAt( idx ) : EOF; + public int peekChar() { + return idx < expression.length() ? expression.charAt(idx) : EOF; } - public int skipChar() - { - return idx < expression.length() ? expression.charAt( idx++ ) : EOF; + public int skipChar() { + return idx < expression.length() ? expression.charAt(idx++) : EOF; } - public String nextToken( char delimiter ) - { + public String nextToken(char delimiter) { int start = idx; - while ( idx < expression.length() && delimiter != expression.charAt( idx ) ) - { + while (idx < expression.length() && delimiter != expression.charAt(idx)) { idx++; } // delimiter MUST be present - if ( idx <= start || idx >= expression.length() ) - { + if (idx <= start || idx >= expression.length()) { return null; } - return expression.substring( start, idx++ ); + return expression.substring(start, idx++); } - public String nextPropertyName() - { + public String nextPropertyName() { final int start = idx; - while ( idx < expression.length() && Character.isJavaIdentifierPart( expression.charAt( idx ) ) ) - { + while (idx < expression.length() && Character.isJavaIdentifierPart(expression.charAt(idx))) { idx++; } // property name does not require delimiter - if ( idx <= start || idx > expression.length() ) - { + if (idx <= start || idx > expression.length()) { return null; } - return expression.substring( start, idx ); + return expression.substring(start, idx); } - public int getPosition() - { + public int getPosition() { return idx < expression.length() ? idx : EOF; } // to make tokenizer look pretty in debugger @Override - public String toString() - { - return idx < expression.length() ? expression.substring( idx ) : ""; + public String toString() { + return idx < expression.length() ? expression.substring(idx) : ""; } } - private ReflectionValueExtractor() - { - } + private ReflectionValueExtractor() {} /** *

    @@ -142,16 +127,14 @@ private ReflectionValueExtractor() *

  • mapped properties should be contains (\\w+)\\((.+)\\) pattern, i.e. * "user.addresses(myAddress).street"
  • * - * + * * @param expression not null expression * @param root not null object * @return the object defined by the expression * @throws Exception if any */ - public static Object evaluate( String expression, Object root ) - throws Exception - { - return evaluate( expression, root, true ); + public static Object evaluate(String expression, Object root) throws Exception { + return evaluate(expression, root, true); } /** @@ -165,7 +148,7 @@ public static Object evaluate( String expression, Object root ) *
  • mapped properties should be contains (\\w+)\\((.+)\\) pattern, i.e. * "user.addresses(myAddress).street"
  • * - * + * * @param expression not null expression * @param root not null object * @param trimRootToken trim the token or not. @@ -173,9 +156,7 @@ public static Object evaluate( String expression, Object root ) * @throws Exception if any */ // TODO: don't throw Exception - public static Object evaluate( String expression, final Object root, final boolean trimRootToken ) - throws Exception - { + public static Object evaluate(String expression, final Object root, final boolean trimRootToken) throws Exception { Object value = root; // ---------------------------------------------------------------------- @@ -183,45 +164,47 @@ public static Object evaluate( String expression, final Object root, final boole // MavenProject instance. // ---------------------------------------------------------------------- - if ( expression == null || "".equals( expression.trim() ) - || !Character.isJavaIdentifierStart( expression.charAt( 0 ) ) ) - { + if (expression == null + || "".equals(expression.trim()) + || !Character.isJavaIdentifierStart(expression.charAt(0))) { return null; } - boolean hasDots = expression.indexOf( PROPERTY_START ) >= 0; + boolean hasDots = expression.indexOf(PROPERTY_START) >= 0; final Tokenizer tokenizer; - if ( trimRootToken && hasDots ) - { - tokenizer = new Tokenizer( expression ); + if (trimRootToken && hasDots) { + tokenizer = new Tokenizer(expression); tokenizer.nextPropertyName(); - if ( tokenizer.getPosition() == EOF ) - { + if (tokenizer.getPosition() == EOF) { return null; } - } - else - { - tokenizer = new Tokenizer( "." + expression ); + } else { + tokenizer = new Tokenizer("." + expression); } int propertyPosition = tokenizer.getPosition(); - while ( value != null && tokenizer.peekChar() != EOF ) - { - switch ( tokenizer.skipChar() ) - { + while (value != null && tokenizer.peekChar() != EOF) { + switch (tokenizer.skipChar()) { case INDEXED_START: - value = getIndexedValue( expression, propertyPosition, tokenizer.getPosition(), value, - tokenizer.nextToken( INDEXED_END ) ); + value = getIndexedValue( + expression, + propertyPosition, + tokenizer.getPosition(), + value, + tokenizer.nextToken(INDEXED_END)); break; case MAPPED_START: - value = getMappedValue( expression, propertyPosition, tokenizer.getPosition(), value, - tokenizer.nextToken( MAPPED_END ) ); + value = getMappedValue( + expression, + propertyPosition, + tokenizer.getPosition(), + value, + tokenizer.nextToken(MAPPED_END)); break; case PROPERTY_START: propertyPosition = tokenizer.getPosition(); - value = getPropertyValue( value, tokenizer.nextPropertyName() ); + value = getPropertyValue(value, tokenizer.nextPropertyName()); break; default: // could not parse expression @@ -232,124 +215,102 @@ public static Object evaluate( String expression, final Object root, final boole return value; } - private static Object getMappedValue( final String expression, final int from, final int to, final Object value, - final String key ) - throws Exception - { - if ( value == null || key == null ) - { + private static Object getMappedValue( + final String expression, final int from, final int to, final Object value, final String key) + throws Exception { + if (value == null || key == null) { return null; } - if ( value instanceof Map ) - { - Object[] localParams = new Object[] { key }; - ClassMap classMap = getClassMap( value.getClass() ); - Method method = classMap.findMethod( "get", localParams ); - return method.invoke( value, localParams ); + if (value instanceof Map) { + Object[] localParams = new Object[] {key}; + ClassMap classMap = getClassMap(value.getClass()); + Method method = classMap.findMethod("get", localParams); + return method.invoke(value, localParams); } - final String message = - String.format( "The token '%s' at position '%d' refers to a java.util.Map, but the value seems is an instance of '%s'", - expression.subSequence( from, to ), from, value.getClass() ); + final String message = String.format( + "The token '%s' at position '%d' refers to a java.util.Map, but the value seems is an instance of '%s'", + expression.subSequence(from, to), from, value.getClass()); - throw new Exception( message ); + throw new Exception(message); } - private static Object getIndexedValue( final String expression, final int from, final int to, final Object value, - final String indexStr ) - throws Exception - { - try - { - int index = Integer.parseInt( indexStr ); - - if ( value.getClass().isArray() ) - { - return Array.get( value, index ); + private static Object getIndexedValue( + final String expression, final int from, final int to, final Object value, final String indexStr) + throws Exception { + try { + int index = Integer.parseInt(indexStr); + + if (value.getClass().isArray()) { + return Array.get(value, index); } - if ( value instanceof List ) - { - ClassMap classMap = getClassMap( value.getClass() ); + if (value instanceof List) { + ClassMap classMap = getClassMap(value.getClass()); // use get method on List interface - Object[] localParams = new Object[] { index }; - Method method = classMap.findMethod( "get", localParams ); - return method.invoke( value, localParams ); + Object[] localParams = new Object[] {index}; + Method method = classMap.findMethod("get", localParams); + return method.invoke(value, localParams); } - } - catch ( NumberFormatException e ) - { + } catch (NumberFormatException e) { return null; - } - catch ( InvocationTargetException e ) - { + } catch (InvocationTargetException e) { // catch array index issues gracefully, otherwise release - if ( e.getCause() instanceof IndexOutOfBoundsException ) - { + if (e.getCause() instanceof IndexOutOfBoundsException) { return null; } throw e; } - final String message = - String.format( "The token '%s' at position '%d' refers to a java.util.List or an array, but the value seems is an instance of '%s'", - expression.subSequence( from, to ), from, value.getClass() ); + final String message = String.format( + "The token '%s' at position '%d' refers to a java.util.List or an array, but the value seems is an instance of '%s'", + expression.subSequence(from, to), from, value.getClass()); - throw new Exception( message ); + throw new Exception(message); } - private static Object getPropertyValue( Object value, String property ) - throws Exception - { - if ( value == null || property == null ) - { + private static Object getPropertyValue(Object value, String property) throws Exception { + if (value == null || property == null) { return null; } - ClassMap classMap = getClassMap( value.getClass() ); - String methodBase = StringUtils.capitalizeFirstLetter( property ); + ClassMap classMap = getClassMap(value.getClass()); + String methodBase = StringUtils.capitalizeFirstLetter(property); String methodName = "get" + methodBase; - Method method = classMap.findMethod( methodName, CLASS_ARGS ); + Method method = classMap.findMethod(methodName, CLASS_ARGS); - if ( method == null ) - { + if (method == null) { // perhaps this is a boolean property?? methodName = "is" + methodBase; - method = classMap.findMethod( methodName, CLASS_ARGS ); + method = classMap.findMethod(methodName, CLASS_ARGS); } - if ( method == null ) - { + if (method == null) { return null; } - try - { - return method.invoke( value, OBJECT_ARGS ); - } - catch ( InvocationTargetException e ) - { + try { + return method.invoke(value, OBJECT_ARGS); + } catch (InvocationTargetException e) { throw e; } } - private static ClassMap getClassMap( Class clazz ) - { + private static ClassMap getClassMap(Class clazz) { - WeakReference softRef = classMaps.get( clazz ); + WeakReference softRef = classMaps.get(clazz); ClassMap classMap; - if ( softRef == null || ( classMap = softRef.get() ) == null ) - { - classMap = new ClassMap( clazz ); + if (softRef == null || (classMap = softRef.get()) == null) { + classMap = new ClassMap(clazz); - classMaps.put( clazz, new WeakReference( classMap ) ); + classMaps.put(clazz, new WeakReference(classMap)); } return classMap; } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/interpolation/util/StringUtils.java b/src/main/java/org/codehaus/plexus/interpolation/util/StringUtils.java index 507cbf9..1852725 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/util/StringUtils.java +++ b/src/main/java/org/codehaus/plexus/interpolation/util/StringUtils.java @@ -59,8 +59,7 @@ * * @author jdcasey */ -public class StringUtils -{ +public class StringUtils { /** *

    Replace all occurrences of a String within another String.

    @@ -73,9 +72,8 @@ public class StringUtils * @param with String to replace with * @return the text with any replacements processed */ - public static String replace( String text, String repl, String with ) - { - return replace( text, repl, with, -1 ); + public static String replace(String text, String repl, String with) { + return replace(text, repl, with, -1); } /** @@ -90,41 +88,34 @@ public static String replace( String text, String repl, String with ) * @param max maximum number of values to replace, or -1 if no maximum * @return the text with any replacements processed */ - public static String replace( String text, String repl, String with, int max ) - { - if ( ( text == null ) || ( repl == null ) || ( with == null ) || ( repl.length() == 0 ) ) - { + public static String replace(String text, String repl, String with, int max) { + if ((text == null) || (repl == null) || (with == null) || (repl.length() == 0)) { return text; } - StringBuilder buf = new StringBuilder( text.length() ); + StringBuilder buf = new StringBuilder(text.length()); int start = 0, end; - while ( ( end = text.indexOf( repl, start ) ) != -1 ) - { - buf.append( text, start, end ).append( with ); + while ((end = text.indexOf(repl, start)) != -1) { + buf.append(text, start, end).append(with); start = end + repl.length(); - if ( --max == 0 ) - { + if (--max == 0) { break; } } - buf.append( text, start, text.length()); + buf.append(text, start, text.length()); return buf.toString(); } - public static String capitalizeFirstLetter( String data ) - { - char firstChar = data.charAt( 0 ); - char titleCase = Character.toTitleCase( firstChar ); - if (firstChar == titleCase) - { + public static String capitalizeFirstLetter(String data) { + char firstChar = data.charAt(0); + char titleCase = Character.toTitleCase(firstChar); + if (firstChar == titleCase) { return data; } - StringBuilder result = new StringBuilder( data.length() ); - result.append( titleCase ); - result.append( data, 1, data.length() ); + StringBuilder result = new StringBuilder(data.length()); + result.append(titleCase); + result.append(data, 1, data.length()); return result.toString(); } - } diff --git a/src/main/java/org/codehaus/plexus/interpolation/util/ValueSourceUtils.java b/src/main/java/org/codehaus/plexus/interpolation/util/ValueSourceUtils.java index 558f28a..85c1dad 100644 --- a/src/main/java/org/codehaus/plexus/interpolation/util/ValueSourceUtils.java +++ b/src/main/java/org/codehaus/plexus/interpolation/util/ValueSourceUtils.java @@ -16,21 +16,18 @@ * limitations under the License. */ -import org.codehaus.plexus.interpolation.ValueSource; - import java.util.Collection; +import org.codehaus.plexus.interpolation.ValueSource; + /** * Utility methods shared by multiple {@link ValueSource} implementations. * * @author jdcasey */ -public final class ValueSourceUtils -{ +public final class ValueSourceUtils { - private ValueSourceUtils() - { - } + private ValueSourceUtils() {} /** * If the expression starts with one of the provided prefixes, trim that prefix @@ -47,63 +44,50 @@ private ValueSourceUtils() * @return The trimmed expression, or null. See the behavior of * allowUnprefixedExpressions in this method for more detail. */ - public static String trimPrefix( String expression, Collection possiblePrefixes, - boolean allowUnprefixedExpressions ) - { - if ( expression == null ) - { + public static String trimPrefix( + String expression, Collection possiblePrefixes, boolean allowUnprefixedExpressions) { + if (expression == null) { return null; } String realExpr = null; - for ( String prefix : possiblePrefixes ) - { - if ( expression.startsWith( prefix ) ) - { - realExpr = expression.substring( prefix.length() ); - if ( realExpr.startsWith( "." ) ) - { - realExpr = realExpr.substring( 1 ); + for (String prefix : possiblePrefixes) { + if (expression.startsWith(prefix)) { + realExpr = expression.substring(prefix.length()); + if (realExpr.startsWith(".")) { + realExpr = realExpr.substring(1); } break; } } - if ( realExpr == null && allowUnprefixedExpressions ) - { + if (realExpr == null && allowUnprefixedExpressions) { realExpr = expression; } return realExpr; } - public static String trimPrefix( String expression, String[] possiblePrefixes, boolean allowUnprefixedExpressions ) - { - if ( expression == null ) - { + public static String trimPrefix(String expression, String[] possiblePrefixes, boolean allowUnprefixedExpressions) { + if (expression == null) { return null; } String realExpr = null; - for ( String prefix : possiblePrefixes ) - { - if ( expression.startsWith( prefix ) ) - { - realExpr = expression.substring( prefix.length() ); - if ( realExpr.startsWith( "." ) ) - { - realExpr = realExpr.substring( 1 ); + for (String prefix : possiblePrefixes) { + if (expression.startsWith(prefix)) { + realExpr = expression.substring(prefix.length()); + if (realExpr.startsWith(".")) { + realExpr = realExpr.substring(1); } break; } } - if ( realExpr == null && allowUnprefixedExpressions ) - { + if (realExpr == null && allowUnprefixedExpressions) { realExpr = expression; } return realExpr; } - } diff --git a/src/test/java/org/codehaus/plexus/interpolation/EnvarBasedValueSourceTest.java b/src/test/java/org/codehaus/plexus/interpolation/EnvarBasedValueSourceTest.java index e6b200b..8a3c76c 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/EnvarBasedValueSourceTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/EnvarBasedValueSourceTest.java @@ -16,10 +16,6 @@ * limitations under the License. */ -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - import java.io.IOException; import java.util.HashMap; import java.util.Map; @@ -28,72 +24,64 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class EnvarBasedValueSourceTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class EnvarBasedValueSourceTest { @BeforeEach - public void setUp() - { + public void setUp() { EnvarBasedValueSource.resetStatics(); } @Test - void testNoArgConstructorIsCaseSensitive() - throws IOException - { - OperatingSystemUtils.setEnvVarSource( new OperatingSystemUtils.EnvVarSource() - { - public Map getEnvMap() - { + void testNoArgConstructorIsCaseSensitive() throws IOException { + OperatingSystemUtils.setEnvVarSource(new OperatingSystemUtils.EnvVarSource() { + public Map getEnvMap() { HashMap map = new HashMap(); - map.put( "aVariable", "variable" ); + map.put("aVariable", "variable"); return map; } - } ); + }); EnvarBasedValueSource source = new EnvarBasedValueSource(); - assertEquals( "variable", source.getValue( "aVariable" ) ); - assertEquals( "variable", source.getValue( "env.aVariable" ) ); - assertNull( source.getValue( "AVARIABLE" ) ); - assertNull( source.getValue( "env.AVARIABLE" ) ); + assertEquals("variable", source.getValue("aVariable")); + assertEquals("variable", source.getValue("env.aVariable")); + assertNull(source.getValue("AVARIABLE")); + assertNull(source.getValue("env.AVARIABLE")); } @Test - void testCaseInsensitive() - throws IOException - { - OperatingSystemUtils.setEnvVarSource( new OperatingSystemUtils.EnvVarSource() - { - public Map getEnvMap() - { + void testCaseInsensitive() throws IOException { + OperatingSystemUtils.setEnvVarSource(new OperatingSystemUtils.EnvVarSource() { + public Map getEnvMap() { HashMap map = new HashMap(); - map.put( "aVariable", "variable" ); + map.put("aVariable", "variable"); return map; } - } ); + }); - EnvarBasedValueSource source = new EnvarBasedValueSource( false ); + EnvarBasedValueSource source = new EnvarBasedValueSource(false); - assertEquals( "variable", source.getValue( "aVariable" ) ); - assertEquals( "variable", source.getValue( "env.aVariable" ) ); - assertEquals( "variable", source.getValue( "AVARIABLE" ) ); - assertEquals( "variable", source.getValue( "env.AVARIABLE" ) ); + assertEquals("variable", source.getValue("aVariable")); + assertEquals("variable", source.getValue("env.aVariable")); + assertEquals("variable", source.getValue("AVARIABLE")); + assertEquals("variable", source.getValue("env.AVARIABLE")); } @Test - void testGetRealEnvironmentVariable() - throws IOException - { - OperatingSystemUtils.setEnvVarSource( new OperatingSystemUtils.DefaultEnvVarSource() ); + void testGetRealEnvironmentVariable() throws IOException { + OperatingSystemUtils.setEnvVarSource(new OperatingSystemUtils.DefaultEnvVarSource()); EnvarBasedValueSource source = new EnvarBasedValueSource(); String realEnvVar = "JAVA_HOME"; - String realValue = System.getenv().get( realEnvVar ); - assertNotNull( realValue , "Can't run this test until " + realEnvVar + " env variable is set"); + String realValue = System.getenv().get(realEnvVar); + assertNotNull(realValue, "Can't run this test until " + realEnvVar + " env variable is set"); - assertEquals( realValue, source.getValue( realEnvVar ) ); + assertEquals(realValue, source.getValue(realEnvVar)); } -} \ No newline at end of file +} diff --git a/src/test/java/org/codehaus/plexus/interpolation/InterpolatorFilterReaderTest.java b/src/test/java/org/codehaus/plexus/interpolation/InterpolatorFilterReaderTest.java index 88eacf0..0be913d 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/InterpolatorFilterReaderTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/InterpolatorFilterReaderTest.java @@ -24,8 +24,6 @@ * SOFTWARE. */ -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.io.StringReader; import java.util.ArrayList; import java.util.HashMap; @@ -34,296 +32,258 @@ import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * InterpolatorFilterReaderTest, heavily based on InterpolationFilterReaderTest. Heh, even the test strings remained the * same! - * + * * @author cstamas - * + * */ -public class InterpolatorFilterReaderTest -{ +public class InterpolatorFilterReaderTest { /* * Added and commented by jdcasey@03-Feb-2005 because it is a bug in the InterpolationFilterReader. * kenneyw@15-04-2005 fixed the bug. */ @Test - public void testShouldNotInterpolateExpressionAtEndOfDataWithInvalidEndToken() - throws Exception - { + public void testShouldNotInterpolateExpressionAtEndOfDataWithInvalidEndToken() throws Exception { Map m = new HashMap(); - m.put( "test", "TestValue" ); + m.put("test", "TestValue"); String testStr = "This is a ${test"; - assertEquals( "This is a ${test", interpolate( testStr, m ) ); + assertEquals("This is a ${test", interpolate(testStr, m)); } /* * kenneyw@14-04-2005 Added test to check above fix. */ @Test - public void testShouldNotInterpolateExpressionWithMissingEndToken() - throws Exception - { + public void testShouldNotInterpolateExpressionWithMissingEndToken() throws Exception { Map m = new HashMap(); - m.put( "test", "TestValue" ); + m.put("test", "TestValue"); String testStr = "This is a ${test, really"; - assertEquals( "This is a ${test, really", interpolate( testStr, m ) ); + assertEquals("This is a ${test, really", interpolate(testStr, m)); } @Test - public void testShouldNotInterpolateWithMalformedStartToken() - throws Exception - { + public void testShouldNotInterpolateWithMalformedStartToken() throws Exception { Map m = new HashMap(); - m.put( "test", "testValue" ); + m.put("test", "testValue"); String foo = "This is a $!test} again"; - assertEquals( "This is a $!test} again", interpolate( foo, m ) ); + assertEquals("This is a $!test} again", interpolate(foo, m)); } @Test - public void testShouldNotInterpolateWithMalformedEndToken() - throws Exception - { + public void testShouldNotInterpolateWithMalformedEndToken() throws Exception { Map m = new HashMap(); - m.put( "test", "testValue" ); + m.put("test", "testValue"); String foo = "This is a ${test!} again"; - assertEquals( "This is a ${test!} again", interpolate( foo, m ) ); + assertEquals("This is a ${test!} again", interpolate(foo, m)); } @Test - public void testDefaultInterpolationWithNonInterpolatedValueAtEnd() - throws Exception - { + public void testDefaultInterpolationWithNonInterpolatedValueAtEnd() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "${name} is an ${noun}. ${not.interpolated}"; - assertEquals( "jason is an asshole. ${not.interpolated}", interpolate( foo, m ) ); + assertEquals("jason is an asshole. ${not.interpolated}", interpolate(foo, m)); } @Test - public void testDefaultInterpolationWithInterpolatedValueAtEnd() - throws Exception - { + public void testDefaultInterpolationWithInterpolatedValueAtEnd() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "${name} is an ${noun}"; - assertEquals( "jason is an asshole", interpolate( foo, m ) ); + assertEquals("jason is an asshole", interpolate(foo, m)); } @Test - public void testInterpolationWithInterpolatedValueAtEndWithCustomToken() - throws Exception - { + public void testInterpolationWithInterpolatedValueAtEndWithCustomToken() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "@{name} is an @{noun}"; - assertEquals( "jason is an asshole", interpolate( foo, m, "@{", "}" ) ); + assertEquals("jason is an asshole", interpolate(foo, m, "@{", "}")); } @Test - public void testInterpolationWithInterpolatedValueAtEndWithCustomTokenAndCustomString() - throws Exception - { + public void testInterpolationWithInterpolatedValueAtEndWithCustomTokenAndCustomString() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "@name@ is an @noun@"; - assertEquals( "jason is an asshole", interpolate( foo, m, "@", "@" ) ); + assertEquals("jason is an asshole", interpolate(foo, m, "@", "@")); } @Test - public void testEscape() - throws Exception - { + public void testEscape() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "${name} is an \\${noun}"; - assertEquals( "jason is an ${noun}", interpolate( foo, m, "\\" ) ); + assertEquals("jason is an ${noun}", interpolate(foo, m, "\\")); } @Test - public void testEscapeAtStart() - throws Exception - { + public void testEscapeAtStart() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "\\${name} is an \\${noun}"; - assertEquals( "${name} is an ${noun}", interpolate( foo, m, "\\" ) ); + assertEquals("${name} is an ${noun}", interpolate(foo, m, "\\")); } @Test - public void testEscapeOnlyAtStart() - throws Exception - { + public void testEscapeOnlyAtStart() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "\\@name@ is an @noun@"; - String result = interpolate( foo, m, "@", "@" ); - assertEquals( "@name@ is an asshole", result ); + String result = interpolate(foo, m, "@", "@"); + assertEquals("@name@ is an asshole", result); } @Test - public void testEscapeOnlyAtStartDefaultToken() - throws Exception - { + public void testEscapeOnlyAtStartDefaultToken() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "\\${name} is an ${noun}"; - String result = interpolate( foo, m, "${", "}" ); - assertEquals( "${name} is an asshole", result ); + String result = interpolate(foo, m, "${", "}"); + assertEquals("${name} is an asshole", result); } @Test - public void testShouldDetectRecursiveExpressionPassingThroughTwoPrefixes() - throws Exception - { + public void testShouldDetectRecursiveExpressionPassingThroughTwoPrefixes() throws Exception { List prefixes = new ArrayList(); - prefixes.add( "prefix1" ); - prefixes.add( "prefix2" ); + prefixes.add("prefix1"); + prefixes.add("prefix2"); - RecursionInterceptor ri = new PrefixAwareRecursionInterceptor( prefixes, false ); + RecursionInterceptor ri = new PrefixAwareRecursionInterceptor(prefixes, false); Map context = new HashMap(); - context.put( "name", "${prefix2.name}" ); + context.put("name", "${prefix2.name}"); String input = "${prefix1.name}"; StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new MapBasedValueSource( context ) ); + interpolator.addValueSource(new MapBasedValueSource(context)); - InterpolatorFilterReader r = new InterpolatorFilterReader( new StringReader( input ), interpolator, ri ); - r.setInterpolateWithPrefixPattern( false ); - r.setEscapeString( "\\" ); + InterpolatorFilterReader r = new InterpolatorFilterReader(new StringReader(input), interpolator, ri); + r.setInterpolateWithPrefixPattern(false); + r.setEscapeString("\\"); StringBuilder buf = new StringBuilder(); int read = -1; char[] cbuf = new char[1024]; - while ( ( read = r.read( cbuf ) ) > -1 ) - { - buf.append( cbuf, 0, read ); + while ((read = r.read(cbuf)) > -1) { + buf.append(cbuf, 0, read); } - assertEquals( input, buf.toString() ); + assertEquals(input, buf.toString()); } @Test - public void testShouldDetectRecursiveExpressionWithPrefixAndWithout() - throws Exception - { + public void testShouldDetectRecursiveExpressionWithPrefixAndWithout() throws Exception { List prefixes = new ArrayList(); - prefixes.add( "prefix1" ); + prefixes.add("prefix1"); - RecursionInterceptor ri = new PrefixAwareRecursionInterceptor( prefixes, false ); + RecursionInterceptor ri = new PrefixAwareRecursionInterceptor(prefixes, false); Map context = new HashMap(); - context.put( "name", "${prefix1.name}" ); + context.put("name", "${prefix1.name}"); String input = "${name}"; StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new MapBasedValueSource( context ) ); + interpolator.addValueSource(new MapBasedValueSource(context)); - InterpolatorFilterReader r = new InterpolatorFilterReader( new StringReader( input ), interpolator, ri ); - r.setInterpolateWithPrefixPattern( false ); - r.setEscapeString( "\\" ); + InterpolatorFilterReader r = new InterpolatorFilterReader(new StringReader(input), interpolator, ri); + r.setInterpolateWithPrefixPattern(false); + r.setEscapeString("\\"); StringBuilder buf = new StringBuilder(); int read = -1; char[] cbuf = new char[1024]; - while ( ( read = r.read( cbuf ) ) > -1 ) - { - buf.append( cbuf, 0, read ); + while ((read = r.read(cbuf)) > -1) { + buf.append(cbuf, 0, read); } - assertEquals( "${prefix1.name}", buf.toString() ); + assertEquals("${prefix1.name}", buf.toString()); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - private String interpolate( String input, Map context ) - throws Exception - { - return interpolate( input, context, null ); + private String interpolate(String input, Map context) throws Exception { + return interpolate(input, context, null); } - private String interpolate( String input, Map context, String escapeStr ) - throws Exception - { + private String interpolate(String input, Map context, String escapeStr) throws Exception { Interpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new MapBasedValueSource( context ) ); + interpolator.addValueSource(new MapBasedValueSource(context)); - InterpolatorFilterReader r = new InterpolatorFilterReader( new StringReader( input ), interpolator ); - r.setInterpolateWithPrefixPattern( false ); - if ( escapeStr != null ) - { - r.setEscapeString( escapeStr ); + InterpolatorFilterReader r = new InterpolatorFilterReader(new StringReader(input), interpolator); + r.setInterpolateWithPrefixPattern(false); + if (escapeStr != null) { + r.setEscapeString(escapeStr); } StringBuilder buf = new StringBuilder(); int read = -1; char[] cbuf = new char[1024]; - while ( ( read = r.read( cbuf ) ) > -1 ) - { - buf.append( cbuf, 0, read ); + while ((read = r.read(cbuf)) > -1) { + buf.append(cbuf, 0, read); } return buf.toString(); } - private String interpolate( String input, Map context, String beginToken, String endToken ) - throws Exception - { - StringSearchInterpolator interpolator = new StringSearchInterpolator( beginToken, endToken ); + private String interpolate(String input, Map context, String beginToken, String endToken) throws Exception { + StringSearchInterpolator interpolator = new StringSearchInterpolator(beginToken, endToken); - interpolator.addValueSource( new MapBasedValueSource( context ) ); + interpolator.addValueSource(new MapBasedValueSource(context)); - InterpolatorFilterReader r = new InterpolatorFilterReader( new StringReader( input ), interpolator, beginToken, endToken ); - r.setInterpolateWithPrefixPattern( false ); - r.setEscapeString( "\\" ); + InterpolatorFilterReader r = + new InterpolatorFilterReader(new StringReader(input), interpolator, beginToken, endToken); + r.setInterpolateWithPrefixPattern(false); + r.setEscapeString("\\"); StringBuilder buf = new StringBuilder(); int read = -1; char[] cbuf = new char[1024]; - while ( ( read = r.read( cbuf ) ) > -1 ) - { - buf.append( cbuf, 0, read ); + while ((read = r.read(cbuf)) > -1) { + buf.append(cbuf, 0, read); } return buf.toString(); } - } diff --git a/src/test/java/org/codehaus/plexus/interpolation/PrefixAwareRecursionInterceptorTest.java b/src/test/java/org/codehaus/plexus/interpolation/PrefixAwareRecursionInterceptorTest.java index 1cbf533..d1f250a 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/PrefixAwareRecursionInterceptorTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/PrefixAwareRecursionInterceptorTest.java @@ -16,75 +16,64 @@ * limitations under the License. */ -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.Test; -public class PrefixAwareRecursionInterceptorTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class PrefixAwareRecursionInterceptorTest { @Test - public void testFindExpression() - { - PrefixAwareRecursionInterceptor receptor = new PrefixAwareRecursionInterceptor( - Collections.singleton( "prefix." ) ); + public void testFindExpression() { + PrefixAwareRecursionInterceptor receptor = + new PrefixAwareRecursionInterceptor(Collections.singleton("prefix.")); String expr = "prefix.first"; - receptor.expressionResolutionStarted( expr ); + receptor.expressionResolutionStarted(expr); - assertTrue( receptor.hasRecursiveExpression( expr ) ); - assertEquals( "[first]", receptor.getExpressionCycle( expr ).toString() ); + assertTrue(receptor.hasRecursiveExpression(expr)); + assertEquals("[first]", receptor.getExpressionCycle(expr).toString()); - receptor.expressionResolutionFinished( expr ); + receptor.expressionResolutionFinished(expr); - assertFalse( receptor.hasRecursiveExpression( expr ) ); + assertFalse(receptor.hasRecursiveExpression(expr)); } @Test - public void testFindExpressionWithDifferentPrefix() - { - PrefixAwareRecursionInterceptor receptor = new PrefixAwareRecursionInterceptor( - Arrays.asList( new String[] { - "prefix.", - "other." - } ) ); + public void testFindExpressionWithDifferentPrefix() { + PrefixAwareRecursionInterceptor receptor = + new PrefixAwareRecursionInterceptor(Arrays.asList(new String[] {"prefix.", "other."})); String expr = "prefix.first"; - receptor.expressionResolutionStarted( expr ); + receptor.expressionResolutionStarted(expr); - assertTrue( receptor.hasRecursiveExpression( expr ) ); + assertTrue(receptor.hasRecursiveExpression(expr)); - receptor.expressionResolutionFinished( expr ); + receptor.expressionResolutionFinished(expr); - assertFalse( receptor.hasRecursiveExpression( expr ) ); + assertFalse(receptor.hasRecursiveExpression(expr)); } @Test - public void testFindExpressionWithoutPrefix() - { - PrefixAwareRecursionInterceptor receptor = new PrefixAwareRecursionInterceptor( - Arrays.asList( new String[] { - "prefix.", - "other." - } ) ); + public void testFindExpressionWithoutPrefix() { + PrefixAwareRecursionInterceptor receptor = + new PrefixAwareRecursionInterceptor(Arrays.asList(new String[] {"prefix.", "other."})); String prefixedExpr = "prefix.first"; String expr = "first"; - receptor.expressionResolutionStarted( prefixedExpr ); + receptor.expressionResolutionStarted(prefixedExpr); - assertTrue( receptor.hasRecursiveExpression( expr ) ); + assertTrue(receptor.hasRecursiveExpression(expr)); - receptor.expressionResolutionFinished( prefixedExpr ); + receptor.expressionResolutionFinished(prefixedExpr); - assertFalse( receptor.hasRecursiveExpression( expr ) ); + assertFalse(receptor.hasRecursiveExpression(expr)); } - } diff --git a/src/test/java/org/codehaus/plexus/interpolation/PrefixedObjectValueSourceTest.java b/src/test/java/org/codehaus/plexus/interpolation/PrefixedObjectValueSourceTest.java index 0a916aa..996d090 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/PrefixedObjectValueSourceTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/PrefixedObjectValueSourceTest.java @@ -16,59 +16,54 @@ * limitations under the License. */ -import static org.junit.jupiter.api.Assertions.assertNull; - import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; -public class PrefixedObjectValueSourceTest -{ +import static org.junit.jupiter.api.Assertions.assertNull; + +public class PrefixedObjectValueSourceTest { @Test - public void testEmptyExpressionResultsInNullReturn_NoPrefixUsed() - { + public void testEmptyExpressionResultsInNullReturn_NoPrefixUsed() { String target = "Target object"; - + List prefixes = new ArrayList(); - prefixes.add( "target" ); - prefixes.add( "object" ); - - PrefixedObjectValueSource vs = new PrefixedObjectValueSource( prefixes, target, true ); - Object result = vs.getValue( "" ); - - assertNull( result ); + prefixes.add("target"); + prefixes.add("object"); + + PrefixedObjectValueSource vs = new PrefixedObjectValueSource(prefixes, target, true); + Object result = vs.getValue(""); + + assertNull(result); } @Test - public void testEmptyExpressionResultsInNullReturn_PrefixUsedWithDot() - { + public void testEmptyExpressionResultsInNullReturn_PrefixUsedWithDot() { String target = "Target object"; - + List prefixes = new ArrayList(); - prefixes.add( "target" ); - prefixes.add( "object" ); - - PrefixedObjectValueSource vs = new PrefixedObjectValueSource( prefixes, target, true ); - Object result = vs.getValue( "target." ); - - assertNull( result ); + prefixes.add("target"); + prefixes.add("object"); + + PrefixedObjectValueSource vs = new PrefixedObjectValueSource(prefixes, target, true); + Object result = vs.getValue("target."); + + assertNull(result); } @Test - public void testEmptyExpressionResultsInNullReturn_PrefixUsedWithoutDot() - { + public void testEmptyExpressionResultsInNullReturn_PrefixUsedWithoutDot() { String target = "Target object"; - + List prefixes = new ArrayList(); - prefixes.add( "target" ); - prefixes.add( "object" ); - - PrefixedObjectValueSource vs = new PrefixedObjectValueSource( prefixes, target, true ); - Object result = vs.getValue( "target" ); - - assertNull( result ); - } + prefixes.add("target"); + prefixes.add("object"); + + PrefixedObjectValueSource vs = new PrefixedObjectValueSource(prefixes, target, true); + Object result = vs.getValue("target"); + assertNull(result); + } } diff --git a/src/test/java/org/codehaus/plexus/interpolation/PrefixedValueSourceWrapperTest.java b/src/test/java/org/codehaus/plexus/interpolation/PrefixedValueSourceWrapperTest.java index e7502a4..1e65b9b 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/PrefixedValueSourceWrapperTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/PrefixedValueSourceWrapperTest.java @@ -16,58 +16,56 @@ * limitations under the License. */ -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - import java.util.Properties; import org.junit.jupiter.api.Test; -public class PrefixedValueSourceWrapperTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class PrefixedValueSourceWrapperTest { @Test - public void testShouldReturnValueForPropertyVSWRappedWithSinglePrefix() - { + public void testShouldReturnValueForPropertyVSWRappedWithSinglePrefix() { String prefix = "prefix."; String key = "key"; String value = "value"; Properties props = new Properties(); - props.setProperty( key, value ); + props.setProperty(key, value); - PrefixedValueSourceWrapper wrapper = new PrefixedValueSourceWrapper( new PropertiesBasedValueSource( props ), prefix ); + PrefixedValueSourceWrapper wrapper = + new PrefixedValueSourceWrapper(new PropertiesBasedValueSource(props), prefix); - assertEquals( value, wrapper.getValue( prefix + key ) ); + assertEquals(value, wrapper.getValue(prefix + key)); } @Test - public void testShouldReturnNullForIncorrectPrefixUsingPropertyVSWRappedWithSinglePrefix() - { + public void testShouldReturnNullForIncorrectPrefixUsingPropertyVSWRappedWithSinglePrefix() { String prefix = "prefix."; String otherPrefix = "other."; String key = "key"; String value = "value"; Properties props = new Properties(); - props.setProperty( key, value ); + props.setProperty(key, value); - PrefixedValueSourceWrapper wrapper = new PrefixedValueSourceWrapper( new PropertiesBasedValueSource( props ), prefix ); + PrefixedValueSourceWrapper wrapper = + new PrefixedValueSourceWrapper(new PropertiesBasedValueSource(props), prefix); - assertNull( wrapper.getValue( otherPrefix + key ) ); + assertNull(wrapper.getValue(otherPrefix + key)); } @Test - public void testShouldNullForMissingValueInPropertyVSWRappedWithSinglePrefix() - { + public void testShouldNullForMissingValueInPropertyVSWRappedWithSinglePrefix() { String prefix = "prefix."; String key = "key"; Properties props = new Properties(); - PrefixedValueSourceWrapper wrapper = new PrefixedValueSourceWrapper( new PropertiesBasedValueSource( props ), prefix ); + PrefixedValueSourceWrapper wrapper = + new PrefixedValueSourceWrapper(new PropertiesBasedValueSource(props), prefix); - assertNull( wrapper.getValue( prefix + key ) ); + assertNull(wrapper.getValue(prefix + key)); } - } diff --git a/src/test/java/org/codehaus/plexus/interpolation/PropertiesBasedValueSourceTest.java b/src/test/java/org/codehaus/plexus/interpolation/PropertiesBasedValueSourceTest.java index d893030..6fe10b8 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/PropertiesBasedValueSourceTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/PropertiesBasedValueSourceTest.java @@ -16,41 +16,37 @@ * limitations under the License. */ -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - import java.util.Properties; import org.junit.jupiter.api.Test; -public class PropertiesBasedValueSourceTest -{ +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class PropertiesBasedValueSourceTest { @Test - public void testPropertyShouldReturnValueFromProperties() - { + public void testPropertyShouldReturnValueFromProperties() { Properties props = new Properties(); String key = "key"; String value = "value"; - props.setProperty( key, value ); + props.setProperty(key, value); - PropertiesBasedValueSource vs = new PropertiesBasedValueSource( props ); + PropertiesBasedValueSource vs = new PropertiesBasedValueSource(props); - assertNotNull( vs.getValue( key ) ); + assertNotNull(vs.getValue(key)); } @Test - public void testPropertyShouldReturnNullWhenPropertyMissing() - { + public void testPropertyShouldReturnNullWhenPropertyMissing() { Properties props = new Properties(); String key = "key"; - PropertiesBasedValueSource vs = new PropertiesBasedValueSource( props ); + PropertiesBasedValueSource vs = new PropertiesBasedValueSource(props); - assertNull( vs.getValue( key ) ); + assertNull(vs.getValue(key)); } - } diff --git a/src/test/java/org/codehaus/plexus/interpolation/RegexBasedInterpolatorTest.java b/src/test/java/org/codehaus/plexus/interpolation/RegexBasedInterpolatorTest.java index 245ef51..d3c31f6 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/RegexBasedInterpolatorTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/RegexBasedInterpolatorTest.java @@ -16,9 +16,6 @@ * limitations under the License. */ -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; - import java.io.IOException; import java.util.HashMap; import java.util.Map; @@ -28,211 +25,180 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class RegexBasedInterpolatorTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +public class RegexBasedInterpolatorTest { @BeforeEach - public void setUp() - { + public void setUp() { EnvarBasedValueSource.resetStatics(); } - public String getVar() - { + public String getVar() { return "testVar"; } @Test - public void testShouldFailOnExpressionCycle() - { + public void testShouldFailOnExpressionCycle() { Properties props = new Properties(); - props.setProperty( "key1", "${key2}" ); - props.setProperty( "key2", "${key1}" ); + props.setProperty("key1", "${key2}"); + props.setProperty("key2", "${key1}"); RegexBasedInterpolator rbi = new RegexBasedInterpolator(); - rbi.addValueSource( new PropertiesBasedValueSource( props ) ); + rbi.addValueSource(new PropertiesBasedValueSource(props)); - try - { - rbi.interpolate( "${key1}", new SimpleRecursionInterceptor() ); + try { + rbi.interpolate("${key1}", new SimpleRecursionInterceptor()); - fail( "Should detect expression cycle and fail." ); - } - catch ( InterpolationException e ) - { + fail("Should detect expression cycle and fail."); + } catch (InterpolationException e) { // expected } } @Test - public void testShouldResolveByMy_getVar_Method() - throws InterpolationException - { + public void testShouldResolveByMy_getVar_Method() throws InterpolationException { RegexBasedInterpolator rbi = new RegexBasedInterpolator(); - rbi.addValueSource( new ObjectBasedValueSource( this ) ); - String result = rbi.interpolate( "this is a ${this.var}", "this" ); + rbi.addValueSource(new ObjectBasedValueSource(this)); + String result = rbi.interpolate("this is a ${this.var}", "this"); - assertEquals( "this is a testVar", result ); + assertEquals("this is a testVar", result); } @Test - public void testShouldResolveByContextValue() - throws InterpolationException - { + public void testShouldResolveByContextValue() throws InterpolationException { RegexBasedInterpolator rbi = new RegexBasedInterpolator(); Map context = new HashMap(); - context.put( "var", "testVar" ); + context.put("var", "testVar"); - rbi.addValueSource( new MapBasedValueSource( context ) ); + rbi.addValueSource(new MapBasedValueSource(context)); - String result = rbi.interpolate( "this is a ${this.var}", "this" ); + String result = rbi.interpolate("this is a ${this.var}", "this"); - assertEquals( "this is a testVar", result ); + assertEquals("this is a testVar", result); } @Test - public void testShouldResolveByEnvar() - throws IOException, InterpolationException - { - OperatingSystemUtils.setEnvVarSource( new OperatingSystemUtils.EnvVarSource() - { - public Map getEnvMap() - { - HashMap map = new HashMap(); - map.put( "SOME_ENV", "variable" ); + public void testShouldResolveByEnvar() throws IOException, InterpolationException { + OperatingSystemUtils.setEnvVarSource(new OperatingSystemUtils.EnvVarSource() { + public Map getEnvMap() { + HashMap map = new HashMap(); + map.put("SOME_ENV", "variable"); return map; } - } ); + }); RegexBasedInterpolator rbi = new RegexBasedInterpolator(); - rbi.addValueSource( new EnvarBasedValueSource() ); + rbi.addValueSource(new EnvarBasedValueSource()); - String result = rbi.interpolate( "this is a ${env.SOME_ENV}", "this" ); + String result = rbi.interpolate("this is a ${env.SOME_ENV}", "this"); - assertEquals( "this is a variable", result ); + assertEquals("this is a variable", result); } @Test - public void testUseAlternateRegex() - throws Exception - { - RegexBasedInterpolator rbi = new RegexBasedInterpolator( "\\@\\{(", ")?([^}]+)\\}@" ); + public void testUseAlternateRegex() throws Exception { + RegexBasedInterpolator rbi = new RegexBasedInterpolator("\\@\\{(", ")?([^}]+)\\}@"); Map context = new HashMap(); - context.put( "var", "testVar" ); + context.put("var", "testVar"); - rbi.addValueSource( new MapBasedValueSource( context ) ); + rbi.addValueSource(new MapBasedValueSource(context)); - String result = rbi.interpolate( "this is a @{this.var}@", "this" ); + String result = rbi.interpolate("this is a @{this.var}@", "this"); - assertEquals( "this is a testVar", result ); + assertEquals("this is a testVar", result); } @Test - public void testNPEFree() - throws Exception - { - RegexBasedInterpolator rbi = new RegexBasedInterpolator( "\\@\\{(", ")?([^}]+)\\}@" ); + public void testNPEFree() throws Exception { + RegexBasedInterpolator rbi = new RegexBasedInterpolator("\\@\\{(", ")?([^}]+)\\}@"); Map context = new HashMap(); - context.put( "var", "testVar" ); + context.put("var", "testVar"); - rbi.addValueSource( new MapBasedValueSource( context ) ); + rbi.addValueSource(new MapBasedValueSource(context)); - String result = rbi.interpolate( null ); + String result = rbi.interpolate(null); - assertEquals( "", result ); + assertEquals("", result); } @Test - public void testUsePostProcessor_DoesNotChangeValue() - throws InterpolationException - { + public void testUsePostProcessor_DoesNotChangeValue() throws InterpolationException { RegexBasedInterpolator rbi = new RegexBasedInterpolator(); - + Map context = new HashMap(); - context.put( "test.var", "testVar" ); + context.put("test.var", "testVar"); - rbi.addValueSource( new MapBasedValueSource( context ) ); + rbi.addValueSource(new MapBasedValueSource(context)); - rbi.addPostProcessor( new InterpolationPostProcessor() - { - public Object execute( String expression, Object value ) - { + rbi.addPostProcessor(new InterpolationPostProcessor() { + public Object execute(String expression, Object value) { return null; } - } ); + }); - String result = rbi.interpolate( "this is a ${test.var}", "" ); + String result = rbi.interpolate("this is a ${test.var}", ""); - assertEquals( "this is a testVar", result ); + assertEquals("this is a testVar", result); } @Test - public void testUsePostProcessor_ChangesValue() - throws InterpolationException - { + public void testUsePostProcessor_ChangesValue() throws InterpolationException { int loopNumber = 200000; - + long start = System.currentTimeMillis(); RegexBasedInterpolator rbi = new RegexBasedInterpolator(); Map context = new HashMap(); - context.put( "test.var", "testVar" ); + context.put("test.var", "testVar"); - rbi.addValueSource( new MapBasedValueSource( context ) ); + rbi.addValueSource(new MapBasedValueSource(context)); - rbi.addPostProcessor( new InterpolationPostProcessor() - { - public Object execute( String expression, Object value ) - { + rbi.addPostProcessor(new InterpolationPostProcessor() { + public Object execute(String expression, Object value) { return value + "2"; } - } ); - - for ( int i = 0, number = loopNumber; i < number; i++ ) - { + }); + for (int i = 0, number = loopNumber; i < number; i++) { - String result = rbi.interpolate( "this is a ${test.var}", "" ); + String result = rbi.interpolate("this is a ${test.var}", ""); - assertEquals( "this is a testVar2", result ); + assertEquals("this is a testVar2", result); } long end = System.currentTimeMillis(); - System.out.println( "time without pattern reuse and RegexBasedInterpolator instance reuse " + ( end - start ) ); + System.out.println("time without pattern reuse and RegexBasedInterpolator instance reuse " + (end - start)); System.gc(); - + start = System.currentTimeMillis(); - - - - rbi = new RegexBasedInterpolator( true ); - - rbi.addPostProcessor( new InterpolationPostProcessor() - { - public Object execute( String expression, Object value ) - { + + rbi = new RegexBasedInterpolator(true); + + rbi.addPostProcessor(new InterpolationPostProcessor() { + public Object execute(String expression, Object value) { return value + "2"; } - } ); - - rbi.addValueSource( new MapBasedValueSource( context ) ); - - for ( int i = 0, number = loopNumber; i < number; i++ ) - { + }); + + rbi.addValueSource(new MapBasedValueSource(context)); + + for (int i = 0, number = loopNumber; i < number; i++) { - String result = rbi.interpolate( "this is a ${test.var}", "" ); + String result = rbi.interpolate("this is a ${test.var}", ""); - assertEquals( "this is a testVar2", result ); + assertEquals("this is a testVar2", result); } end = System.currentTimeMillis(); - System.out.println( "time with pattern reuse and RegexBasedInterpolator instance reuse " + ( end - start ) ); + System.out.println("time with pattern reuse and RegexBasedInterpolator instance reuse " + (end - start)); } } diff --git a/src/test/java/org/codehaus/plexus/interpolation/StringSearchInterpolatorTest.java b/src/test/java/org/codehaus/plexus/interpolation/StringSearchInterpolatorTest.java index 1d184eb..5152670 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/StringSearchInterpolatorTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/StringSearchInterpolatorTest.java @@ -16,9 +16,6 @@ * limitations under the License. */ -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.fail; - import java.io.IOException; import java.util.ArrayList; import java.util.Collections; @@ -31,488 +28,419 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class StringSearchInterpolatorTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +public class StringSearchInterpolatorTest { @BeforeEach - public void setUp() - { + public void setUp() { EnvarBasedValueSource.resetStatics(); } @Test - public void testLongDelimitersInContext() - throws InterpolationException - { + public void testLongDelimitersInContext() throws InterpolationException { String src = "This is a test.label for long delimiters in context."; String result = "This is a test for long delimiters in context."; Properties p = new Properties(); - p.setProperty( "test.label", "test" ); + p.setProperty("test.label", "test"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "", "" ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("", ""); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - assertEquals( result, interpolator.interpolate( src ) ); + assertEquals(result, interpolator.interpolate(src)); } @Test - public void testLongDelimitersWithNoStartContext() - throws InterpolationException - { + public void testLongDelimitersWithNoStartContext() throws InterpolationException { String src = "test.label for long delimiters in context."; String result = "test for long delimiters in context."; Properties p = new Properties(); - p.setProperty( "test.label", "test" ); + p.setProperty("test.label", "test"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "", "" ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("", ""); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - assertEquals( result, interpolator.interpolate( src ) ); + assertEquals(result, interpolator.interpolate(src)); } @Test - public void testLongDelimitersWithNoEndContext() - throws InterpolationException - { + public void testLongDelimitersWithNoEndContext() throws InterpolationException { String src = "This is a test.label"; String result = "This is a test"; Properties p = new Properties(); - p.setProperty( "test.label", "test" ); + p.setProperty("test.label", "test"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "", "" ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("", ""); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - assertEquals( result, interpolator.interpolate( src ) ); + assertEquals(result, interpolator.interpolate(src)); } @Test - public void testLongDelimitersWithNoContext() - throws InterpolationException - { + public void testLongDelimitersWithNoContext() throws InterpolationException { String src = "test.label"; String result = "test"; Properties p = new Properties(); - p.setProperty( "test.label", "test" ); + p.setProperty("test.label", "test"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "", "" ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("", ""); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - assertEquals( result, interpolator.interpolate( src ) ); + assertEquals(result, interpolator.interpolate(src)); } @Test - public void testSimpleSubstitution() - throws InterpolationException - { + public void testSimpleSubstitution() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - assertEquals( "This is a test value.", interpolator.interpolate( "This is a test ${key}." ) ); + assertEquals("This is a test value.", interpolator.interpolate("This is a test ${key}.")); } @Test - public void testSimpleSubstitution_TwoExpressions() - throws InterpolationException - { + public void testSimpleSubstitution_TwoExpressions() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); - p.setProperty( "key2", "value2" ); + p.setProperty("key", "value"); + p.setProperty("key2", "value2"); StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - assertEquals( "value-value2", interpolator.interpolate( "${key}-${key2}" ) ); + assertEquals("value-value2", interpolator.interpolate("${key}-${key2}")); } @Test - public void testBrokenExpression_LeaveItAlone() - throws InterpolationException - { + public void testBrokenExpression_LeaveItAlone() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - assertEquals( "This is a test ${key.", interpolator.interpolate( "This is a test ${key." ) ); + assertEquals("This is a test ${key.", interpolator.interpolate("This is a test ${key.")); } @Test - public void testShouldFailOnExpressionCycle() - { + public void testShouldFailOnExpressionCycle() { Properties props = new Properties(); - props.setProperty( "key1", "${key2}" ); - props.setProperty( "key2", "${key1}" ); + props.setProperty("key1", "${key2}"); + props.setProperty("key2", "${key1}"); StringSearchInterpolator rbi = new StringSearchInterpolator(); - rbi.addValueSource( new PropertiesBasedValueSource( props ) ); + rbi.addValueSource(new PropertiesBasedValueSource(props)); - try - { - rbi.interpolate( "${key1}", new SimpleRecursionInterceptor() ); + try { + rbi.interpolate("${key1}", new SimpleRecursionInterceptor()); - fail( "Should detect expression cycle and fail." ); - } - catch ( InterpolationException e ) - { + fail("Should detect expression cycle and fail."); + } catch (InterpolationException e) { // expected } } @Test - public void testShouldResolveByUsingObject_List_Map() - throws InterpolationException - { + public void testShouldResolveByUsingObject_List_Map() throws InterpolationException { StringSearchInterpolator rbi = new StringSearchInterpolator(); - rbi.addValueSource( new ObjectBasedValueSource( this ) ); + rbi.addValueSource(new ObjectBasedValueSource(this)); String result = - rbi.interpolate( "this is a ${var} ${list[1].name} ${anArray[2].name} ${map(Key with spaces).name}" ); + rbi.interpolate("this is a ${var} ${list[1].name} ${anArray[2].name} ${map(Key with spaces).name}"); - assertEquals( "this is a testVar testIndexedWithList testIndexedWithArray testMap", result ); + assertEquals("this is a testVar testIndexedWithList testIndexedWithArray testMap", result); } @Test - public void testShouldResolveByContextValue() - throws InterpolationException - { + public void testShouldResolveByContextValue() throws InterpolationException { StringSearchInterpolator rbi = new StringSearchInterpolator(); Map context = new HashMap(); - context.put( "var", "testVar" ); + context.put("var", "testVar"); - rbi.addValueSource( new MapBasedValueSource( context ) ); + rbi.addValueSource(new MapBasedValueSource(context)); - String result = rbi.interpolate( "this is a ${var}" ); + String result = rbi.interpolate("this is a ${var}"); - assertEquals( "this is a testVar", result ); + assertEquals("this is a testVar", result); } @Test - public void testShouldResolveByEnvar() - throws IOException, InterpolationException - { - OperatingSystemUtils.setEnvVarSource( new OperatingSystemUtils.EnvVarSource() - { - public Map getEnvMap() - { - HashMap map = new HashMap(); - map.put( "SOME_ENV", "variable" ); - map.put( "OTHER_ENV", "other variable" ); + public void testShouldResolveByEnvar() throws IOException, InterpolationException { + OperatingSystemUtils.setEnvVarSource(new OperatingSystemUtils.EnvVarSource() { + public Map getEnvMap() { + HashMap map = new HashMap(); + map.put("SOME_ENV", "variable"); + map.put("OTHER_ENV", "other variable"); return map; } - } ); + }); StringSearchInterpolator rbi = new StringSearchInterpolator(); - rbi.addValueSource( new EnvarBasedValueSource( false ) ); + rbi.addValueSource(new EnvarBasedValueSource(false)); - String result = rbi.interpolate( "this is a ${env.SOME_ENV} ${env.OTHER_ENV}" ); + String result = rbi.interpolate("this is a ${env.SOME_ENV} ${env.OTHER_ENV}"); - assertEquals( "this is a variable other variable", result ); + assertEquals("this is a variable other variable", result); } @Test - public void testUsePostProcessor_DoesNotChangeValue() - throws InterpolationException - { + public void testUsePostProcessor_DoesNotChangeValue() throws InterpolationException { StringSearchInterpolator rbi = new StringSearchInterpolator(); Map context = new HashMap(); - context.put( "test.var", "testVar" ); + context.put("test.var", "testVar"); - rbi.addValueSource( new MapBasedValueSource( context ) ); + rbi.addValueSource(new MapBasedValueSource(context)); - rbi.addPostProcessor( new InterpolationPostProcessor() - { - public Object execute( String expression, Object value ) - { + rbi.addPostProcessor(new InterpolationPostProcessor() { + public Object execute(String expression, Object value) { return null; } - } ); + }); - String result = rbi.interpolate( "this is a ${test.var}" ); + String result = rbi.interpolate("this is a ${test.var}"); - assertEquals( "this is a testVar", result ); + assertEquals("this is a testVar", result); } @Test - public void testUsePostProcessor_ChangesValue() - throws InterpolationException - { + public void testUsePostProcessor_ChangesValue() throws InterpolationException { StringSearchInterpolator rbi = new StringSearchInterpolator(); Map context = new HashMap(); - context.put( "test.var", "testVar" ); + context.put("test.var", "testVar"); - rbi.addValueSource( new MapBasedValueSource( context ) ); + rbi.addValueSource(new MapBasedValueSource(context)); - rbi.addPostProcessor( new InterpolationPostProcessor() - { - public Object execute( String expression, Object value ) - { + rbi.addPostProcessor(new InterpolationPostProcessor() { + public Object execute(String expression, Object value) { return value + "2"; } - } ); + }); - String result = rbi.interpolate( "this is a ${test.var}" ); + String result = rbi.interpolate("this is a ${test.var}"); - assertEquals( "this is a testVar2", result ); + assertEquals("this is a testVar2", result); } @Test - public void testSimpleSubstitutionWithDefinedExpr() - throws InterpolationException - { + public void testSimpleSubstitutionWithDefinedExpr() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "@{", "}" ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("@{", "}"); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - assertEquals( "This is a test value.", interpolator.interpolate( "This is a test @{key}." ) ); + assertEquals("This is a test value.", interpolator.interpolate("This is a test @{key}.")); } @Test - public void testEscape() - throws InterpolationException - { + public void testEscape() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "@{", "}" ); - interpolator.setEscapeString( "\\" ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("@{", "}"); + interpolator.setEscapeString("\\"); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - String result = interpolator.interpolate( "This is a test \\@{key}." ); + String result = interpolator.interpolate("This is a test \\@{key}."); - assertEquals( "This is a test @{key}.", result ); + assertEquals("This is a test @{key}.", result); } @Test - public void testEscapeWithLongEscapeStr() - throws InterpolationException - { + public void testEscapeWithLongEscapeStr() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "@{", "}" ); - interpolator.setEscapeString( "$$" ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("@{", "}"); + interpolator.setEscapeString("$$"); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - String result = interpolator.interpolate( "This is a test $$@{key}." ); + String result = interpolator.interpolate("This is a test $$@{key}."); - assertEquals( "This is a test @{key}.", result ); + assertEquals("This is a test @{key}.", result); } @Test - public void testEscapeWithLongEscapeStrAtStart() - throws InterpolationException - { + public void testEscapeWithLongEscapeStrAtStart() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "@{", "}" ); - interpolator.setEscapeString( "$$" ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("@{", "}"); + interpolator.setEscapeString("$$"); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - String result = interpolator.interpolate( "$$@{key} This is a test." ); + String result = interpolator.interpolate("$$@{key} This is a test."); - assertEquals( "@{key} This is a test.", result ); + assertEquals("@{key} This is a test.", result); } @Test - public void testNotEscapeWithLongEscapeStrAtStart() - throws InterpolationException - { + public void testNotEscapeWithLongEscapeStrAtStart() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "@{", "}" ); - interpolator.setEscapeString( "$$" ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("@{", "}"); + interpolator.setEscapeString("$$"); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - String result = interpolator.interpolate( "@{key} This is a test." ); + String result = interpolator.interpolate("@{key} This is a test."); - assertEquals( "value This is a test.", result ); + assertEquals("value This is a test.", result); } @Test - public void testEscapeNotFailWithNullEscapeStr() - throws InterpolationException - { + public void testEscapeNotFailWithNullEscapeStr() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "@{", "}" ); - interpolator.setEscapeString( null ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("@{", "}"); + interpolator.setEscapeString(null); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - String result = interpolator.interpolate( "This is a test @{key}." ); + String result = interpolator.interpolate("This is a test @{key}."); - assertEquals( "This is a test value.", result ); + assertEquals("This is a test value.", result); } @Test - public void testOnlyEscapeExprAtStart() - throws InterpolationException - { + public void testOnlyEscapeExprAtStart() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "@{", "}" ); - interpolator.setEscapeString( "\\" ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("@{", "}"); + interpolator.setEscapeString("\\"); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - String result = interpolator.interpolate( "\\@{key} This is a test." ); + String result = interpolator.interpolate("\\@{key} This is a test."); - assertEquals( "@{key} This is a test.", result ); + assertEquals("@{key} This is a test.", result); } @Test - public void testNotEscapeExprAtStart() - throws InterpolationException - { + public void testNotEscapeExprAtStart() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "@{", "}" ); - interpolator.setEscapeString( "\\" ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("@{", "}"); + interpolator.setEscapeString("\\"); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - String result = interpolator.interpolate( "@{key} This is a test." ); + String result = interpolator.interpolate("@{key} This is a test."); - assertEquals( "value This is a test.", result ); + assertEquals("value This is a test.", result); } @Test - public void testEscapeExprAtStart() - throws InterpolationException - { + public void testEscapeExprAtStart() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "@", "@" ); - interpolator.setEscapeString( "\\" ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("@", "@"); + interpolator.setEscapeString("\\"); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - String result = interpolator.interpolate( "\\@key@ This is a test @key@." ); + String result = interpolator.interpolate("\\@key@ This is a test @key@."); - assertEquals( "@key@ This is a test value.", result ); + assertEquals("@key@ This is a test value.", result); } @Test - public void testNPEFree() - throws InterpolationException - { + public void testNPEFree() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "@{", "}" ); - interpolator.setEscapeString( "\\" ); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + StringSearchInterpolator interpolator = new StringSearchInterpolator("@{", "}"); + interpolator.setEscapeString("\\"); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - String result = interpolator.interpolate( null ); + String result = interpolator.interpolate(null); - assertEquals( "", result ); + assertEquals("", result); } @Test - public void testInterruptedInterpolate() - throws InterpolationException - { + public void testInterruptedInterpolate() throws InterpolationException { Interpolator interpolator = new StringSearchInterpolator(); RecursionInterceptor recursionInterceptor = new SimpleRecursionInterceptor(); - final boolean[] error = new boolean[] { false }; - interpolator.addValueSource( new ValueSource() - { - public Object getValue( String expression ) { - if ( expression.equals( "key" ) ) - { - if ( error[ 0 ] ) - { - throw new IllegalStateException( "broken" ); + final boolean[] error = new boolean[] {false}; + interpolator.addValueSource(new ValueSource() { + public Object getValue(String expression) { + if (expression.equals("key")) { + if (error[0]) { + throw new IllegalStateException("broken"); } return "val"; - } - else - { + } else { return null; } } - public List getFeedback() - { + + public List getFeedback() { return Collections.EMPTY_LIST; } - public void clearFeedback() - { - } - } ); - assertEquals( "-val-" , interpolator.interpolate( "-${key}-", recursionInterceptor ) , "control case"); - error[ 0 ] = true; - try - { - interpolator.interpolate( "-${key}-", recursionInterceptor ); - fail( "should have thrown exception" ); - } - catch ( IllegalStateException x ) - { + + public void clearFeedback() {} + }); + assertEquals("-val-", interpolator.interpolate("-${key}-", recursionInterceptor), "control case"); + error[0] = true; + try { + interpolator.interpolate("-${key}-", recursionInterceptor); + fail("should have thrown exception"); + } catch (IllegalStateException x) { // right } - error[ 0 ] = false; - assertEquals( "-val-", interpolator.interpolate( "-${key}-", recursionInterceptor ) , "should not believe there is a cycle here"); + error[0] = false; + assertEquals( + "-val-", + interpolator.interpolate("-${key}-", recursionInterceptor), + "should not believe there is a cycle here"); } - public String getVar() - { + public String getVar() { return "testVar"; } - public Person[] getAnArray() - { + public Person[] getAnArray() { Person[] array = new Person[3]; - array[0] = new Person( "Gabriel" ); - array[1] = new Person( "Daniela" ); - array[2] = new Person( "testIndexedWithArray" ); + array[0] = new Person("Gabriel"); + array[1] = new Person("Daniela"); + array[2] = new Person("testIndexedWithArray"); return array; } - public List getList() - { + public List getList() { List list = new ArrayList(); - list.add( new Person( "Gabriel" ) ); - list.add( new Person( "testIndexedWithList" ) ); - list.add( new Person( "Daniela" ) ); + list.add(new Person("Gabriel")); + list.add(new Person("testIndexedWithList")); + list.add(new Person("Daniela")); return list; } - public Map getMap() - { + public Map getMap() { Map map = new HashMap(); - map.put( "Key with spaces", new Person( "testMap" ) ); + map.put("Key with spaces", new Person("testMap")); return map; } - public static class Person - { + public static class Person { private String name; - public Person( String name ) - { + public Person(String name) { this.name = name; } - public String getName() - { + public String getName() { return name; } } - } diff --git a/src/test/java/org/codehaus/plexus/interpolation/fixed/EnvarBasedValueSourceTest.java b/src/test/java/org/codehaus/plexus/interpolation/fixed/EnvarBasedValueSourceTest.java index e0f283b..b6ff638 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/fixed/EnvarBasedValueSourceTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/fixed/EnvarBasedValueSourceTest.java @@ -16,10 +16,6 @@ * limitations under the License. */ -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - import java.io.IOException; import java.util.HashMap; import java.util.Map; @@ -28,73 +24,64 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class EnvarBasedValueSourceTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +public class EnvarBasedValueSourceTest { @BeforeEach - public void setUp() - { + public void setUp() { EnvarBasedValueSource.resetStatics(); } @Test - void testNoArgConstructorIsCaseSensitive() - throws IOException - { - OperatingSystemUtils.setEnvVarSource( new OperatingSystemUtils.EnvVarSource() - { - public Map getEnvMap() - { + void testNoArgConstructorIsCaseSensitive() throws IOException { + OperatingSystemUtils.setEnvVarSource(new OperatingSystemUtils.EnvVarSource() { + public Map getEnvMap() { HashMap map = new HashMap(); - map.put( "aVariable", "variable" ); + map.put("aVariable", "variable"); return map; } - } ); + }); EnvarBasedValueSource source = new EnvarBasedValueSource(); - assertEquals( "variable", source.getValue( "aVariable", null ) ); - assertEquals( "variable", source.getValue( "env.aVariable", null ) ); - assertNull( source.getValue( "AVARIABLE", null ) ); - assertNull( source.getValue( "env.AVARIABLE", null ) ); + assertEquals("variable", source.getValue("aVariable", null)); + assertEquals("variable", source.getValue("env.aVariable", null)); + assertNull(source.getValue("AVARIABLE", null)); + assertNull(source.getValue("env.AVARIABLE", null)); } @Test - void testCaseInsensitive() - throws IOException - { - OperatingSystemUtils.setEnvVarSource( new OperatingSystemUtils.EnvVarSource() - { - public Map getEnvMap() - { + void testCaseInsensitive() throws IOException { + OperatingSystemUtils.setEnvVarSource(new OperatingSystemUtils.EnvVarSource() { + public Map getEnvMap() { HashMap map = new HashMap(); - map.put( "aVariable", "variable" ); + map.put("aVariable", "variable"); return map; } - } ); + }); - EnvarBasedValueSource source = new EnvarBasedValueSource( false ); + EnvarBasedValueSource source = new EnvarBasedValueSource(false); - assertEquals( "variable", source.getValue( "aVariable", null ) ); - assertEquals( "variable", source.getValue( "env.aVariable", null ) ); - assertEquals( "variable", source.getValue( "AVARIABLE", null ) ); - assertEquals( "variable", source.getValue( "env.AVARIABLE", null ) ); + assertEquals("variable", source.getValue("aVariable", null)); + assertEquals("variable", source.getValue("env.aVariable", null)); + assertEquals("variable", source.getValue("AVARIABLE", null)); + assertEquals("variable", source.getValue("env.AVARIABLE", null)); } @Test - void testGetRealEnvironmentVariable() - throws IOException - { - OperatingSystemUtils.setEnvVarSource( new OperatingSystemUtils.DefaultEnvVarSource() ); + void testGetRealEnvironmentVariable() throws IOException { + OperatingSystemUtils.setEnvVarSource(new OperatingSystemUtils.DefaultEnvVarSource()); EnvarBasedValueSource source = new EnvarBasedValueSource(); String realEnvVar = "JAVA_HOME"; - String realValue = System.getenv().get( realEnvVar ); - assertNotNull( realValue , "Can't run this test until " + realEnvVar + " env variable is set"); + String realValue = System.getenv().get(realEnvVar); + assertNotNull(realValue, "Can't run this test until " + realEnvVar + " env variable is set"); - assertEquals( realValue, source.getValue( realEnvVar, null ) ); + assertEquals(realValue, source.getValue(realEnvVar, null)); } - } diff --git a/src/test/java/org/codehaus/plexus/interpolation/fixed/FixedStringSearchInterpolatorTest.java b/src/test/java/org/codehaus/plexus/interpolation/fixed/FixedStringSearchInterpolatorTest.java index a7990f1..afef83e 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/fixed/FixedStringSearchInterpolatorTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/fixed/FixedStringSearchInterpolatorTest.java @@ -15,10 +15,6 @@ * limitations under the License. */ -import static org.codehaus.plexus.interpolation.fixed.FixedStringSearchInterpolator.create; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -34,532 +30,474 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -public class FixedStringSearchInterpolatorTest -{ +import static org.codehaus.plexus.interpolation.fixed.FixedStringSearchInterpolator.create; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class FixedStringSearchInterpolatorTest { @BeforeEach - public void setUp() - { + public void setUp() { EnvarBasedValueSource.resetStatics(); } @Test - void testLongDelimitersInContext() - { + void testLongDelimitersInContext() { String src = "This is a test.label for long delimiters in context."; String result = "This is a test for long delimiters in context."; Properties p = new Properties(); - p.setProperty( "test.label", "test" ); + p.setProperty("test.label", "test"); FixedStringSearchInterpolator interpolator = - create( new PropertiesBasedValueSource( p ) ).withExpressionMarkers( "", "" ); + create(new PropertiesBasedValueSource(p)).withExpressionMarkers("", ""); - assertEquals( result, interpolator.interpolate( src ) ); + assertEquals(result, interpolator.interpolate(src)); } @Test - void testLongDelimitersWithNoStartContext() - { + void testLongDelimitersWithNoStartContext() { String src = "test.label for long delimiters in context."; String result = "test for long delimiters in context."; Properties p = new Properties(); - p.setProperty( "test.label", "test" ); + p.setProperty("test.label", "test"); FixedStringSearchInterpolator interpolator = - create( new PropertiesBasedValueSource( p ) ).withExpressionMarkers( "", "" ); + create(new PropertiesBasedValueSource(p)).withExpressionMarkers("", ""); - assertEquals( result, interpolator.interpolate( src ) ); + assertEquals(result, interpolator.interpolate(src)); } @Test - void testLongDelimitersWithNoEndContext() - { + void testLongDelimitersWithNoEndContext() { String src = "This is a test.label"; String result = "This is a test"; Properties p = new Properties(); - p.setProperty( "test.label", "test" ); + p.setProperty("test.label", "test"); FixedStringSearchInterpolator interpolator = - create( new PropertiesBasedValueSource( p ) ).withExpressionMarkers( "", "" ); + create(new PropertiesBasedValueSource(p)).withExpressionMarkers("", ""); - assertEquals( result, interpolator.interpolate( src ) ); + assertEquals(result, interpolator.interpolate(src)); } @Test - void testLongDelimitersWithNoContext() - { + void testLongDelimitersWithNoContext() { String src = "test.label"; String result = "test"; Properties p = new Properties(); - p.setProperty( "test.label", "test" ); + p.setProperty("test.label", "test"); FixedStringSearchInterpolator interpolator = - create( new PropertiesBasedValueSource( p ) ).withExpressionMarkers( "", "" ); + create(new PropertiesBasedValueSource(p)).withExpressionMarkers("", ""); - assertEquals( result, interpolator.interpolate( src ) ); + assertEquals(result, interpolator.interpolate(src)); } @Test - void testSimpleSubstitution() - { + void testSimpleSubstitution() { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - FixedStringSearchInterpolator interpolator = create( new PropertiesBasedValueSource( p ) ); + FixedStringSearchInterpolator interpolator = create(new PropertiesBasedValueSource(p)); - assertEquals( "This is a test value.", interpolator.interpolate( "This is a test ${key}." ) ); + assertEquals("This is a test value.", interpolator.interpolate("This is a test ${key}.")); } @Test - void testSimpleSubstitution_TwoExpressions() - { + void testSimpleSubstitution_TwoExpressions() { Properties p = new Properties(); - p.setProperty( "key", "value" ); - p.setProperty( "key2", "value2" ); + p.setProperty("key", "value"); + p.setProperty("key2", "value2"); - FixedStringSearchInterpolator interpolator = create( new PropertiesBasedValueSource( p ) ); + FixedStringSearchInterpolator interpolator = create(new PropertiesBasedValueSource(p)); - assertEquals( "value-value2", interpolator.interpolate( "${key}-${key2}" ) ); + assertEquals("value-value2", interpolator.interpolate("${key}-${key2}")); } @Test - void testBrokenExpression_LeaveItAlone() - { + void testBrokenExpression_LeaveItAlone() { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - FixedStringSearchInterpolator interpolator = create( new PropertiesBasedValueSource( p ) ); + FixedStringSearchInterpolator interpolator = create(new PropertiesBasedValueSource(p)); - assertEquals( "This is a test ${key.", interpolator.interpolate( "This is a test ${key." ) ); + assertEquals("This is a test ${key.", interpolator.interpolate("This is a test ${key.")); } @Test - void testShouldFailOnExpressionCycle() - { + void testShouldFailOnExpressionCycle() { Properties props = new Properties(); - props.setProperty( "key1", "${key2}" ); - props.setProperty( "key2", "${key1}" ); + props.setProperty("key1", "${key2}"); + props.setProperty("key2", "${key1}"); - FixedStringSearchInterpolator rbi = create( new PropertiesBasedValueSource( props ) ); + FixedStringSearchInterpolator rbi = create(new PropertiesBasedValueSource(props)); - assertThrows(InterpolationCycleException.class, () -> rbi.interpolate( "${key1}" ), - "Should detect expression cycle and fail." ); + assertThrows( + InterpolationCycleException.class, + () -> rbi.interpolate("${key1}"), + "Should detect expression cycle and fail."); } @Test - void testShouldResolveByUsingObject_List_Map() - throws InterpolationException - { - FixedStringSearchInterpolator rbi = create( new ObjectBasedValueSource( this ) ); + void testShouldResolveByUsingObject_List_Map() throws InterpolationException { + FixedStringSearchInterpolator rbi = create(new ObjectBasedValueSource(this)); String result = - rbi.interpolate( "this is a ${var} ${list[1].name} ${anArray[2].name} ${map(Key with spaces).name}" ); + rbi.interpolate("this is a ${var} ${list[1].name} ${anArray[2].name} ${map(Key with spaces).name}"); - assertEquals( "this is a testVar testIndexedWithList testIndexedWithArray testMap", result ); + assertEquals("this is a testVar testIndexedWithList testIndexedWithArray testMap", result); } @Test - void testShouldResolveByContextValue() - throws InterpolationException - { + void testShouldResolveByContextValue() throws InterpolationException { Map context = new HashMap(); - context.put( "var", "testVar" ); + context.put("var", "testVar"); - FixedStringSearchInterpolator rbi = create( new MapBasedValueSource( context ) ); + FixedStringSearchInterpolator rbi = create(new MapBasedValueSource(context)); - String result = rbi.interpolate( "this is a ${var}" ); + String result = rbi.interpolate("this is a ${var}"); - assertEquals( "this is a testVar", result ); + assertEquals("this is a testVar", result); } @Test - void testShouldResolveByEnvar() - throws IOException, InterpolationException - { - OperatingSystemUtils.setEnvVarSource( new OperatingSystemUtils.EnvVarSource() - { - public Map getEnvMap() - { - HashMap map = new HashMap(); - map.put( "SOME_ENV", "variable" ); - map.put( "OTHER_ENV", "other variable" ); + void testShouldResolveByEnvar() throws IOException, InterpolationException { + OperatingSystemUtils.setEnvVarSource(new OperatingSystemUtils.EnvVarSource() { + public Map getEnvMap() { + HashMap map = new HashMap(); + map.put("SOME_ENV", "variable"); + map.put("OTHER_ENV", "other variable"); return map; } - } ); + }); - FixedStringSearchInterpolator rbi = create( new EnvarBasedValueSource( false ) ); + FixedStringSearchInterpolator rbi = create(new EnvarBasedValueSource(false)); - String result = rbi.interpolate( "this is a ${env.SOME_ENV} ${env.OTHER_ENV}" ); + String result = rbi.interpolate("this is a ${env.SOME_ENV} ${env.OTHER_ENV}"); - assertEquals( "this is a variable other variable", result ); + assertEquals("this is a variable other variable", result); } @Test - void testUsePostProcessor_DoesNotChangeValue() - throws InterpolationException - { + void testUsePostProcessor_DoesNotChangeValue() throws InterpolationException { Map context = new HashMap(); - context.put( "test.var", "testVar" ); + context.put("test.var", "testVar"); - final InterpolationPostProcessor postProcessor = new InterpolationPostProcessor() - { - public Object execute( String expression, Object value ) - { + final InterpolationPostProcessor postProcessor = new InterpolationPostProcessor() { + public Object execute(String expression, Object value) { return null; } }; FixedStringSearchInterpolator rbi = - create( new MapBasedValueSource( context ) ).withPostProcessor( postProcessor ); + create(new MapBasedValueSource(context)).withPostProcessor(postProcessor); - String result = rbi.interpolate( "this is a ${test.var}" ); + String result = rbi.interpolate("this is a ${test.var}"); - assertEquals( "this is a testVar", result ); + assertEquals("this is a testVar", result); } @Test - void testUsePostProcessor_ChangesValue() - throws InterpolationException - { + void testUsePostProcessor_ChangesValue() throws InterpolationException { Map context = new HashMap(); - context.put( "test.var", "testVar" ); + context.put("test.var", "testVar"); - final InterpolationPostProcessor postProcessor = new InterpolationPostProcessor() - { - public Object execute( String expression, Object value ) - { + final InterpolationPostProcessor postProcessor = new InterpolationPostProcessor() { + public Object execute(String expression, Object value) { return value + "2"; } }; FixedStringSearchInterpolator rbi = - create( new MapBasedValueSource( context ) ).withPostProcessor( postProcessor ); + create(new MapBasedValueSource(context)).withPostProcessor(postProcessor); - String result = rbi.interpolate( "this is a ${test.var}" ); + String result = rbi.interpolate("this is a ${test.var}"); - assertEquals( "this is a testVar2", result ); + assertEquals("this is a testVar2", result); } @Test - void testSimpleSubstitutionWithDefinedExpr() - throws InterpolationException - { + void testSimpleSubstitutionWithDefinedExpr() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - FixedStringSearchInterpolator interpolator = create( "@{", "}", new PropertiesBasedValueSource( p ) ); + FixedStringSearchInterpolator interpolator = create("@{", "}", new PropertiesBasedValueSource(p)); - assertEquals( "This is a test value.", interpolator.interpolate( "This is a test @{key}." ) ); + assertEquals("This is a test value.", interpolator.interpolate("This is a test @{key}.")); } @Test - void testEscape() - throws InterpolationException - { + void testEscape() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - FixedStringSearchInterpolator interpolator = - create( new PropertiesBasedValueSource( p ) ).withExpressionMarkers( "@{", "}" ).withEscapeString( "\\" ); + FixedStringSearchInterpolator interpolator = create(new PropertiesBasedValueSource(p)) + .withExpressionMarkers("@{", "}") + .withEscapeString("\\"); - String result = interpolator.interpolate( "This is a test \\@{key}." ); + String result = interpolator.interpolate("This is a test \\@{key}."); - assertEquals( "This is a test @{key}.", result ); + assertEquals("This is a test @{key}.", result); } @Test - void testEscapeWithLongEscapeStr() - throws InterpolationException - { + void testEscapeWithLongEscapeStr() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - FixedStringSearchInterpolator interpolator = - create( new PropertiesBasedValueSource( p ) ).withExpressionMarkers( "@{", "}" ).withEscapeString( "$$" ); + FixedStringSearchInterpolator interpolator = create(new PropertiesBasedValueSource(p)) + .withExpressionMarkers("@{", "}") + .withEscapeString("$$"); - String result = interpolator.interpolate( "This is a test $$@{key}." ); + String result = interpolator.interpolate("This is a test $$@{key}."); - assertEquals( "This is a test @{key}.", result ); + assertEquals("This is a test @{key}.", result); } @Test - void testEscapeWithLongEscapeStrAtStart() - throws InterpolationException - { + void testEscapeWithLongEscapeStrAtStart() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - FixedStringSearchInterpolator interpolator = - create( new PropertiesBasedValueSource( p ) ).withExpressionMarkers( "@{", "}" ).withEscapeString( "$$" ); + FixedStringSearchInterpolator interpolator = create(new PropertiesBasedValueSource(p)) + .withExpressionMarkers("@{", "}") + .withEscapeString("$$"); - String result = interpolator.interpolate( "$$@{key} This is a test." ); + String result = interpolator.interpolate("$$@{key} This is a test."); - assertEquals( "@{key} This is a test.", result ); + assertEquals("@{key} This is a test.", result); } @Test - void testNotEscapeWithLongEscapeStrAtStart() - throws InterpolationException - { + void testNotEscapeWithLongEscapeStrAtStart() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - FixedStringSearchInterpolator interpolator = - create( new PropertiesBasedValueSource( p ) ).withExpressionMarkers( "@{", "}" ).withEscapeString( "$$" ); + FixedStringSearchInterpolator interpolator = create(new PropertiesBasedValueSource(p)) + .withExpressionMarkers("@{", "}") + .withEscapeString("$$"); - String result = interpolator.interpolate( "@{key} This is a test." ); + String result = interpolator.interpolate("@{key} This is a test."); - assertEquals( "value This is a test.", result ); + assertEquals("value This is a test.", result); } @Test - void testEscapeNotFailWithNullEscapeStr() - throws InterpolationException - { + void testEscapeNotFailWithNullEscapeStr() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - FixedStringSearchInterpolator interpolator = - create( new PropertiesBasedValueSource( p ) ).withExpressionMarkers( "@{", "}" ).withEscapeString( null ); + FixedStringSearchInterpolator interpolator = create(new PropertiesBasedValueSource(p)) + .withExpressionMarkers("@{", "}") + .withEscapeString(null); - String result = interpolator.interpolate( "This is a test @{key}." ); + String result = interpolator.interpolate("This is a test @{key}."); - assertEquals( "This is a test value.", result ); + assertEquals("This is a test value.", result); } @Test - void testOnlyEscapeExprAtStart() - throws InterpolationException - { + void testOnlyEscapeExprAtStart() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - FixedStringSearchInterpolator interpolator = - create( new PropertiesBasedValueSource( p ) ).withExpressionMarkers( "@{", "}" ).withEscapeString( "\\" ); + FixedStringSearchInterpolator interpolator = create(new PropertiesBasedValueSource(p)) + .withExpressionMarkers("@{", "}") + .withEscapeString("\\"); - String result = interpolator.interpolate( "\\@{key} This is a test." ); + String result = interpolator.interpolate("\\@{key} This is a test."); - assertEquals( "@{key} This is a test.", result ); + assertEquals("@{key} This is a test.", result); } @Test - void testNotEscapeExprAtStart() - throws InterpolationException - { + void testNotEscapeExprAtStart() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - FixedStringSearchInterpolator interpolator = - create( new PropertiesBasedValueSource( p ) ).withExpressionMarkers( "@{", "}" ).withEscapeString( "\\" ); + FixedStringSearchInterpolator interpolator = create(new PropertiesBasedValueSource(p)) + .withExpressionMarkers("@{", "}") + .withEscapeString("\\"); - String result = interpolator.interpolate( "@{key} This is a test." ); + String result = interpolator.interpolate("@{key} This is a test."); - assertEquals( "value This is a test.", result ); + assertEquals("value This is a test.", result); } @Test - void testEscapeExprAtStart() - throws InterpolationException - { + void testEscapeExprAtStart() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - FixedStringSearchInterpolator interpolator = - create( new PropertiesBasedValueSource( p ) ).withExpressionMarkers( "@", "@" ).withEscapeString( "\\" ); + FixedStringSearchInterpolator interpolator = create(new PropertiesBasedValueSource(p)) + .withExpressionMarkers("@", "@") + .withEscapeString("\\"); - String result = interpolator.interpolate( "\\@key@ This is a test @key@." ); + String result = interpolator.interpolate("\\@key@ This is a test @key@."); - assertEquals( "@key@ This is a test value.", result ); + assertEquals("@key@ This is a test value.", result); } @Test - void testNPEFree() - throws InterpolationException - { + void testNPEFree() throws InterpolationException { Properties p = new Properties(); - p.setProperty( "key", "value" ); + p.setProperty("key", "value"); - FixedStringSearchInterpolator interpolator = - create( new PropertiesBasedValueSource( p ) ).withExpressionMarkers( "@{", "}" ).withEscapeString( "\\" ); + FixedStringSearchInterpolator interpolator = create(new PropertiesBasedValueSource(p)) + .withExpressionMarkers("@{", "}") + .withEscapeString("\\"); - String result = interpolator.interpolate( null ); + String result = interpolator.interpolate(null); - assertEquals( "", result ); + assertEquals("", result); } @Test - void testInterruptedInterpolate() - throws InterpolationException - { - final boolean[] error = new boolean[]{ false }; - FixedValueSource valueSource = new FixedValueSource() - { - public Object getValue( String expression, InterpolationState errorCollector ) - { - if ( expression.equals( "key" ) ) - { - if ( error[0] ) - { - throw new IllegalStateException( "broken" ); + void testInterruptedInterpolate() throws InterpolationException { + final boolean[] error = new boolean[] {false}; + FixedValueSource valueSource = new FixedValueSource() { + public Object getValue(String expression, InterpolationState errorCollector) { + if (expression.equals("key")) { + if (error[0]) { + throw new IllegalStateException("broken"); } return "val"; - } - else - { + } else { return null; } } }; - FixedStringSearchInterpolator interpolator = create( valueSource ); + FixedStringSearchInterpolator interpolator = create(valueSource); - assertEquals( "-val-", interpolator.interpolate( "-${key}-" ) , "control case"); + assertEquals("-val-", interpolator.interpolate("-${key}-"), "control case"); error[0] = true; - assertThrows( IllegalStateException.class, () -> interpolator.interpolate( "-${key}-" ) , + assertThrows( + IllegalStateException.class, + () -> interpolator.interpolate("-${key}-"), "should have thrown exception"); error[0] = false; - assertEquals( "-val-", interpolator.interpolate( "-${key}-" ) , "should not believe there is a cycle here"); + assertEquals("-val-", interpolator.interpolate("-${key}-"), "should not believe there is a cycle here"); } - public String getVar() - { + public String getVar() { return "testVar"; } - public Person[] getAnArray() - { + public Person[] getAnArray() { Person[] array = new Person[3]; - array[0] = new Person( "Gabriel" ); - array[1] = new Person( "Daniela" ); - array[2] = new Person( "testIndexedWithArray" ); + array[0] = new Person("Gabriel"); + array[1] = new Person("Daniela"); + array[2] = new Person("testIndexedWithArray"); return array; } - public List getList() - { + public List getList() { List list = new ArrayList(); - list.add( new Person( "Gabriel" ) ); - list.add( new Person( "testIndexedWithList" ) ); - list.add( new Person( "Daniela" ) ); + list.add(new Person("Gabriel")); + list.add(new Person("testIndexedWithList")); + list.add(new Person("Daniela")); return list; } - public Map getMap() - { + public Map getMap() { Map map = new HashMap(); - map.put( "Key with spaces", new Person( "testMap" ) ); + map.put("Key with spaces", new Person("testMap")); return map; } - public static class Person - { + public static class Person { private String name; - public Person( String name ) - { + public Person(String name) { this.name = name; } - public String getName() - { + public String getName() { return name; } } @Test - void testLinkedInterpolators() - { + void testLinkedInterpolators() { final String EXPR = "${test.label}AND${test2}"; final String EXPR2 = "${test.label}${test2.label}AND${test2}"; FixedStringSearchInterpolator interWith2Fields = - create( properttyBasedValueSource( "test.label", "p", "test2", "x" ) ); - assertEquals( "pANDx", interWith2Fields.interpolate( EXPR ) ); + create(properttyBasedValueSource("test.label", "p", "test2", "x")); + assertEquals("pANDx", interWith2Fields.interpolate(EXPR)); - FixedStringSearchInterpolator joined = - create( interWith2Fields, properttyBasedValueSource( "test2.label", "zz" ) ); - assertEquals( "pzzANDx", joined.interpolate( EXPR2 ) ); + FixedStringSearchInterpolator joined = create(interWith2Fields, properttyBasedValueSource("test2.label", "zz")); + assertEquals("pzzANDx", joined.interpolate(EXPR2)); } @Test - void testDominance() - { + void testDominance() { final String EXPR = "${test.label}AND${test2}"; final String EXPR2 = "${test.label}${test2.label}AND${test2}"; FixedStringSearchInterpolator interWith2Fields = - create( properttyBasedValueSource( "test.label", "p", "test2", "x", "test2.label", "dominant" ) ); - assertEquals( "pANDx", interWith2Fields.interpolate( EXPR ) ); + create(properttyBasedValueSource("test.label", "p", "test2", "x", "test2.label", "dominant")); + assertEquals("pANDx", interWith2Fields.interpolate(EXPR)); - FixedStringSearchInterpolator joined = - create( interWith2Fields, properttyBasedValueSource( "test2.label", "zz" ) ); - assertEquals( "pdominantANDx", joined.interpolate( EXPR2 ) ); + FixedStringSearchInterpolator joined = create(interWith2Fields, properttyBasedValueSource("test2.label", "zz")); + assertEquals("pdominantANDx", joined.interpolate(EXPR2)); } @Test - void unresolable_linked() - { + void unresolable_linked() { final String EXPR2 = "${test.label}${test2.label}AND${test2}"; FixedStringSearchInterpolator interWith2Fields = - create( properttyBasedValueSource( "test.label", "p", "test2", "x", "test2.label", "dominant" ) ); + create(properttyBasedValueSource("test.label", "p", "test2", "x", "test2.label", "dominant")); - FixedStringSearchInterpolator joined = - create( interWith2Fields, properttyBasedValueSource( "test2.label", "zz" ) ); - assertEquals( "pdominantANDx", joined.interpolate( EXPR2 ) ); + FixedStringSearchInterpolator joined = create(interWith2Fields, properttyBasedValueSource("test2.label", "zz")); + assertEquals("pdominantANDx", joined.interpolate(EXPR2)); } @Test - void testCyclesWithLinked() - { - assertThrows( InterpolationCycleException.class, () -> { - FixedStringSearchInterpolator first = create( properttyBasedValueSource( "key1", "${key2}" ) ); - FixedStringSearchInterpolator second = create( first, properttyBasedValueSource( "key2", "${key1}" ) ); - second.interpolate( "${key2}" ); - } ); + void testCyclesWithLinked() { + assertThrows(InterpolationCycleException.class, () -> { + FixedStringSearchInterpolator first = create(properttyBasedValueSource("key1", "${key2}")); + FixedStringSearchInterpolator second = create(first, properttyBasedValueSource("key2", "${key1}")); + second.interpolate("${key2}"); + }); } @Test - void testCyclesWithLinked_betweenRootAndOther() - { - assertThrows( InterpolationCycleException.class, () -> { - FixedStringSearchInterpolator first = create( properttyBasedValueSource( "key1", "${key2}" ) ); - FixedStringSearchInterpolator second = create( first, properttyBasedValueSource( "key2", "${key1}" ) ); - second.interpolate( "${key1}" ); - } ); + void testCyclesWithLinked_betweenRootAndOther() { + assertThrows(InterpolationCycleException.class, () -> { + FixedStringSearchInterpolator first = create(properttyBasedValueSource("key1", "${key2}")); + FixedStringSearchInterpolator second = create(first, properttyBasedValueSource("key2", "${key1}")); + second.interpolate("${key1}"); + }); } @Test - void fixedInjectedIntoRegular() - throws InterpolationException - { - FixedStringSearchInterpolator first = create( properttyBasedValueSource( "key1", "v1" ) ); + void fixedInjectedIntoRegular() throws InterpolationException { + FixedStringSearchInterpolator first = create(properttyBasedValueSource("key1", "v1")); Properties p = new Properties(); - p.setProperty( "key", "X" ); - StringSearchInterpolator interpolator = new StringSearchInterpolator( "${", "}" ); - interpolator.setEscapeString( "\\" ); - interpolator.addValueSource( new org.codehaus.plexus.interpolation.PropertiesBasedValueSource( p ) ); - interpolator.addValueSource( new FixedInterpolatorValueSource( first ) ); - assertEquals("v1X", interpolator.interpolate( "${key1}${key}" )); - + p.setProperty("key", "X"); + StringSearchInterpolator interpolator = new StringSearchInterpolator("${", "}"); + interpolator.setEscapeString("\\"); + interpolator.addValueSource(new org.codehaus.plexus.interpolation.PropertiesBasedValueSource(p)); + interpolator.addValueSource(new FixedInterpolatorValueSource(first)); + assertEquals("v1X", interpolator.interpolate("${key1}${key}")); } - private PropertiesBasedValueSource properttyBasedValueSource( String... values ) - { + private PropertiesBasedValueSource properttyBasedValueSource(String... values) { Properties p = new Properties(); - for ( int i = 0; i < values.length; i += 2 ) - { - p.setProperty( values[i], values[i + 1] ); + for (int i = 0; i < values.length; i += 2) { + p.setProperty(values[i], values[i + 1]); } - return new PropertiesBasedValueSource( p ); + return new PropertiesBasedValueSource(p); } } - diff --git a/src/test/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterInterpolatorFilterReaderTest.java b/src/test/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterInterpolatorFilterReaderTest.java index 98190b2..95ab97d 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterInterpolatorFilterReaderTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterInterpolatorFilterReaderTest.java @@ -24,6 +24,12 @@ * SOFTWARE. */ +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import org.codehaus.plexus.interpolation.Interpolator; import org.codehaus.plexus.interpolation.MapBasedValueSource; import org.codehaus.plexus.interpolation.PrefixAwareRecursionInterceptor; @@ -31,361 +37,309 @@ import org.codehaus.plexus.interpolation.StringSearchInterpolator; import org.junit.jupiter.api.Test; -import java.io.StringReader; - import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; /** * InterpolatorFilterReaderTest, heavily based on InterpolationFilterReaderTest. Heh, even the test strings remained the * same! - * + * * @author cstamas - * + * */ -public class MultiDelimiterInterpolatorFilterReaderTest -{ +public class MultiDelimiterInterpolatorFilterReaderTest { /* * Added and commented by jdcasey@03-Feb-2005 because it is a bug in the InterpolationFilterReader. * kenneyw@15-04-2005 fixed the bug. */ @Test - public void testShouldNotInterpolateExpressionAtEndOfDataWithInvalidEndToken() - throws Exception - { + public void testShouldNotInterpolateExpressionAtEndOfDataWithInvalidEndToken() throws Exception { Map m = new HashMap(); - m.put( "test", "TestValue" ); + m.put("test", "TestValue"); String testStr = "This is a ${test"; - assertEquals( "This is a ${test", interpolate( testStr, m ) ); + assertEquals("This is a ${test", interpolate(testStr, m)); } /* * kenneyw@14-04-2005 Added test to check above fix. */ @Test - public void testShouldNotInterpolateExpressionWithMissingEndToken() - throws Exception - { + public void testShouldNotInterpolateExpressionWithMissingEndToken() throws Exception { Map m = new HashMap(); - m.put( "test", "TestValue" ); + m.put("test", "TestValue"); String testStr = "This is a ${test, really"; - assertEquals( "This is a ${test, really", interpolate( testStr, m ) ); + assertEquals("This is a ${test, really", interpolate(testStr, m)); } @Test - public void testShouldNotInterpolateWithMalformedStartToken() - throws Exception - { + public void testShouldNotInterpolateWithMalformedStartToken() throws Exception { Map m = new HashMap(); - m.put( "test", "testValue" ); + m.put("test", "testValue"); String foo = "This is a $!test} again"; - assertEquals( "This is a $!test} again", interpolate( foo, m ) ); + assertEquals("This is a $!test} again", interpolate(foo, m)); } @Test - public void testShouldNotInterpolateWithMalformedEndToken() - throws Exception - { + public void testShouldNotInterpolateWithMalformedEndToken() throws Exception { Map m = new HashMap(); - m.put( "test", "testValue" ); + m.put("test", "testValue"); String foo = "This is a ${test!} again"; - assertEquals( "This is a ${test!} again", interpolate( foo, m ) ); + assertEquals("This is a ${test!} again", interpolate(foo, m)); } @Test - public void testDefaultInterpolationWithNonInterpolatedValueAtEnd() - throws Exception - { + public void testDefaultInterpolationWithNonInterpolatedValueAtEnd() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "${name} is an ${noun}. ${not.interpolated}"; - assertEquals( "jason is an asshole. ${not.interpolated}", interpolate( foo, m ) ); + assertEquals("jason is an asshole. ${not.interpolated}", interpolate(foo, m)); } @Test - public void testDefaultInterpolationWithInterpolatedValueAtEnd() - throws Exception - { + public void testDefaultInterpolationWithInterpolatedValueAtEnd() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "${name} is an ${noun}"; - assertEquals( "jason is an asshole", interpolate( foo, m ) ); + assertEquals("jason is an asshole", interpolate(foo, m)); } @Test - public void testInterpolationWithInterpolatedValueAtEndWithCustomToken() - throws Exception - { + public void testInterpolationWithInterpolatedValueAtEndWithCustomToken() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "@{name} is an @{noun}"; - assertEquals( "jason is an asshole", interpolate( foo, m, "@{", "}" ) ); + assertEquals("jason is an asshole", interpolate(foo, m, "@{", "}")); } @Test - public void testInterpolationWithInterpolatedValueAtEndWithCustomTokenAndCustomString() - throws Exception - { + public void testInterpolationWithInterpolatedValueAtEndWithCustomTokenAndCustomString() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "@name@ is an @noun@"; - assertEquals( "jason is an asshole", interpolate( foo, m, "@", "@" ) ); + assertEquals("jason is an asshole", interpolate(foo, m, "@", "@")); } @Test - public void testEscape() - throws Exception - { + public void testEscape() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "${name} is an \\${noun}"; - assertEquals( "jason is an ${noun}", interpolate( foo, m, "\\" ) ); + assertEquals("jason is an ${noun}", interpolate(foo, m, "\\")); } @Test - public void testEscapeAtStart() - throws Exception - { + public void testEscapeAtStart() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "\\${name} is an \\${noun}"; - assertEquals( "${name} is an ${noun}", interpolate( foo, m, "\\" ) ); + assertEquals("${name} is an ${noun}", interpolate(foo, m, "\\")); } @Test - public void testEscapeOnlyAtStart() - throws Exception - { + public void testEscapeOnlyAtStart() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "\\@name@ is an @noun@"; - String result = interpolate( foo, m, "@", "@" ); - assertEquals( "@name@ is an asshole", result ); + String result = interpolate(foo, m, "@", "@"); + assertEquals("@name@ is an asshole", result); } @Test - public void testEscapeOnlyAtStartDefaultToken() - throws Exception - { + public void testEscapeOnlyAtStartDefaultToken() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "noun", "asshole" ); + m.put("name", "jason"); + m.put("noun", "asshole"); String foo = "\\${name} is an ${noun}"; - String result = interpolate( foo, m, "${", "}" ); - assertEquals( "${name} is an asshole", result ); + String result = interpolate(foo, m, "${", "}"); + assertEquals("${name} is an asshole", result); } @Test - public void testShouldDetectRecursiveExpressionPassingThroughTwoPrefixes() - throws Exception - { + public void testShouldDetectRecursiveExpressionPassingThroughTwoPrefixes() throws Exception { List prefixes = new ArrayList(); - prefixes.add( "prefix1" ); - prefixes.add( "prefix2" ); + prefixes.add("prefix1"); + prefixes.add("prefix2"); - RecursionInterceptor ri = new PrefixAwareRecursionInterceptor( prefixes, false ); + RecursionInterceptor ri = new PrefixAwareRecursionInterceptor(prefixes, false); Map context = new HashMap(); - context.put( "name", "${prefix2.name}" ); + context.put("name", "${prefix2.name}"); String input = "${prefix1.name}"; StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new MapBasedValueSource( context ) ); + interpolator.addValueSource(new MapBasedValueSource(context)); - MultiDelimiterInterpolatorFilterReader r = new MultiDelimiterInterpolatorFilterReader( new StringReader( input ), - interpolator, ri ); - r.setInterpolateWithPrefixPattern( false ); - r.setEscapeString( "\\" ); + MultiDelimiterInterpolatorFilterReader r = + new MultiDelimiterInterpolatorFilterReader(new StringReader(input), interpolator, ri); + r.setInterpolateWithPrefixPattern(false); + r.setEscapeString("\\"); StringBuilder buf = new StringBuilder(); int read = -1; char[] cbuf = new char[1024]; - while ( ( read = r.read( cbuf ) ) > -1 ) - { - buf.append( cbuf, 0, read ); + while ((read = r.read(cbuf)) > -1) { + buf.append(cbuf, 0, read); } - assertEquals( input, buf.toString() ); + assertEquals(input, buf.toString()); } @Test - public void testShouldDetectRecursiveExpressionWithPrefixAndWithout() - throws Exception - { + public void testShouldDetectRecursiveExpressionWithPrefixAndWithout() throws Exception { List prefixes = new ArrayList(); - prefixes.add( "prefix1" ); + prefixes.add("prefix1"); - RecursionInterceptor ri = new PrefixAwareRecursionInterceptor( prefixes, false ); + RecursionInterceptor ri = new PrefixAwareRecursionInterceptor(prefixes, false); Map context = new HashMap(); - context.put( "name", "${prefix1.name}" ); + context.put("name", "${prefix1.name}"); String input = "${name}"; StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new MapBasedValueSource( context ) ); + interpolator.addValueSource(new MapBasedValueSource(context)); - MultiDelimiterInterpolatorFilterReader r = new MultiDelimiterInterpolatorFilterReader( new StringReader( input ), - interpolator, ri ); - r.setInterpolateWithPrefixPattern( false ); - r.setEscapeString( "\\" ); + MultiDelimiterInterpolatorFilterReader r = + new MultiDelimiterInterpolatorFilterReader(new StringReader(input), interpolator, ri); + r.setInterpolateWithPrefixPattern(false); + r.setEscapeString("\\"); StringBuilder buf = new StringBuilder(); int read = -1; char[] cbuf = new char[1024]; - while ( ( read = r.read( cbuf ) ) > -1 ) - { - buf.append( cbuf, 0, read ); + while ((read = r.read(cbuf)) > -1) { + buf.append(cbuf, 0, read); } - assertEquals( "${prefix1.name}", buf.toString() ); + assertEquals("${prefix1.name}", buf.toString()); } @Test - public void testInterpolationWithMultipleTokenTypes() - throws Exception - { + public void testInterpolationWithMultipleTokenTypes() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "otherName", "@name@" ); + m.put("name", "jason"); + m.put("otherName", "@name@"); String foo = "${otherName}"; - assertEquals( "jason", interpolateMulti( foo, m, new String[] { "${*}", "@*@" } ) ); + assertEquals("jason", interpolateMulti(foo, m, new String[] {"${*}", "@*@"})); } @Test - public void testInterpolationWithMultipleTokenTypes_ReversedOrdering() - throws Exception - { + public void testInterpolationWithMultipleTokenTypes_ReversedOrdering() throws Exception { Map m = new HashMap(); - m.put( "name", "jason" ); - m.put( "otherName", "${name}" ); + m.put("name", "jason"); + m.put("otherName", "${name}"); String foo = "@otherName@"; - assertEquals( "jason", interpolateMulti( foo, m, new String[] { "${*}", "@*@" } ) ); + assertEquals("jason", interpolateMulti(foo, m, new String[] {"${*}", "@*@"})); } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- - private String interpolate( String input, Map context ) - throws Exception - { - return interpolate( input, context, null ); + private String interpolate(String input, Map context) throws Exception { + return interpolate(input, context, null); } - private String interpolate( String input, Map context, String escapeStr ) - throws Exception - { + private String interpolate(String input, Map context, String escapeStr) throws Exception { Interpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new MapBasedValueSource( context ) ); + interpolator.addValueSource(new MapBasedValueSource(context)); - MultiDelimiterInterpolatorFilterReader r = new MultiDelimiterInterpolatorFilterReader( new StringReader( input ), interpolator ); - r.setInterpolateWithPrefixPattern( false ); - if ( escapeStr != null ) - { - r.setEscapeString( escapeStr ); + MultiDelimiterInterpolatorFilterReader r = + new MultiDelimiterInterpolatorFilterReader(new StringReader(input), interpolator); + r.setInterpolateWithPrefixPattern(false); + if (escapeStr != null) { + r.setEscapeString(escapeStr); } StringBuilder buf = new StringBuilder(); int read = -1; char[] cbuf = new char[1024]; - while ( ( read = r.read( cbuf ) ) > -1 ) - { - buf.append( cbuf, 0, read ); + while ((read = r.read(cbuf)) > -1) { + buf.append(cbuf, 0, read); } return buf.toString(); } - private String interpolate( String input, Map context, String beginToken, String endToken ) - throws Exception - { - StringSearchInterpolator interpolator = new StringSearchInterpolator( beginToken, endToken ); + private String interpolate(String input, Map context, String beginToken, String endToken) throws Exception { + StringSearchInterpolator interpolator = new StringSearchInterpolator(beginToken, endToken); - interpolator.addValueSource( new MapBasedValueSource( context ) ); + interpolator.addValueSource(new MapBasedValueSource(context)); - MultiDelimiterInterpolatorFilterReader r = new MultiDelimiterInterpolatorFilterReader( new StringReader( input ), interpolator ); - r.addDelimiterSpec( beginToken + "*" + endToken ); + MultiDelimiterInterpolatorFilterReader r = + new MultiDelimiterInterpolatorFilterReader(new StringReader(input), interpolator); + r.addDelimiterSpec(beginToken + "*" + endToken); - r.setInterpolateWithPrefixPattern( false ); - r.setEscapeString( "\\" ); + r.setInterpolateWithPrefixPattern(false); + r.setEscapeString("\\"); StringBuilder buf = new StringBuilder(); int read = -1; char[] cbuf = new char[1024]; - while ( ( read = r.read( cbuf ) ) > -1 ) - { - buf.append( cbuf, 0, read ); + while ((read = r.read(cbuf)) > -1) { + buf.append(cbuf, 0, read); } return buf.toString(); } - private String interpolateMulti( String input, Map context, String[] specs ) - throws Exception - { + private String interpolateMulti(String input, Map context, String[] specs) throws Exception { MultiDelimiterStringSearchInterpolator interp = new MultiDelimiterStringSearchInterpolator(); - interp.addValueSource( new MapBasedValueSource( context ) ); + interp.addValueSource(new MapBasedValueSource(context)); - MultiDelimiterInterpolatorFilterReader r = new MultiDelimiterInterpolatorFilterReader( new StringReader( input ), interp ); + MultiDelimiterInterpolatorFilterReader r = + new MultiDelimiterInterpolatorFilterReader(new StringReader(input), interp); - for ( String spec : specs ) - { - interp.addDelimiterSpec( spec ); - r.addDelimiterSpec( spec ); + for (String spec : specs) { + interp.addDelimiterSpec(spec); + r.addDelimiterSpec(spec); } - r.setInterpolateWithPrefixPattern( false ); - r.setEscapeString( "\\" ); + r.setInterpolateWithPrefixPattern(false); + r.setEscapeString("\\"); StringBuilder buf = new StringBuilder(); int read = -1; char[] cbuf = new char[1024]; - while ( ( read = r.read( cbuf ) ) > -1 ) - { - buf.append( cbuf, 0, read ); + while ((read = r.read(cbuf)) > -1) { + buf.append(cbuf, 0, read); } return buf.toString(); } - } diff --git a/src/test/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterStringSearchInterpolatorTest.java b/src/test/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterStringSearchInterpolatorTest.java index 4d4cdc8..2c5fe2f 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterStringSearchInterpolatorTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/multi/MultiDelimiterStringSearchInterpolatorTest.java @@ -16,115 +16,107 @@ * limitations under the License. */ +import java.util.HashMap; +import java.util.Map; + import org.codehaus.plexus.interpolation.InterpolationException; import org.codehaus.plexus.interpolation.MapBasedValueSource; import org.codehaus.plexus.interpolation.ValueSource; import org.junit.jupiter.api.Test; -import java.util.HashMap; -import java.util.Map; - import static org.junit.jupiter.api.Assertions.assertEquals; -public class MultiDelimiterStringSearchInterpolatorTest -{ +public class MultiDelimiterStringSearchInterpolatorTest { @Test - public void testInterpolationWithDifferentDelimiters() - throws InterpolationException - { + public void testInterpolationWithDifferentDelimiters() throws InterpolationException { Map ctx = new HashMap(); - ctx.put( "name", "User" ); - ctx.put( "otherName", "@name@" ); + ctx.put("name", "User"); + ctx.put("otherName", "@name@"); String input = "${otherName}"; - ValueSource vs = new MapBasedValueSource( ctx ); - MultiDelimiterStringSearchInterpolator interpolator = new MultiDelimiterStringSearchInterpolator().addDelimiterSpec( "@" ) - .withValueSource( vs ); + ValueSource vs = new MapBasedValueSource(ctx); + MultiDelimiterStringSearchInterpolator interpolator = new MultiDelimiterStringSearchInterpolator() + .addDelimiterSpec("@") + .withValueSource(vs); - String result = interpolator.interpolate( input ); + String result = interpolator.interpolate(input); - assertEquals( ctx.get( "name" ), result ); + assertEquals(ctx.get("name"), result); } @Test public void testSuccessiveInterpolationWithDifferentDelimiters_ReversedDelimiterSequence() - throws InterpolationException - { + throws InterpolationException { Map ctx = new HashMap(); - ctx.put( "name", "User" ); - ctx.put( "otherName", "${name}" ); + ctx.put("name", "User"); + ctx.put("otherName", "${name}"); String input = "@otherName@"; - ValueSource vs = new MapBasedValueSource( ctx ); - MultiDelimiterStringSearchInterpolator interpolator = new MultiDelimiterStringSearchInterpolator().addDelimiterSpec( "@" ) - .withValueSource( vs ); + ValueSource vs = new MapBasedValueSource(ctx); + MultiDelimiterStringSearchInterpolator interpolator = new MultiDelimiterStringSearchInterpolator() + .addDelimiterSpec("@") + .withValueSource(vs); - String result = interpolator.interpolate( input ); + String result = interpolator.interpolate(input); - assertEquals( ctx.get( "name" ), result ); + assertEquals(ctx.get("name"), result); } @Test - public void testInterpolationWithMultipleEscapes() - throws InterpolationException - { - Map ctx = new HashMap(); - ctx.put( "name", "User" ); - ctx.put( "otherName", "##${first} and #${last}" ); + public void testInterpolationWithMultipleEscapes() throws InterpolationException { + Map ctx = new HashMap(); + ctx.put("name", "User"); + ctx.put("otherName", "##${first} and #${last}"); - String input = "${otherName}"; + String input = "${otherName}"; - ValueSource vs = new MapBasedValueSource( ctx ); - MultiDelimiterStringSearchInterpolator interpolator = new MultiDelimiterStringSearchInterpolator() - .withValueSource( vs ); - interpolator.setEscapeString("#"); + ValueSource vs = new MapBasedValueSource(ctx); + MultiDelimiterStringSearchInterpolator interpolator = + new MultiDelimiterStringSearchInterpolator().withValueSource(vs); + interpolator.setEscapeString("#"); - String result = interpolator.interpolate( input ); + String result = interpolator.interpolate(input); - assertEquals( "#${first} and ${last}", result ); - } + assertEquals("#${first} and ${last}", result); + } @Test - public void testInterpolationWithMultipleEscapes2() - throws InterpolationException - { + public void testInterpolationWithMultipleEscapes2() throws InterpolationException { Map ctx = new HashMap(); - ctx.put( "name", "User" ); - ctx.put( "otherName", "#${first} and ##${last}" ); + ctx.put("name", "User"); + ctx.put("otherName", "#${first} and ##${last}"); String input = "${otherName}"; - ValueSource vs = new MapBasedValueSource( ctx ); + ValueSource vs = new MapBasedValueSource(ctx); MultiDelimiterStringSearchInterpolator interpolator = - new MultiDelimiterStringSearchInterpolator().withValueSource( vs ); - interpolator.setEscapeString( "#" ); + new MultiDelimiterStringSearchInterpolator().withValueSource(vs); + interpolator.setEscapeString("#"); - String result = interpolator.interpolate( input ); + String result = interpolator.interpolate(input); - assertEquals( "${first} and #${last}", result ); + assertEquals("${first} and #${last}", result); } @Test - public void testInterpolationWithMultipleEscapes3() - throws InterpolationException - { + public void testInterpolationWithMultipleEscapes3() throws InterpolationException { Map ctx = new HashMap(); - ctx.put( "name", "User" ); - ctx.put( "last", "beer" ); - ctx.put( "otherName", "###${first} and ##${second} and ${last}" ); + ctx.put("name", "User"); + ctx.put("last", "beer"); + ctx.put("otherName", "###${first} and ##${second} and ${last}"); String input = "${otherName}"; - ValueSource vs = new MapBasedValueSource( ctx ); + ValueSource vs = new MapBasedValueSource(ctx); MultiDelimiterStringSearchInterpolator interpolator = new MultiDelimiterStringSearchInterpolator() // - .withValueSource( vs ) // - .escapeString( "#" ); + .withValueSource(vs) // + .escapeString("#"); - String result = interpolator.interpolate( input ); + String result = interpolator.interpolate(input); - assertEquals( "##${first} and #${second} and beer", result ); + assertEquals("##${first} and #${second} and beer", result); } } diff --git a/src/test/java/org/codehaus/plexus/interpolation/object/FieldBasedObjectInterpolatorTest.java b/src/test/java/org/codehaus/plexus/interpolation/object/FieldBasedObjectInterpolatorTest.java index 57d6e96..08c8ad8 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/object/FieldBasedObjectInterpolatorTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/object/FieldBasedObjectInterpolatorTest.java @@ -16,8 +16,6 @@ * limitations under the License. */ -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -29,261 +27,236 @@ import org.codehaus.plexus.interpolation.StringSearchInterpolator; import org.junit.jupiter.api.Test; -public class FieldBasedObjectInterpolatorTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class FieldBasedObjectInterpolatorTest { @Test - public void testInterpolateStringArray() - throws Exception - { + public void testInterpolateStringArray() throws Exception { Properties p = new Properties(); - p.setProperty( "key", "value" ); - p.setProperty( "key2", "value2" ); + p.setProperty("key", "value"); + p.setProperty("key2", "value2"); - String[] values = { "${key}", "${key2}" }; + String[] values = {"${key}", "${key2}"}; StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - new FieldBasedObjectInterpolator().interpolate( values, interpolator ); + new FieldBasedObjectInterpolator().interpolate(values, interpolator); - assertEquals( "value", values[0] ); - assertEquals( "value2", values[1] ); + assertEquals("value", values[0]); + assertEquals("value2", values[1]); } @Test - public void testInterpolateObjectWithStringArrayField() - throws Exception - { + public void testInterpolateObjectWithStringArrayField() throws Exception { Properties p = new Properties(); - p.setProperty( "key", "value" ); - p.setProperty( "key2", "value2" ); + p.setProperty("key", "value"); + p.setProperty("key2", "value2"); - String[] values = { "${key}", "${key2}" }; + String[] values = {"${key}", "${key2}"}; - ObjectWithStringArrayField obj = new ObjectWithStringArrayField( values ); + ObjectWithStringArrayField obj = new ObjectWithStringArrayField(values); StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - new FieldBasedObjectInterpolator().interpolate( obj, interpolator ); + new FieldBasedObjectInterpolator().interpolate(obj, interpolator); - assertEquals( "value", obj.values[0] ); - assertEquals( "value2", obj.values[1] ); + assertEquals("value", obj.values[0]); + assertEquals("value2", obj.values[1]); } @Test - public void testInterpolateObjectWithStringListField() - throws Exception - { + public void testInterpolateObjectWithStringListField() throws Exception { Properties p = new Properties(); - p.setProperty( "key", "value" ); - p.setProperty( "key2", "value2" ); + p.setProperty("key", "value"); + p.setProperty("key2", "value2"); List values = new ArrayList(); - values.add( "${key}" ); - values.add( "${key2}" ); + values.add("${key}"); + values.add("${key2}"); - ObjectWithListField obj = new ObjectWithListField( values ); + ObjectWithListField obj = new ObjectWithListField(values); StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - new FieldBasedObjectInterpolator().interpolate( obj, interpolator ); + new FieldBasedObjectInterpolator().interpolate(obj, interpolator); - assertEquals( "value", obj.values.get( 0 ) ); - assertEquals( "value2", obj.values.get( 1 ) ); + assertEquals("value", obj.values.get(0)); + assertEquals("value2", obj.values.get(1)); } @Test - public void testInterpolateObjectWithStringListFieldAndOneLiteralValue() - throws Exception - { + public void testInterpolateObjectWithStringListFieldAndOneLiteralValue() throws Exception { Properties p = new Properties(); - p.setProperty( "key", "value" ); - p.setProperty( "key2", "value2" ); + p.setProperty("key", "value"); + p.setProperty("key2", "value2"); List values = new ArrayList(); - values.add( "key" ); - values.add( "${key2}" ); + values.add("key"); + values.add("${key2}"); - ObjectWithListField obj = new ObjectWithListField( values ); + ObjectWithListField obj = new ObjectWithListField(values); StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - new FieldBasedObjectInterpolator().interpolate( obj, interpolator ); + new FieldBasedObjectInterpolator().interpolate(obj, interpolator); - assertEquals( "key", obj.values.get( 0 ) ); - assertEquals( "value2", obj.values.get( 1 ) ); + assertEquals("key", obj.values.get(0)); + assertEquals("value2", obj.values.get(1)); } @Test - public void testInterpolateObjectWithUnmodifiableStringListField() - throws Exception - { + public void testInterpolateObjectWithUnmodifiableStringListField() throws Exception { Properties p = new Properties(); - p.setProperty( "key", "value" ); - p.setProperty( "key2", "value2" ); + p.setProperty("key", "value"); + p.setProperty("key2", "value2"); - List values = Collections.unmodifiableList( Collections.singletonList( "${key}" ) ); + List values = Collections.unmodifiableList(Collections.singletonList("${key}")); - ObjectWithListField obj = new ObjectWithListField( values ); + ObjectWithListField obj = new ObjectWithListField(values); StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - new FieldBasedObjectInterpolator().interpolate( obj, interpolator ); + new FieldBasedObjectInterpolator().interpolate(obj, interpolator); - assertEquals( "${key}", obj.values.get( 0 ) ); + assertEquals("${key}", obj.values.get(0)); } @Test - public void testInterpolateObjectWithStringArrayListField() - throws Exception - { + public void testInterpolateObjectWithStringArrayListField() throws Exception { Properties p = new Properties(); - p.setProperty( "key", "value" ); - p.setProperty( "key2", "value2" ); - p.setProperty( "key3", "value3" ); - p.setProperty( "key4", "value4" ); + p.setProperty("key", "value"); + p.setProperty("key2", "value2"); + p.setProperty("key3", "value3"); + p.setProperty("key4", "value4"); List values = new ArrayList(); - values.add( new String[] { "${key}", "${key2}" } ); - values.add( new String[] { "${key3}", "${key4}" } ); + values.add(new String[] {"${key}", "${key2}"}); + values.add(new String[] {"${key3}", "${key4}"}); - ObjectWithListField obj = new ObjectWithListField( values ); + ObjectWithListField obj = new ObjectWithListField(values); StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - new FieldBasedObjectInterpolator().interpolate( obj, interpolator ); + new FieldBasedObjectInterpolator().interpolate(obj, interpolator); - assertEquals( "value", ( (String[]) obj.values.get( 0 ) )[0] ); - assertEquals( "value2", ( (String[]) obj.values.get( 0 ) )[1] ); - assertEquals( "value3", ( (String[]) obj.values.get( 1 ) )[0] ); - assertEquals( "value4", ( (String[]) obj.values.get( 1 ) )[1] ); + assertEquals("value", ((String[]) obj.values.get(0))[0]); + assertEquals("value2", ((String[]) obj.values.get(0))[1]); + assertEquals("value3", ((String[]) obj.values.get(1))[0]); + assertEquals("value4", ((String[]) obj.values.get(1))[1]); } @Test - public void testInterpolateObjectWithStringToStringMapField() - throws Exception - { + public void testInterpolateObjectWithStringToStringMapField() throws Exception { Properties p = new Properties(); - p.setProperty( "key", "value" ); - p.setProperty( "key2", "value2" ); + p.setProperty("key", "value"); + p.setProperty("key2", "value2"); - Map values = new HashMap(); - values.put( "key", "${key}" ); - values.put( "key2", "${key2}" ); + Map values = new HashMap(); + values.put("key", "${key}"); + values.put("key2", "${key2}"); - ObjectWithMapField obj = new ObjectWithMapField( values ); + ObjectWithMapField obj = new ObjectWithMapField(values); StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - new FieldBasedObjectInterpolator().interpolate( obj, interpolator ); + new FieldBasedObjectInterpolator().interpolate(obj, interpolator); - assertEquals( "value", obj.values.get( "key" ) ); - assertEquals( "value2", obj.values.get( "key2" ) ); + assertEquals("value", obj.values.get("key")); + assertEquals("value2", obj.values.get("key2")); } @Test - public void testInterpolateObjectWithStringToStringMapFieldAndOneLiteralValue() - throws Exception - { + public void testInterpolateObjectWithStringToStringMapFieldAndOneLiteralValue() throws Exception { Properties p = new Properties(); - p.setProperty( "key", "value" ); - p.setProperty( "key2", "value2" ); + p.setProperty("key", "value"); + p.setProperty("key2", "value2"); - Map values = new HashMap(); - values.put( "key", "val" ); - values.put( "key2", "${key2}" ); + Map values = new HashMap(); + values.put("key", "val"); + values.put("key2", "${key2}"); - ObjectWithMapField obj = new ObjectWithMapField( values ); + ObjectWithMapField obj = new ObjectWithMapField(values); StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - new FieldBasedObjectInterpolator().interpolate( obj, interpolator ); + new FieldBasedObjectInterpolator().interpolate(obj, interpolator); - assertEquals( "val", obj.values.get( "key" ) ); - assertEquals( "value2", obj.values.get( "key2" ) ); + assertEquals("val", obj.values.get("key")); + assertEquals("value2", obj.values.get("key2")); } @Test - public void testInterpolateObjectWithUnmodifiableStringToStringMapField() - throws Exception - { + public void testInterpolateObjectWithUnmodifiableStringToStringMapField() throws Exception { Properties p = new Properties(); - p.setProperty( "key", "value" ); - p.setProperty( "key2", "value2" ); + p.setProperty("key", "value"); + p.setProperty("key2", "value2"); - Map values = Collections.unmodifiableMap( Collections.singletonMap( "key", "${key}" ) ); + Map values = Collections.unmodifiableMap(Collections.singletonMap("key", "${key}")); - ObjectWithMapField obj = new ObjectWithMapField( values ); + ObjectWithMapField obj = new ObjectWithMapField(values); StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - new FieldBasedObjectInterpolator().interpolate( obj, interpolator ); + new FieldBasedObjectInterpolator().interpolate(obj, interpolator); - assertEquals( "${key}", obj.values.get( "key" ) ); + assertEquals("${key}", obj.values.get("key")); } @Test - public void testInterpolateObjectWithStringToStringArrayMapField() - throws Exception - { + public void testInterpolateObjectWithStringToStringArrayMapField() throws Exception { Properties p = new Properties(); - p.setProperty( "key", "value" ); - p.setProperty( "key2", "value2" ); - p.setProperty( "key3", "value3" ); - p.setProperty( "key4", "value4" ); + p.setProperty("key", "value"); + p.setProperty("key2", "value2"); + p.setProperty("key3", "value3"); + p.setProperty("key4", "value4"); - Map values = new HashMap(); - values.put( "key", new String[] { "${key}", "${key2}" } ); - values.put( "key2", new String[] { "${key3}", "${key4}" } ); + Map values = new HashMap(); + values.put("key", new String[] {"${key}", "${key2}"}); + values.put("key2", new String[] {"${key3}", "${key4}"}); - ObjectWithMapField obj = new ObjectWithMapField( values ); + ObjectWithMapField obj = new ObjectWithMapField(values); StringSearchInterpolator interpolator = new StringSearchInterpolator(); - interpolator.addValueSource( new PropertiesBasedValueSource( p ) ); + interpolator.addValueSource(new PropertiesBasedValueSource(p)); - new FieldBasedObjectInterpolator().interpolate( obj, interpolator ); + new FieldBasedObjectInterpolator().interpolate(obj, interpolator); - assertEquals( "value", ( (String[]) obj.values.get( "key" ) )[0] ); - assertEquals( "value2", ( (String[]) obj.values.get( "key" ) )[1] ); - assertEquals( "value3", ( (String[]) obj.values.get( "key2" ) )[0] ); - assertEquals( "value4", ( (String[]) obj.values.get( "key2" ) )[1] ); + assertEquals("value", ((String[]) obj.values.get("key"))[0]); + assertEquals("value2", ((String[]) obj.values.get("key"))[1]); + assertEquals("value3", ((String[]) obj.values.get("key2"))[0]); + assertEquals("value4", ((String[]) obj.values.get("key2"))[1]); } - private static final class ObjectWithStringArrayField - { + private static final class ObjectWithStringArrayField { private final String[] values; - public ObjectWithStringArrayField( String[] values ) - { + public ObjectWithStringArrayField(String[] values) { this.values = values; } } - private static final class ObjectWithListField - { + private static final class ObjectWithListField { private final List values; - public ObjectWithListField( List values ) - { + public ObjectWithListField(List values) { this.values = values; } } - private static final class ObjectWithMapField - { + private static final class ObjectWithMapField { private final Map values; - public ObjectWithMapField( Map values ) - { + public ObjectWithMapField(Map values) { this.values = values; } } diff --git a/src/test/java/org/codehaus/plexus/interpolation/util/StringUtilsTest.java b/src/test/java/org/codehaus/plexus/interpolation/util/StringUtilsTest.java index cfc17ce..d788f63 100644 --- a/src/test/java/org/codehaus/plexus/interpolation/util/StringUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/interpolation/util/StringUtilsTest.java @@ -15,18 +15,15 @@ * limitations under the License. */ -import static org.junit.jupiter.api.Assertions.assertEquals; - import org.junit.jupiter.api.Test; -public class StringUtilsTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class StringUtilsTest { @Test - public void testCapitalizeFirstLetter() - throws Exception - { - assertEquals( "Abc", StringUtils.capitalizeFirstLetter( "abc" ) ); - assertEquals( "\u00cdce", StringUtils.capitalizeFirstLetter( "\u00edce" ) ); - assertEquals( "X", StringUtils.capitalizeFirstLetter( "x" ) ); + public void testCapitalizeFirstLetter() throws Exception { + assertEquals("Abc", StringUtils.capitalizeFirstLetter("abc")); + assertEquals("\u00cdce", StringUtils.capitalizeFirstLetter("\u00edce")); + assertEquals("X", StringUtils.capitalizeFirstLetter("x")); } }