| 1 87 package org.codehaus.loom.components.util; 88 89 import org.apache.avalon.framework.context.Context; 90 import org.apache.avalon.framework.context.ContextException; 91 92 99 public final class PropertyUtil 100 { 101 private PropertyUtil() 102 { 103 } 104 105 116 public static Object resolveProperty( final String property, 117 final Context context, 118 final boolean ignoreUndefined ) 119 throws Exception  120 { 121 int start = findBeginning( property, 0 ); 122 if( -1 == start ) 123 { 124 return property; 125 } 126 127 int end = findEnding( property, start ); 128 129 final int length = property.length(); 130 131 if( 0 == start && end == ( length - 1 ) ) 132 { 133 return resolveValue( property.substring( start + 2, end ), 134 context, 135 ignoreUndefined ); 136 } 137 138 final StringBuffer sb = new StringBuffer ( length * 2 ); 139 int lastPlace = 0; 140 141 while( true ) 142 { 143 final Object value = 144 resolveValue( property.substring( start + 2, end ), 145 context, 146 ignoreUndefined ); 147 148 sb.append( property.substring( lastPlace, start ) ); 149 sb.append( value ); 150 151 lastPlace = end + 1; 152 153 start = findBeginning( property, lastPlace ); 154 if( -1 == start ) 155 { 156 break; 157 } 158 159 end = findEnding( property, start ); 160 } 161 162 sb.append( property.substring( lastPlace, length ) ); 163 164 return sb.toString(); 165 } 166 167 private static int findBeginning( final String property, 168 final int currentPosition ) 169 { 170 return property.indexOf( "${", currentPosition ); 172 } 173 174 private static int findEnding( final String property, 175 final int currentPosition ) 176 throws Exception  177 { 178 final int index = property.indexOf( '}', currentPosition ); 180 if( -1 == index ) 181 { 182 throw new Exception ( "Malformed property with mismatched }'s" ); 183 } 184 185 return index; 186 } 187 188 199 private static Object resolveValue( final String key, 200 final Context context, 201 final boolean ignoreUndefined ) 202 throws Exception  203 { 204 Object value = null; 205 206 try 207 { 208 value = context.get( key ); 209 } 210 catch( final ContextException ce ) 211 { 212 } 214 215 if( null == value ) 216 { 217 if( ignoreUndefined ) 218 { 219 return ""; 220 } 221 else 222 { 223 throw new Exception ( "Unable to find " + 224 key + 225 " to expand during " 226 + "property resolution." ); 227 } 228 } 229 230 return value; 231 } 232 } 233 | Popular Tags |