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