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