001
014
015 package com.liferay.portal.kernel.upgrade.util;
016
017 import com.liferay.portal.kernel.log.Log;
018 import com.liferay.portal.kernel.log.LogFactoryUtil;
019 import com.liferay.portal.kernel.upgrade.StagnantRowException;
020 import com.liferay.portal.kernel.util.GetterUtil;
021 import com.liferay.portal.kernel.util.StringBundler;
022 import com.liferay.portal.kernel.util.Validator;
023
024
027 public class IdReplacer {
028
029 public static String replaceLongIds(
030 String s, String begin, ValueMapper valueMapper)
031 throws Exception {
032
033 if ((s == null) || (begin == null) ||
034 (valueMapper == null) || (valueMapper.size() == 0)) {
035
036 return s;
037 }
038
039 char[] chars = s.toCharArray();
040
041 StringBundler sb = new StringBundler();
042
043 int pos = 0;
044
045 while (true) {
046 int x = s.indexOf(begin, pos);
047 int y = _getEndPos(chars, x + begin.length());
048
049 if ((x == -1) || (y == -1)) {
050 sb.append(s.substring(pos));
051
052 break;
053 }
054 else {
055 sb.append(s.substring(pos, x + begin.length()));
056
057 String oldString = s.substring(x + begin.length(), y);
058
059 if (Validator.isNotNull(oldString)) {
060 Long oldValue = new Long(GetterUtil.getLong(oldString));
061
062 Long newValue = null;
063
064 try {
065 newValue = (Long)valueMapper.getNewValue(oldValue);
066 }
067 catch (StagnantRowException sre) {
068 if (_log.isWarnEnabled()) {
069 _log.warn(sre);
070 }
071 }
072
073 if (newValue == null) {
074 newValue = oldValue;
075 }
076
077 sb.append(newValue);
078 }
079
080 pos = y;
081 }
082 }
083
084 return sb.toString();
085 }
086
087 public String replaceLongIds(
088 String s, String begin, String end, ValueMapper valueMapper)
089 throws Exception {
090
091 if ((s == null) || (begin == null) || (end == null) ||
092 (valueMapper == null) || (valueMapper.size() == 0)) {
093
094 return s;
095 }
096
097 StringBundler sb = new StringBundler();
098
099 int pos = 0;
100
101 while (true) {
102 int x = s.indexOf(begin, pos);
103 int y = s.indexOf(end, x + begin.length());
104
105 if ((x == -1) || (y == -1)) {
106 sb.append(s.substring(pos));
107
108 break;
109 }
110 else {
111 sb.append(s.substring(pos, x + begin.length()));
112
113 Long oldValue = new Long(
114 GetterUtil.getLong(s.substring(x + begin.length(), y)));
115
116 Long newValue = null;
117
118 try {
119 newValue = (Long)valueMapper.getNewValue(oldValue);
120 }
121 catch (StagnantRowException sre) {
122 if (_log.isWarnEnabled()) {
123 _log.warn(sre);
124 }
125 }
126
127 if (newValue == null) {
128 newValue = oldValue;
129 }
130
131 sb.append(newValue);
132
133 pos = y;
134 }
135 }
136
137 return sb.toString();
138 }
139
140 private static int _getEndPos(char[] chars, int pos) {
141 while (true) {
142 if (pos >= chars.length) {
143 break;
144 }
145
146 if (!Character.isDigit(chars[pos])) {
147 break;
148 }
149
150 pos++;
151 }
152
153 return pos;
154 }
155
156 private static Log _log = LogFactoryUtil.getLog(IdReplacer.class);
157
158 }