001
014
015 package com.liferay.util;
016
017 import com.liferay.portal.kernel.util.StringUtil;
018
019 import java.util.ArrayList;
020 import java.util.Iterator;
021 import java.util.LinkedHashMap;
022 import java.util.List;
023 import java.util.Map;
024
025
028 public class ContextReplace implements Cloneable {
029
030 public ContextReplace() {
031 this(null);
032 }
033
034 public ContextReplace(Map<String, String> context) {
035 if (context != null) {
036 _context.putAll(context);
037
038 _updateArrays();
039 }
040 }
041
042 public void addValue(String key, String value) {
043 if ((key != null) && (value != null)) {
044 _context.put(key, value);
045
046 _updateArrays();
047 }
048 }
049
050 public String replace(String text) {
051 if (text == null) {
052 return null;
053 }
054
055 if (_keys.length == 0) {
056 return text;
057 }
058
059 return StringUtil.replace(text, _keys, _values);
060 }
061
062 public Object clone() {
063 return new ContextReplace(_context);
064 }
065
066 private void _updateArrays() {
067 List<String> keys = new ArrayList<String>();
068 List<String> values = new ArrayList<String>();
069
070 Iterator<Map.Entry<String, String>> itr =
071 _context.entrySet().iterator();
072
073 while (itr.hasNext()) {
074 Map.Entry<String, String> entry = itr.next();
075
076 String entryKey = entry.getKey();
077 String entryValue = entry.getValue();
078
079 keys.add("${" + entryKey + "}");
080 values.add(entryValue);
081 }
082
083 _keys = keys.toArray(new String[keys.size()]);
084 _values = values.toArray(new String[values.size()]);
085 }
086
087 private Map<String, String> _context = new LinkedHashMap<String, String>();
088 private String[] _keys = new String[0];
089 private String[] _values = new String[0];
090
091 }