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