01: /**
02: * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
03: *
04: * Permission is hereby granted, free of charge, to any person obtaining a copy
05: * of this software and associated documentation files (the "Software"), to deal
06: * in the Software without restriction, including without limitation the rights
07: * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
08: * copies of the Software, and to permit persons to whom the Software is
09: * furnished to do so, subject to the following conditions:
10: *
11: * The above copyright notice and this permission notice shall be included in
12: * all copies or substantial portions of the Software.
13: *
14: * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15: * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16: * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17: * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18: * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19: * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20: * SOFTWARE.
21: */package com.liferay.util;
22:
23: import com.liferay.portal.kernel.util.StringUtil;
24:
25: import java.util.ArrayList;
26: import java.util.Iterator;
27: import java.util.LinkedHashMap;
28: import java.util.List;
29: import java.util.Map;
30:
31: /**
32: * <a href="ContextReplace.java.html"><b><i>View Source</i></b></a>
33: *
34: * @author Brian Wing Shun Chan
35: *
36: */
37: public class ContextReplace implements Cloneable {
38:
39: public ContextReplace() {
40: this (null);
41: }
42:
43: public ContextReplace(Map context) {
44: if (context != null) {
45: _context.putAll(context);
46:
47: _updateArrays();
48: }
49: }
50:
51: public void addValue(String key, String value) {
52: if ((key != null) && (value != null)) {
53: _context.put(key, value);
54:
55: _updateArrays();
56: }
57: }
58:
59: public String replace(String text) {
60: if (text == null) {
61: return null;
62: }
63:
64: if (_keys.length == 0) {
65: return text;
66: }
67:
68: return StringUtil.replace(text, _keys, _values);
69: }
70:
71: public Object clone() {
72: return new ContextReplace(_context);
73: }
74:
75: private void _updateArrays() {
76: List keys = new ArrayList();
77: List values = new ArrayList();
78:
79: Iterator itr = _context.entrySet().iterator();
80:
81: while (itr.hasNext()) {
82: Map.Entry entry = (Map.Entry) itr.next();
83:
84: String entryKey = (String) entry.getKey();
85: String entryValue = (String) entry.getValue();
86:
87: keys.add("${" + entryKey + "}");
88: values.add(entryValue);
89: }
90:
91: _keys = (String[]) keys.toArray(new String[0]);
92: _values = (String[]) values.toArray(new String[0]);
93: }
94:
95: private Map _context = new LinkedHashMap();
96: private String[] _keys = new String[0];
97: private String[] _values = new String[0];
98:
99: }
|