package mir.util;
+import multex.Failure;
+import multex.Exc;
+
import java.util.*;
public class ParameterExpander {
return result;
}
- public static String findValueForKey(Map aMap, String aKey) throws Exception {
- Object node;
+ private static Object findNode(String aKey, Map aMap, List aParts) throws Exception {
Iterator i;
- List parts = splitString(aKey, NODE_SEPARATOR);
String location = "";
+ Object node = aMap;
- node = aMap;
-
- i = parts.iterator();
+ i = aParts.iterator();
while(i.hasNext()) {
String part = (String) i.next();
location = location + part;
if (node == null) {
- throw new Exception( "Can't expand key " + aKey + ": "+ location + " does not exist" );
+ throw new ParameterExpanderExc( "Can't expand key {1}: {2} does not exist", new Object[]{aKey,location} );
}
}
- if (node instanceof Map) {
- node = ((Map) node).get(DEFAULT_KEY);
- }
+ return node;
+ }
+
+ public static Object findValueForKey(Map aMap, String aKey) throws Exception {
+ Object node;
+ List parts = splitString(aKey, NODE_SEPARATOR);
+
+ node = findNode(aKey, aMap, parts);
+
+ return node;
+ }
- if (!(node instanceof String))
- throw new Exception( "Can't expand key " + aKey + ": "+ location + " is not a string but a " + node.getClass().getName() );
+ public static String findStringForKey(Map aMap, String aKey) throws Exception {
+ Object expandedValue = findValueForKey(aMap, aKey);
- return (String) node;
+ if (!(expandedValue instanceof String))
+ throw new ParameterExpanderExc( "Value of key is not a string but a {1}", new Object[]{expandedValue.getClass().getName()} );
+
+ return (String) expandedValue;
+ }
+
+ public static void setValueForKey(Map aMap, String aKey, Object aValue) throws Exception {
+ List parts = splitString(aKey, NODE_SEPARATOR);
+
+ String key = (String) parts.get(parts.size()-1);
+ parts.remove(parts.size()-1);
+
+ Object node=findNode(aKey, aMap, parts);
+
+ if (node instanceof Map) {
+ ((Map) node).put(key, aValue);
+ }
+ else
+ throw new ParameterExpanderExc( "Can't set key {1}: not inside a Map", new Object[]{aKey} );
}
public static String expandExpression(Map aMap, String anExpression) throws Exception {
if (anExpression.charAt(position+1) == '{') {
endOfNamePosition=anExpression.indexOf('}', position);
if (endOfNamePosition>=0) {
- result.append(findValueForKey(aMap, anExpression.substring(position+2, endOfNamePosition)));
+ result.append(findStringForKey(aMap, anExpression.substring(position+2, endOfNamePosition)));
previousPosition=endOfNamePosition+1;
}
else {
- throw new Exception("Missing } in " + anExpression);
+ throw new ParameterExpanderExc("Missing } in {1}",new Object[]{anExpression});
}
}
else
return result.toString();
}
+
+
+ public static class ParameterExpanderExc extends Exc {
+ public ParameterExpanderExc(String msg, Object[] objects) {
+ super(msg, objects);
+ }
+ }
}