1 17 18 package org.apache.commons.digester.substitution; 19 20 import java.util.Map ; 21 import java.util.ArrayList ; 22 23 28 29 public class MultiVariableExpander implements VariableExpander { 30 private int nEntries = 0; 31 private ArrayList markers = new ArrayList (2); 32 private ArrayList sources = new ArrayList (2); 33 34 public MultiVariableExpander() { 35 } 36 37 public void addSource(String marker, Map source) { 38 ++nEntries; 39 markers.add(marker); 40 sources.add(source); 41 } 42 43 50 public String expand(String param) { 51 for(int i=0; i<nEntries; ++i) { 52 param = expand( 53 param, 54 (String ) markers.get(i), 55 (Map ) sources.get(i)); 56 } 57 return param; 58 } 59 60 75 public String expand(String str, String marker, Map source) { 76 String startMark = marker + "{"; 77 int markLen = startMark.length(); 78 79 int index = 0; 80 for(;;) 81 { 82 index = str.indexOf(startMark, index); 83 if (index == -1) 84 { 85 return str; 86 } 87 88 int startIndex = index + markLen; 89 if (startIndex > str.length()) 90 { 91 throw new IllegalArgumentException ( 92 "var expression starts at end of string"); 93 } 94 95 int endIndex = str.indexOf("}", index + markLen); 96 if (endIndex == -1) 97 { 98 throw new IllegalArgumentException ( 99 "var expression starts but does not end"); 100 } 101 102 String key = str.substring(index+markLen, endIndex); 103 Object value = source.get(key); 104 if (value == null) { 105 throw new IllegalArgumentException ( 106 "parameter [" + key + "] is not defined."); 107 } 108 String varValue = value.toString(); 109 110 str = str.substring(0, index) + varValue + str.substring(endIndex+1); 111 index += varValue.length(); 112 } 113 } 114 115 } 116 | Popular Tags |