01: /*
02: * $Id: MapVariableInterpolator.java 460938 2006-06-06 08:47:55Z jonl $
03: * $Revision: 460938 $ $Date: 2006-06-06 10:47:55 +0200 (Tue, 06 Jun 2006) $
04: *
05: * ==============================================================================
06: * Licensed under the Apache License, Version 2.0 (the "License"); you may not
07: * use this file except in compliance with the License. You may obtain a copy of
08: * the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing, software
13: * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14: * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15: * License for the specific language governing permissions and limitations under
16: * the License.
17: */
18: package wicket.util.string.interpolator;
19:
20: import java.util.Map;
21:
22: /**
23: * Interpolates variables into a string from a Map.
24: *
25: * @author Jonathan Locke
26: */
27: public class MapVariableInterpolator extends VariableInterpolator {
28: /** Map of variables */
29: private Map variables;
30:
31: /**
32: * Constructor
33: *
34: * @param string
35: * The string to interpolate into
36: * @param variables
37: * The variables to substitute
38: */
39: public MapVariableInterpolator(final String string,
40: final Map variables) {
41: super (string);
42: this .variables = variables;
43: }
44:
45: /**
46: * Accessor to set variables
47: *
48: * @param variables
49: * New value
50: */
51: public final void setVariables(final Map variables) {
52: this .variables = variables;
53: }
54:
55: /**
56: * Gets a value for a variable name during interpolation
57: *
58: * @param variableName
59: * The variable
60: * @return The value
61: */
62: protected final String getValue(final String variableName) {
63: final Object value = variables.get(variableName);
64: if (value != null) {
65: return value.toString();
66: }
67: throw new IllegalStateException("Interpolated variable '"
68: + variableName + "' not found.");
69: }
70:
71: /**
72: * Interpolate the string with the arguments defined in a map
73: *
74: * @param string
75: * @param variables
76: * @return interpolated string
77: */
78: public static String interpolate(String string, Map variables) {
79: return new MapVariableInterpolator(string, variables)
80: .toString();
81: }
82:
83: }
|