View Javadoc

1   package org.apache.helix.util;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.
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  }