/
RockerUtil.java
319 lines (260 loc) · 9.83 KB
/
RockerUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
/*
* Copyright 2015 Fizzed Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fizzed.rocker.compiler;
import com.fizzed.rocker.ContentType;
import com.fizzed.rocker.model.JavaVersion;
import com.fizzed.rocker.model.TemplateModel;
//import org.apache.commons.lang3.text.translate.*;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
//import javax.xml.bind.DatatypeConverter;
import org.apache.commons.lang3.text.translate.CharSequenceTranslator;
import org.apache.commons.lang3.text.translate.EntityArrays;
import org.apache.commons.lang3.text.translate.LookupTranslator;
public class RockerUtil {
private static final Pattern VALID_JAVA_IDENTIFIER = Pattern
.compile("\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*");
static public boolean isJava8Plus(TemplateModel model) {
return model.getOptions().isGreaterThanOrEqualToJavaVersion(JavaVersion.v1_8);
}
public static boolean isJavaIdentifier(String identifier) {
return VALID_JAVA_IDENTIFIER.matcher(identifier).matches();
}
static public String pathToPackageName(Path path) {
if (path == null) {
return "";
}
// path.toString() uses File.seperator between components
return path.toString().replace(File.separator, ".");
}
static public Path packageNameToPath(String packageName) {
if (packageName == null || packageName.equals("")) {
return null;
}
return Paths.get(packageName.replace('.', '/'));
}
static public boolean isRelativePath(Path baseDir, Path file) {
return file.startsWith(baseDir);
}
public static int countChars(String value, char ch) {
int count = 0;
for (int i = 0; i < value.length(); i++) {
if (value.charAt(i) == ch) {
count++;
}
}
return count;
}
static public boolean isWhitespaceNoLineBreak(char c) {
// switch statements are always lightning fast
switch (c) {
case ' ':
case '\t':
case '\r':
return true;
default:
return false;
}
}
static public boolean isWhitespace(char c) {
// switch statements are always lightning fast
switch (c) {
case ' ':
case '\t':
case '\r':
case '\n':
return true;
default:
return false;
}
}
static public boolean isWhitespace(String s) {
for (int i = 0; i < s.length(); i++) {
if (!isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
static public String consoleFriendlyText(String s) {
if (s == null) {
return "<NULL>";
}
s = s.replace("\n", "\\n");
s = s.replace("\r", "\\r");
return s;
}
static public String templateNameToName(String templateName) {
int pos = templateName.indexOf('.');
// must be at least 1 char
if (pos < 1) {
throw new IllegalArgumentException("Invalid template name format (unable find first dot character)");
}
return templateName.substring(0, pos);
}
static public ContentType templateNameToContentType(String templateName) {
int pos = templateName.lastIndexOf('.');
// must be at least 1 char
if (pos < 0) {
throw new IllegalArgumentException("Invalid template name format (unable find last dot character)");
}
String ext = templateName.substring(pos+1);
for (ContentType type : ContentType.values()) {
if (type.toString().equalsIgnoreCase(ext)) {
return type;
}
}
throw new IllegalArgumentException("Unsupported content type for extension [" + ext + "] for template name [" + templateName + "]");
}
public static Collection<File> listFileTree(File dir) {
Set<File> fileTree = new HashSet<>();
for (File entry : dir.listFiles()) {
if (entry.isFile()) fileTree.add(entry);
else fileTree.addAll(listFileTree(entry));
}
return fileTree;
}
public static String qualifiedClassName(Object obj) {
return qualifiedClassName(obj.getClass());
}
public static String qualifiedClassName(Class<?> type) {
return type.getName().replace('$', '.');
}
public static String unqualifiedClassName(Object obj) {
return unqualifiedClassName(obj.getClass());
}
public static String unqualifiedClassName(Class<?> type) {
String name = type.getName();
if (name != null && name.lastIndexOf('.') > 0) {
name = name.substring(name.lastIndexOf('.') + 1); // Map$Entry
name = name.replace('$', '.'); // Map.Entry
}
return name;
}
// removes " -> {" at end of string
public static String chompClosureOpen(String expr) {
if (!expr.endsWith("{")) {
return expr;
}
int closurePos = expr.lastIndexOf("->");
if (closurePos < 0) {
return expr;
}
return expr.substring(0, closurePos).trim();
}
// removes " => {" at end of string
public static String chompClosureAssignmentOpen(String expr) {
if (!expr.endsWith("{")) {
return expr;
}
int closureAssignmentPos = expr.lastIndexOf("=>");
if (closureAssignmentPos < 0) {
return expr;
}
return expr.substring(0, closureAssignmentPos).trim();
}
static public List<String> stringIntoChunks(String s, int chunkSize) {
// most likely case
if (s.length() <= chunkSize) {
return Arrays.asList(s);
}
List<String> strings = new ArrayList<>();
for (int offset = 0; offset < s.length(); ) {
int chunkLength = chunkSize;
if ((offset + chunkLength) > s.length()) {
chunkLength = s.length() - offset;
}
String chunk = s.substring(offset, offset+chunkLength);
strings.add(chunk);
offset += chunkLength;
}
return strings;
}
static public List<String> getTextAsJavaByteArrayInitializer(String text, String charsetName, int maxArraySize) throws UnsupportedEncodingException {
byte[] bytes = text.getBytes(charsetName);
List<String> arrays = new ArrayList<>();
for (int length = 0; length < bytes.length; ) {
StringBuilder sb = new StringBuilder();
sb.append("new byte[] { ");
for (int chunk = 0; length < bytes.length && chunk < maxArraySize; chunk++) {
byte b = bytes[length];
if (chunk != 0) {
sb.append(", ");
}
appendByteAsJavaByteInitializer(sb, b);
chunk++;
length++;
}
sb.append(" };");
arrays.add(sb.toString());
}
return arrays;
}
static public void appendByteAsJavaByteInitializer(StringBuilder sb, byte b) {
if (b >= 0 && b < 128) {
if (Character.isAlphabetic(b)) {
sb.append("'").append((char)b).append("'");
} else {
// no cast needed
sb.append("0x").append(byteArrayToHex(new byte[] { b }));
}
} else {
// cast needed
sb.append("(byte)0x").append(byteArrayToHex(new byte[] { b }));
}
}
static public String md5(File f) throws IOException {
try {
byte[] b = Files.readAllBytes(f.toPath());
byte[] hash = MessageDigest.getInstance("MD5").digest(b);
return byteArrayToHex(hash);
} catch (NoSuchAlgorithmException e) {
throw new IOException(e.getMessage(), e);
}
}
static public String byteArrayToHex(byte[] a) {
StringBuilder sb = new StringBuilder(a.length * 2);
for (byte b : a) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
}
/**
* copied from commons lang, but without Unicode escaper anyway whether you
* have unicode in your template or not in last case you would like to have
* a pretty-generated comments for debug
*/
public static final CharSequenceTranslator ESCAPE_JAVA
= new LookupTranslator(
new String[][]{
{"\"", "\\\""},
{"\\", "\\\\"},}).with(
new LookupTranslator(EntityArrays.JAVA_CTRL_CHARS_ESCAPE())
);
}