Background
A subclass of java.util.Properties
attempts to recursively resolve configured properties:
prop_a=Prop A is ${prop_b}
prop_b=Prop B is ${prop_c}
prop_c=Prop C.
After reading the file, prop_a
should be Prop A is Prop B is Prop C
.
Property Reference Semantics
Nest properties are not allowed, making the following invalid:
${property_name_a ${property_name_b}}
A valid property is:
name=Text for ${property_a}, followed by ${property_b}.
Source Code
Code that handles parsing:
/**
* This will throw an IllegalArgumentException if there are mismatched
* braces.
*
* @param s - The string with zero or more ${} references to resolve.
* @return The value of the string, with all substituted values made.
*/
public String resolve( String s ) {
StringBuffer sb = new StringBuffer( 256 );
Stack<StringBuffer> stack = new Stack<StringBuffer>();
int len = s.length();
for( int i = 0; i < len; i++ ) {
char c = s.charAt( i );
switch( c ) {
case '$': {
if( i + 1 < len && s.charAt( i + 1 ) == '{' ) {
stack.push( sb );
sb = new StringBuffer( 256 );
i++;
}
break;
}
case '}': {
if( stack.isEmpty() ) {
throw new IllegalArgumentException( "unexpected '}'" );
}
String name = sb.toString();
sb = stack.pop();
sb.append( super.getProperty( name, null ) );
break;
}
default: {
sb.append( c );
break;
}
}
}
if( !stack.isEmpty() ) {
throw new IllegalArgumentException( "missing '}'" );
}
return sb.toString();
}
Question
How would you simplify the code and detect/avoid infinite recursion?