View Javadoc

1   /*
2    * Copyright 2007 Hippo
3    *
4    * Licensed under the Apache License, Version 2.0 (the  "License"); 
5    * you may not use this file except in compliance with the License. 
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" 
12   * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
13   * See the License for the specific language governing permissions and 
14   * limitations under the License.
15   */
16  package nl.hippo.client.webdav.utils;
17  
18  import java.util.Iterator;
19  import java.util.Map;
20  
21  import org.apache.commons.lang.StringUtils;
22  
23  /**
24   * Performs basic variable interpolation on a String for variables within 
25   * a Map. Variables of the form, ${var}, are supported.
26   */
27  public class Interpolation {
28  
29      private static final String SYMBOLIC_VALUE_MARKER_START = "${";
30      private static final String SYMBOLIC_VALUE_MARKER_END = "}";
31  
32      public static String interpolate(String templateString, Map valuesMap) {
33          if (valuesMap == null || valuesMap.isEmpty()) {
34              return templateString;
35          }
36          if (templateString == null || templateString.length() < 1) {
37              return templateString;
38          }
39  
40          String result = templateString;
41          Iterator sets = valuesMap.entrySet().iterator();
42          while (sets.hasNext()) {
43              Map.Entry set = (Map.Entry) sets.next();
44              String key = (String) set.getKey();
45              String valueToBeSubstituted = SYMBOLIC_VALUE_MARKER_START + key + SYMBOLIC_VALUE_MARKER_END;
46              String substitutionValue = StringUtils.defaultString((String) set.getValue());
47              result = StringUtils.replace(result, valueToBeSubstituted, substitutionValue);
48          }
49          return result;
50      }
51  
52  }