1
22
23 package com.liferay.portal.upgrade.util;
24
25 import com.liferay.portal.kernel.util.GetterUtil;
26 import com.liferay.portal.kernel.util.Validator;
27 import com.liferay.portal.upgrade.StagnantRowException;
28
29 import org.apache.commons.logging.Log;
30 import org.apache.commons.logging.LogFactory;
31
32
38 public class IdReplacer {
39
40 public static String replaceLongIds(
41 String s, String begin, ValueMapper valueMapper)
42 throws Exception {
43
44 if ((s == null) || (begin == null) ||
45 (valueMapper == null) || (valueMapper.size() == 0)) {
46
47 return s;
48 }
49
50 char[] charArray = s.toCharArray();
51
52 StringBuilder sb = new StringBuilder(s.length());
53
54 int pos = 0;
55
56 while (true) {
57 int x = s.indexOf(begin, pos);
58 int y = _getEndPos(charArray, x + begin.length());
59
60 if ((x == -1) || (y == -1)) {
61 sb.append(s.substring(pos, s.length()));
62
63 break;
64 }
65 else {
66 sb.append(s.substring(pos, x + begin.length()));
67
68 String oldString = s.substring(x + begin.length(), y);
69
70 if (Validator.isNotNull(oldString)) {
71 Long oldValue = new Long(GetterUtil.getLong(oldString));
72
73 Long newValue = null;
74
75 try {
76 newValue = (Long)valueMapper.getNewValue(oldValue);
77 }
78 catch (StagnantRowException sre) {
79 if (_log.isWarnEnabled()) {
80 _log.warn(sre);
81 }
82 }
83
84 if (newValue == null) {
85 newValue = oldValue;
86 }
87
88 sb.append(newValue);
89 }
90
91 pos = y;
92 }
93 }
94
95 return sb.toString();
96 }
97
98 public String replaceLongIds(
99 String s, String begin, String end, ValueMapper valueMapper)
100 throws Exception {
101
102 if ((s == null) || (begin == null) || (end == null) ||
103 (valueMapper == null) || (valueMapper.size() == 0)) {
104
105 return s;
106 }
107
108 StringBuilder sb = new StringBuilder(s.length());
109
110 int pos = 0;
111
112 while (true) {
113 int x = s.indexOf(begin, pos);
114 int y = s.indexOf(end, x + begin.length());
115
116 if ((x == -1) || (y == -1)) {
117 sb.append(s.substring(pos, s.length()));
118
119 break;
120 }
121 else {
122 sb.append(s.substring(pos, x + begin.length()));
123
124 Long oldValue = new Long(GetterUtil.getLong(
125 s.substring(x + begin.length(), y)));
126
127 Long newValue = null;
128
129 try {
130 newValue = (Long)valueMapper.getNewValue(oldValue);
131 }
132 catch (StagnantRowException sre) {
133 if (_log.isWarnEnabled()) {
134 _log.warn(sre);
135 }
136 }
137
138 if (newValue == null) {
139 newValue = oldValue;
140 }
141
142 sb.append(newValue);
143
144 pos = y;
145 }
146 }
147
148 return sb.toString();
149 }
150
151 private static int _getEndPos(char[] charArray, int pos) {
152 while (true) {
153 if (pos >= charArray.length) {
154 break;
155 }
156
157 if (!Character.isDigit(charArray[pos])) {
158 break;
159 }
160
161 pos++;
162 }
163
164 return pos;
165 }
166
167 private static Log _log = LogFactory.getLog(IdReplacer.class);
168
169 }