1 package org.apache.helix.util;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.util.Arrays;
23 import java.util.HashMap;
24 import java.util.Map;
25 import java.util.regex.Matcher;
26 import java.util.regex.Pattern;
27
28 import org.apache.log4j.Logger;
29
30 public class StringTemplate
31 {
32 private static Logger LOG = Logger.getLogger(StringTemplate.class);
33
34 Map<Enum, Map<Integer, String>> templateMap = new HashMap<Enum, Map<Integer, String>>();
35 static Pattern pattern = Pattern.compile("(\\{.+?\\})");
36
37 public void addEntry(Enum type, int numKeys, String template)
38 {
39 if (!templateMap.containsKey(type))
40 {
41 templateMap.put(type, new HashMap<Integer, String>());
42 }
43 LOG.trace("Add template for type: " + type.name() + ", arguments: " + numKeys
44 + ", template: " + template);
45 templateMap.get(type).put(numKeys, template);
46 }
47
48 public String instantiate(Enum type, String... keys)
49 {
50 if (keys == null)
51 {
52 keys = new String[] {};
53 }
54
55 String template = null;
56 if (templateMap.containsKey(type))
57 {
58 template = templateMap.get(type).get(keys.length);
59 }
60
61 String result = null;
62
63 if (template != null)
64 {
65 result = template;
66 Matcher matcher = pattern.matcher(template);
67 int count = 0;
68 while (matcher.find())
69 {
70 String var = matcher.group();
71 result = result.replace(var, keys[count]);
72 count++;
73 }
74 }
75
76 if (result == null || result.indexOf('{') > -1 || result.indexOf('}') > -1)
77 {
78 String errMsg = "Unable to instantiate template: " + template
79 + " using keys: " + Arrays.toString(keys);
80 LOG.error(errMsg);
81 throw new IllegalArgumentException(errMsg);
82 }
83
84 return result;
85 }
86
87 }