KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > util > TemplateParser


1 /*
2  * $Id: TemplateParser.java 3798 2006-11-04 04:07:14Z aperepel $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.util;
12
13 import java.util.ArrayList JavaDoc;
14 import java.util.HashMap JavaDoc;
15 import java.util.Iterator JavaDoc;
16 import java.util.List JavaDoc;
17 import java.util.Map JavaDoc;
18 import java.util.regex.Matcher JavaDoc;
19 import java.util.regex.Pattern JavaDoc;
20
21 import org.apache.commons.logging.Log;
22 import org.apache.commons.logging.LogFactory;
23
24 /**
25  * <code>TemplateParser</code> is a simple string parser that will substitute
26  * tokens in a string with values supplied in a Map.
27  */

28 public class TemplateParser
29 {
30     public static final String JavaDoc ANT_TEMPLATE_STYLE = "ant";
31     public static final String JavaDoc SQUARE_TEMPLATE_STYLE = "square";
32
33     /**
34      * logger used by this class
35      */

36     protected static Log logger = LogFactory.getLog(TemplateParser.class);
37
38     private Pattern JavaDoc pattern = null;
39     private int pre = 1;
40     private int post = 1;
41     private String JavaDoc style = null;
42
43     public static TemplateParser createAntStyleParser()
44     {
45         return new TemplateParser(ANT_TEMPLATE_STYLE);
46     }
47
48     public static TemplateParser createSquareBracesStyleParser()
49     {
50         return new TemplateParser(SQUARE_TEMPLATE_STYLE);
51     }
52
53     private TemplateParser(String JavaDoc style)
54     {
55         if (ANT_TEMPLATE_STYLE.equals(style))
56         {
57             pattern = Pattern.compile("\\$\\{[^\\}]+\\}");
58             pre = 2;
59         }
60         else if (SQUARE_TEMPLATE_STYLE.equals(style))
61         {
62             pattern = Pattern.compile("\\[[^\\]]+\\]");
63         }
64         else
65         {
66             throw new IllegalArgumentException JavaDoc("Unknown template style: " + style);
67         }
68         this.style = style;
69     }
70
71     /**
72      * Matches one or more templates against a Map of key value pairs. If a value for
73      * a template is not found in the map the template is left as is in the return
74      * String
75      *
76      * @param props the key/value pairs to match against
77      * @param template the string containing the template place holders i.e. My name
78      * is ${name}
79      * @return the parsed String
80      */

81     public String JavaDoc parse(Map JavaDoc props, String JavaDoc template)
82     {
83         return parse(props, template, null);
84     }
85
86     /**
87      * Matches one or more templates against a Map of key value pairs. If a value for
88      * a template is not found in the map the template is left as is in the return
89      * String
90      *
91      * @param callback a callback used to resolve the property name
92      * @param template the string containing the template place holders i.e. My name
93      * is ${name}
94      * @return the parsed String
95      */

96     public String JavaDoc parse(TemplateCallback callback, String JavaDoc template)
97     {
98         return parse(null, template, callback);
99     }
100
101     protected String JavaDoc parse(Map JavaDoc props, String JavaDoc template, TemplateCallback callback)
102     {
103         String JavaDoc result = template;
104         Matcher JavaDoc m = pattern.matcher(template);
105
106         while (m.find())
107         {
108             Object JavaDoc value = null;
109
110             String JavaDoc match = m.group();
111             String JavaDoc propname = match.substring(pre, match.length() - post);
112
113             if (callback != null)
114             {
115                 value = callback.match(propname);
116             }
117             else if (props != null)
118             {
119                 value = props.get(propname);
120             }
121
122             if (value == null)
123             {
124                 if (logger.isWarnEnabled())
125                 {
126                     logger.warn("Value " + propname + " not found in context");
127                 }
128             }
129             else
130             {
131                 String JavaDoc matchRegex = escape(match);
132                 String JavaDoc valueString = value.toString();
133
134                 if (valueString.indexOf('\\') != -1)
135                 {
136                     valueString = valueString.replaceAll("\\\\", "\\\\\\\\");
137                 }
138
139                 result = result.replaceAll(matchRegex, valueString);
140             }
141         }
142         return result;
143     }
144
145     /**
146      * Matches one or more templates against a Map of key value pairs. If a value for
147      * a template is not found in the map the template is left as is in the return
148      * String
149      *
150      * @param props the key/value pairs to match against
151      * @param templates A List of templates
152      * @return the parsed String
153      */

154     public List JavaDoc parse(Map JavaDoc props, List JavaDoc templates)
155     {
156         if (templates == null)
157         {
158             return new ArrayList JavaDoc();
159         }
160         List JavaDoc list = new ArrayList JavaDoc(templates.size());
161         for (Iterator JavaDoc iterator = templates.iterator(); iterator.hasNext();)
162         {
163             list.add(parse(props, iterator.next().toString()));
164         }
165         return list;
166     }
167
168     /**
169      * Matches one or more templates against a Map of key value pairs. If a value for
170      * a template is not found in the map the template is left as is in the return
171      * String
172      *
173      * @param props the key/value pairs to match against
174      * @param templates A Map of templates. The values for each map entry will be
175      * parsed
176      * @return the parsed String
177      */

178     public Map JavaDoc parse(Map JavaDoc props, Map JavaDoc templates)
179     {
180         if (templates == null)
181         {
182             return new HashMap JavaDoc();
183         }
184         Map JavaDoc map = new HashMap JavaDoc(templates.size());
185         Map.Entry JavaDoc entry;
186         for (Iterator JavaDoc iterator = templates.entrySet().iterator(); iterator.hasNext();)
187         {
188             entry = (Map.Entry JavaDoc)iterator.next();
189             map.put(entry.getKey(), parse(props, entry.getValue().toString()));
190         }
191         return map;
192     }
193
194     private String JavaDoc escape(String JavaDoc string)
195     {
196         int length = string.length();
197         if (length == 0)
198         {
199             // nothing to do
200
return string;
201         }
202         else
203         {
204             StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(length * 2);
205             for (int i = 0; i < length; i++)
206             {
207                 char currentCharacter = string.charAt(i);
208                 switch (currentCharacter)
209                 {
210                     case '[' :
211                     case ']' :
212                     case '{' :
213                     case '}' :
214                     case '$' :
215                         buffer.append("\\");
216                         // fall through to append original character
217
default :
218                         buffer.append(currentCharacter);
219                 }
220             }
221             return buffer.toString();
222         }
223     }
224
225     public String JavaDoc getStyle()
226     {
227         return style;
228     }
229
230     public boolean isContainsTemplate(String JavaDoc value)
231     {
232         Matcher JavaDoc m = pattern.matcher(value);
233         return m.find();
234     }
235
236     public static interface TemplateCallback
237     {
238         public Object JavaDoc match(String JavaDoc token);
239     }
240
241 }
242
Popular Tags