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.LinkedHashMap;
021 import java.util.List;
022 import java.util.Map;
023
024
027 public class ContextReplace implements Cloneable {
028
029 public ContextReplace() {
030 this(null);
031 }
032
033 public ContextReplace(Map<String, String> context) {
034 if (context != null) {
035 _context.putAll(context);
036
037 _updateArrays();
038 }
039 }
040
041 public void addValue(String key, String value) {
042 if ((key != null) && (value != null)) {
043 _context.put(key, value);
044
045 _updateArrays();
046 }
047 }
048
049 @Override
050 public Object clone() {
051 return new ContextReplace(_context);
052 }
053
054 public String replace(String text) {
055 if (text == null) {
056 return null;
057 }
058
059 if (_keys.length == 0) {
060 return text;
061 }
062
063 return StringUtil.replace(text, _keys, _values);
064 }
065
066 private void _updateArrays() {
067 List<String> keys = new ArrayList<String>();
068 List<String> values = new ArrayList<String>();
069
070 for (Map.Entry<String, String> entry : _context.entrySet()) {
071 String entryKey = entry.getKey();
072 String entryValue = entry.getValue();
073
074 keys.add("${" + entryKey + "}");
075 values.add(entryValue);
076 }
077
078 _keys = keys.toArray(new String[keys.size()]);
079 _values = values.toArray(new String[values.size()]);
080 }
081
082 private Map<String, String> _context = new LinkedHashMap<String, String>();
083 private String[] _keys = new String[0];
084 private String[] _values = new String[0];
085
086 }