Give more power to StrSubstitutor subclasses

git-svn-id: https://svn.apache.org/repos/asf/jakarta/commons/proper/lang/trunk@429507 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Stephen Colebourne 2006-08-07 23:06:41 +00:00
parent 9c66638127
commit 927e736103
2 changed files with 86 additions and 56 deletions

View File

@ -126,8 +126,8 @@ public class StrSubstitutor {
* Replaces all the occurrences of variables in the given source object with * Replaces all the occurrences of variables in the given source object with
* their matching values from the map. * their matching values from the map.
* *
* @param source the source text containing the variables to substitute * @param source the source text containing the variables to substitute, null returns null
* @param valueMap the map with the values * @param valueMap the map with the values, may be null
* @return the result of the replace operation * @return the result of the replace operation
*/ */
public static String replace(Object source, Map valueMap) { public static String replace(Object source, Map valueMap) {
@ -139,11 +139,12 @@ public class StrSubstitutor {
* their matching values from the map. This method allows to specifiy a * their matching values from the map. This method allows to specifiy a
* custom variable prefix and suffix * custom variable prefix and suffix
* *
* @param source the source text containing the variables to substitute * @param source the source text containing the variables to substitute, null returns null
* @param valueMap the map with the values * @param valueMap the map with the values, may be null
* @param prefix the prefix of variables * @param prefix the prefix of variables, not null
* @param suffix the suffix of variables * @param suffix the suffix of variables, not null
* @return the result of the replace operation * @return the result of the replace operation
* @throws IllegalArgumentException if the prefix or suffix is null
*/ */
public static String replace(Object source, Map valueMap, String prefix, String suffix) { public static String replace(Object source, Map valueMap, String prefix, String suffix) {
return new StrSubstitutor(valueMap, prefix, suffix).replace(source); return new StrSubstitutor(valueMap, prefix, suffix).replace(source);
@ -153,7 +154,7 @@ public class StrSubstitutor {
* Replaces all the occurrences of variables in the given source object with * Replaces all the occurrences of variables in the given source object with
* their matching values from the system properties. * their matching values from the system properties.
* *
* @param source the source text containing the variables to substitute * @param source the source text containing the variables to substitute, null returns null
* @return the result of the replace operation * @return the result of the replace operation
*/ */
public static String replaceSystemProperties(Object source) { public static String replaceSystemProperties(Object source) {
@ -365,14 +366,20 @@ public class StrSubstitutor {
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
/** /**
* Main method for substituting variables. * Internal method that substitutes the variables.
* <p>
* Most users of this class do not need to call this method. This method will
* be called automatically by another (public) method.
* <p>
* Writers of subclasses can override this method if they need access to
* the substitution process at the start or end.
* *
* @param buf the string builder to substitute into, not null * @param buf the string builder to substitute into, not null
* @param offset the start offset within the builder, must be valid * @param offset the start offset within the builder, must be valid
* @param length the length within the builder to be processed, must be valid * @param length the length within the builder to be processed, must be valid
* @return true if altered * @return true if altered
*/ */
private boolean substitute(StrBuilder buf, int offset, int length) { protected boolean substitute(StrBuilder buf, int offset, int length) {
return substitute(buf, offset, length, null) > 0; return substitute(buf, offset, length, null) > 0;
} }
@ -439,7 +446,7 @@ public class StrSubstitutor {
priorVariables.add(varName); priorVariables.add(varName);
// resolve the variable // resolve the variable
String varValue = resolveVariable(varName); String varValue = resolveVariable(varName, buf, startPos, endPos);
if (varValue != null) { if (varValue != null) {
// recursive replace // recursive replace
int varLen = varValue.length(); int varLen = varValue.length();
@ -486,21 +493,28 @@ public class StrSubstitutor {
} }
/** /**
* Resolves the specified variable. This method is called whenever a variable * Internal method that resolves the value of a variable.
* reference is detected in the source text. It is passed the variable's name * <p>
* and must return the corresponding value. This implementation accesses the * Most users of this class do not need to call this method. This method is
* value map using the variable's name as key. Derived classes may override * called automatically by the substitution process.
* this method to implement a different strategy for resolving variables. * <p>
* Writers of subclasses can override this method if they need to alter
* how each substitution occurs. The method is passed the variable's name
* and must return the corresponding value. This implementation uses the
* {@link #getVariableResolver()} with the variable's name as the key.
* *
* @param varName the name of the variable * @param variableName the name of the variable, not null
* @param buf the buffer where the substitution is occurring, not null
* @param startPos the start position of the variable including the prefix, valid
* @param endPos the end position of the variable including the suffix, valid
* @return the variable's value or <b>null</b> if the variable is unknown * @return the variable's value or <b>null</b> if the variable is unknown
*/ */
protected String resolveVariable(String varName) { protected String resolveVariable(String variableName, StrBuilder buf, int startPos, int endPos) {
VariableResolver lookup = getVariableResolver(); VariableResolver lookup = getVariableResolver();
if (lookup == null) { if (lookup == null) {
return null; return null;
} }
return lookup.resolveVariable(varName); return lookup.resolveVariable(variableName);
} }
// Escape // Escape

View File

@ -24,8 +24,6 @@ import junit.framework.TestCase;
import junit.framework.TestSuite; import junit.framework.TestSuite;
import junit.textui.TestRunner; import junit.textui.TestRunner;
import org.apache.commons.lang.text.StrSubstitutor.MapVariableResolver;
/** /**
* Test class for StrSubstitutor. * Test class for StrSubstitutor.
* *
@ -356,42 +354,60 @@ public class StrSubstitutorTest extends TestCase {
} }
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
// /** /**
// * Tests source texts with nothing to replace. * Tests protected.
// */ */
// public void testReplaceNothing() { public void testResolveVariable() {
// assertNull(this.getFormat().replace((char[]) null)); final StrBuilder builder = new StrBuilder("Hi ${name}!");
// assertNull(this.getFormat().replace((String) null)); Map map = new HashMap();
// assertNull(this.getFormat().replace((Object) null)); map.put("name", "commons");
// assertEquals("Nothing to replace.", this.getFormat().replace("Nothing to replace.")); StrSubstitutor sub = new StrSubstitutor(map) {
// assertEquals("42", this.getFormat().replace(new Integer(42))); protected String resolveVariable(String variableName, StrBuilder buf, int startPos, int endPos) {
// assertEquals(0, this.getFormat().replace((StrBuilder) null)); assertEquals("name", variableName);
// } assertSame(builder, buf);
// assertEquals(3, startPos);
//// /** assertEquals(10, endPos);
//// * Tests operating on objects. return "jakarta";
//// */ }
//// public void testReplaceObject() { };
//// this.getValueMap().put("value", new Integer(42)); sub.replace(builder);
//// assertEquals(new Integer(42), this.getFormat().replaceObject("${value}")); assertEquals("Hi jakarta!", builder.toString());
//// assertEquals("The answer is 42.", this.getFormat().replaceObject("The answer is ${value}.")); }
//// }
// //-----------------------------------------------------------------------
// /** /**
// * Tests interpolation with system properties. * Tests static.
// */ */
// public void testReplaceSystemProperties() { public void testStaticReplace() {
// StringBuffer buf = new StringBuffer(); Map map = new HashMap();
// buf.append("Hi ").append(System.getProperty("user.name")); map.put("name", "commons");
// buf.append(", you are working with "); assertEquals("Hi commons!", StrSubstitutor.replace("Hi ${name}!", map));
// buf.append(System.getProperty("os.name")); }
// buf.append(", your home directory is ");
// buf.append(System.getProperty("user.home")).append('.'); /**
// assertEquals(buf.toString(), StrSubstitutor.replaceSystemProperties("Hi ${user.name}, you are " * Tests static.
// + "working with ${os.name}, your home " */
// + "directory is ${user.home}.")); public void testStaticReplacePrefixSuffix() {
// } Map map = new HashMap();
// map.put("name", "commons");
assertEquals("Hi commons!", StrSubstitutor.replace("Hi <name>!", map, "<", ">"));
}
/**
* Tests interpolation with system properties.
*/
public void testStaticReplaceSystemProperties() {
StrBuilder buf = new StrBuilder();
buf.append("Hi ").append(System.getProperty("user.name"));
buf.append(", you are working with ");
buf.append(System.getProperty("os.name"));
buf.append(", your home directory is ");
buf.append(System.getProperty("user.home")).append('.');
assertEquals(buf.toString(), StrSubstitutor.replaceSystemProperties("Hi ${user.name}, you are "
+ "working with ${os.name}, your home "
+ "directory is ${user.home}."));
}
//----------------------------------------------------------------------- //-----------------------------------------------------------------------
private void doTestReplace(String expectedResult, String replaceTemplate, boolean substring) { private void doTestReplace(String expectedResult, String replaceTemplate, boolean substring) {
String expectedShortResult = expectedResult.substring(1, expectedResult.length() - 1); String expectedShortResult = expectedResult.substring(1, expectedResult.length() - 1);