1
19
20 package com.liferay.util;
21
22 import com.liferay.portal.kernel.util.StringUtil;
23
24 import java.util.ArrayList;
25 import java.util.Iterator;
26 import java.util.LinkedHashMap;
27 import java.util.List;
28 import java.util.Map;
29
30
36 public class ContextReplace implements Cloneable {
37
38 public ContextReplace() {
39 this(null);
40 }
41
42 public ContextReplace(Map<String, String> context) {
43 if (context != null) {
44 _context.putAll(context);
45
46 _updateArrays();
47 }
48 }
49
50 public void addValue(String key, String value) {
51 if ((key != null) && (value != null)) {
52 _context.put(key, value);
53
54 _updateArrays();
55 }
56 }
57
58 public String replace(String text) {
59 if (text == null) {
60 return null;
61 }
62
63 if (_keys.length == 0) {
64 return text;
65 }
66
67 return StringUtil.replace(text, _keys, _values);
68 }
69
70 public Object clone() {
71 return new ContextReplace(_context);
72 }
73
74 private void _updateArrays() {
75 List<String> keys = new ArrayList<String>();
76 List<String> values = new ArrayList<String>();
77
78 Iterator<Map.Entry<String, String>> itr =
79 _context.entrySet().iterator();
80
81 while (itr.hasNext()) {
82 Map.Entry<String, String> entry = itr.next();
83
84 String entryKey = entry.getKey();
85 String entryValue = entry.getValue();
86
87 keys.add("${" + entryKey + "}");
88 values.add(entryValue);
89 }
90
91 _keys = keys.toArray(new String[keys.size()]);
92 _values = values.toArray(new String[values.size()]);
93 }
94
95 private Map<String, String> _context = new LinkedHashMap<String, String>();
96 private String[] _keys = new String[0];
97 private String[] _values = new String[0];
98
99 }