1 package org.sapia.util.text; 2 3 4 import java.util.ArrayList ; 7 8 9 37 public class TemplateFactory { 38 42 43 public static final String DEFAULT_STARTING_DELIMITER = "${"; 44 45 46 public static final String DEFAULT_ENDING_DELIMITER = "}"; 47 48 52 53 private String _theStartingDelimiter = DEFAULT_STARTING_DELIMITER; 54 55 56 private String _theEndingDelimiter = DEFAULT_ENDING_DELIMITER; 57 58 private boolean _throwExcMissingVar = true; 59 60 64 67 public TemplateFactory() { 68 } 69 70 76 public TemplateFactory(String aStartingDelimiter, String anEndingDelimiter) { 77 _theStartingDelimiter = aStartingDelimiter; 78 _theEndingDelimiter = anEndingDelimiter; 79 } 80 81 85 public void setThrowExcOnMissingVar(boolean throwEx){ 86 _throwExcMissingVar = throwEx; 87 } 88 89 93 100 public TemplateElementIF parse(String aContent) { 101 if (aContent == null) { 103 throw new IllegalArgumentException ("The content passed in is null."); 104 } 105 106 String aBuffer; 107 ArrayList someElements = new ArrayList (); 108 109 int aLastPosition = 0; 110 boolean isFinished = false; 111 112 while (!isFinished && (aLastPosition < aContent.length())) { 113 int anIndex = aContent.indexOf(_theStartingDelimiter, aLastPosition); 115 116 if (anIndex < 0) { 118 aBuffer = aContent.substring(aLastPosition); 119 someElements.add(new ConstantElement(aBuffer)); 120 isFinished = true; 121 122 } else { 124 if (anIndex > aLastPosition) { 126 aBuffer = aContent.substring(aLastPosition, anIndex); 128 someElements.add(new ConstantElement(aBuffer)); 129 } 130 131 aLastPosition = anIndex + _theStartingDelimiter.length(); 133 anIndex = aContent.indexOf(_theEndingDelimiter, aLastPosition); 134 135 if (anIndex < 0) { 137 aBuffer = aContent.substring(aLastPosition - 139 _theStartingDelimiter.length()); 140 someElements.add(new ConstantElement(aBuffer)); 141 isFinished = true; 142 } 143 else if (anIndex == aLastPosition) { 145 aBuffer = aContent.substring(aLastPosition - 146 _theStartingDelimiter.length(), 147 anIndex + _theEndingDelimiter.length()); 148 someElements.add(new ConstantElement(aBuffer)); 149 aLastPosition = anIndex + _theEndingDelimiter.length(); 150 } 151 else { 152 int aNextDelimiter = aContent.indexOf(_theStartingDelimiter, 153 aLastPosition); 154 155 if ((aNextDelimiter != -1) && (anIndex > aNextDelimiter)) { 157 aBuffer = aContent.substring(aLastPosition - 158 _theStartingDelimiter.length(), aNextDelimiter); 159 someElements.add(new ConstantElement(aBuffer)); 160 aLastPosition = aNextDelimiter; 161 } 162 else { 164 aBuffer = aContent.substring(aLastPosition, anIndex); 165 someElements.add(new VariableElement(aBuffer, _throwExcMissingVar)); 166 aLastPosition = anIndex + _theEndingDelimiter.length(); 167 } 168 } 169 } 170 } 171 172 return new CompositeElement(someElements); 173 } 174 } 175 | Popular Tags |