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