-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataUtil.java
299 lines (274 loc) · 11.7 KB
/
DataUtil.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
package org.jsoup.helper;
import org.jsoup.internal.ConstrainableInputStream;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Comment;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.XmlDeclaration;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Internal static utilities for handling data.
*
*/
public final class DataUtil {
private static final Pattern charsetPattern = Pattern.compile("(?i)\\bcharset=\\s*(?:[\"'])?([^\\s,;\"']*)");
static final String defaultCharset = "UTF-8"; // used if not found in header or meta charset
private static final int firstReadBufferSize = 1024 * 5;
static final int bufferSize = 1024 * 32;
private static final char[] mimeBoundaryChars
= "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
static final int boundaryLength = 32;
private DataUtil() {
}
/**
* Loads a file to a Document.
*
* @param in file to load
* @param charsetName character set of input
* @param baseUri base URI of document, to resolve relative links against
* @return Document
* @throws IOException on IO error
*/
public static Document load(File in, String charsetName, String baseUri) throws IOException {
return parseInputStream(new FileInputStream(in), charsetName, baseUri, Parser.htmlParser());
}
/**
* Parses a Document from an input steam.
*
* @param in input stream to parse. You will need to close it.
* @param charsetName character set of input
* @param baseUri base URI of document, to resolve relative links against
* @return Document
* @throws IOException on IO error
*/
public static Document load(InputStream in, String charsetName, String baseUri) throws IOException {
return parseInputStream(in, charsetName, baseUri, Parser.htmlParser());
}
/**
* Parses a Document from an input steam, using the provided Parser.
*
* @param in input stream to parse. You will need to close it.
* @param charsetName character set of input
* @param baseUri base URI of document, to resolve relative links against
* @param parser alternate {@link Parser#xmlParser() parser} to use.
* @return Document
* @throws IOException on IO error
*/
public static Document load(InputStream in, String charsetName, String baseUri, Parser parser) throws IOException {
return parseInputStream(in, charsetName, baseUri, parser);
}
/**
* Writes the input stream to the output stream. Doesn't close them.
*
* @param in input stream to read from
* @param out output stream to write to
* @throws IOException on IO error
*/
static void crossStreams(final InputStream in, final OutputStream out) throws IOException {
final byte[] buffer = new byte[bufferSize];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
}
static Document parseInputStream(InputStream input, String charsetName, String baseUri, Parser parser) throws IOException {
if (input == null) // empty body
{
return new Document(baseUri);
}
input = ConstrainableInputStream.wrap(input, bufferSize, 0);
Document doc = null;
boolean fullyRead = false;
// read the start of the stream and look for a BOM or meta charset
input.mark(bufferSize);
ByteBuffer firstBytes = readToByteBuffer(input, firstReadBufferSize - 1); // -1 because we read one more to see if completed. First read is < buffer size, so can't be invalid.
fullyRead = input.read() == -1;
input.reset();
// look for BOM - overrides any other header or input
BomCharset bomCharset = detectCharsetFromBom(firstBytes);
if (bomCharset != null) {
charsetName = bomCharset.charset;
}
if (charsetName == null) { // determine from meta. safe first parse as UTF-8
String docData = Charset.forName(defaultCharset).decode(firstBytes).toString();
doc = parser.parseInput(docData, baseUri);
// look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312">
Elements metaElements = doc.select("meta[http-equiv=content-type], meta[charset]");
String foundCharset = null; // if not found, will keep utf-8 as best attempt
for (Element meta : metaElements) {
if (meta.hasAttr("http-equiv")) {
foundCharset = getCharsetFromContentType(meta.attr("content"));
}
if (foundCharset == null && meta.hasAttr("charset")) {
foundCharset = meta.attr("charset");
}
if (foundCharset != null) {
break;
}
}
// look for <?xml encoding='ISO-8859-1'?>
if (foundCharset == null && doc.childNodeSize() > 0) {
Node first = doc.childNode(0);
XmlDeclaration decl = null;
if (first instanceof XmlDeclaration) {
decl = (XmlDeclaration) first;
} else if (first instanceof Comment) {
Comment comment = (Comment) first;
if (comment.isXmlDeclaration()) {
decl = comment.asXmlDeclaration();
}
}
if (decl != null) {
if (decl.name().equalsIgnoreCase("xml")) {
foundCharset = decl.attr("encoding");
}
}
}
foundCharset = validateCharset(foundCharset);
if (foundCharset != null && !foundCharset.equalsIgnoreCase(defaultCharset)) { // need to re-decode. (case insensitive check here to match how validate works)
foundCharset = foundCharset.trim().replaceAll("[\"']", "");
charsetName = foundCharset;
doc = null;
} else if (!fullyRead) {
doc = null;
}
} else { // specified by content type header (or by user on file load)
Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML");
}
if (doc == null) {
if (charsetName == null) {
charsetName = defaultCharset;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(input, charsetName), bufferSize);
if (bomCharset != null && bomCharset.offset) // creating the buffered reader ignores the input pos, so must skip here
{
reader.skip(1);
}
doc = parser.parseInput(reader, baseUri);
Charset charset = Charset.forName(charsetName);
doc.outputSettings().charset(charset);
if (!charset.canEncode()) {
// some charsets can read but not encode; switch to an encodable charset and update the meta el
doc.charset(Charset.forName(defaultCharset));
}
}
input.close();
return doc;
}
/**
* Read the input stream into a byte buffer. To deal with slow input
* streams, you may interrupt the thread this method is executing on. The
* data read until being interrupted will be available.
*
* @param inStream the input stream to read from
* @param maxSize the maximum size in bytes to read from the stream. Set to
* 0 to be unlimited.
* @return the filled byte buffer
* @throws IOException if an exception occurs whilst reading from the input
* stream.
*/
public static ByteBuffer readToByteBuffer(InputStream inStream, int maxSize) throws IOException {
Validate.isTrue(maxSize >= 0, "maxSize must be 0 (unlimited) or larger");
final ConstrainableInputStream input = ConstrainableInputStream.wrap(inStream, bufferSize, maxSize);
return input.readToByteBuffer(maxSize);
}
static ByteBuffer emptyByteBuffer() {
return ByteBuffer.allocate(0);
}
/**
* Parse out a charset from a content type header. If the charset is not
* supported, returns null (so the default will kick in.)
*
* @param contentType e.g. "text/html; charset=EUC-JP"
* @return "EUC-JP", or null if not found. Charset is trimmed and
* uppercased.
*/
static String getCharsetFromContentType(String contentType) {
if (contentType == null) {
return null;
}
Matcher m = charsetPattern.matcher(contentType);
if (m.find()) {
String charset = m.group(1).trim();
charset = charset.replace("charset=", "");
return validateCharset(charset);
}
return null;
}
private static String validateCharset(String cs) {
if (cs == null || cs.length() == 0) {
return null;
}
cs = cs.trim().replaceAll("[\"']", "");
try {
if (Charset.isSupported(cs)) {
return cs;
}
cs = cs.toUpperCase(Locale.ENGLISH);
if (Charset.isSupported(cs)) {
return cs;
}
} catch (IllegalCharsetNameException e) {
// if our this charset matching fails.... we just take the default
}
return null;
}
/**
* Creates a random string, suitable for use as a mime boundary
*/
static String mimeBoundary() {
final StringBuilder mime = StringUtil.borrowBuilder();
final Random rand = new Random();
for (int i = 0; i < boundaryLength; i++) {
mime.append(mimeBoundaryChars[rand.nextInt(mimeBoundaryChars.length)]);
}
return StringUtil.releaseBuilder(mime);
}
private static BomCharset detectCharsetFromBom(final ByteBuffer byteData) {
final Buffer buffer = byteData; // .mark and rewind used to return Buffer, now ByteBuffer, so cast for backward compat
buffer.mark();
byte[] bom = new byte[4];
if (byteData.remaining() >= bom.length) {
byteData.get(bom);
buffer.rewind();
}
if (bom[0] == 0x00 && bom[1] == 0x00 && bom[2] == (byte) 0xFE && bom[3] == (byte) 0xFF
|| // BE
bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE && bom[2] == 0x00 && bom[3] == 0x00) { // LE
return new BomCharset("UTF-32", false); // and I hope it's on your system
} else if (bom[0] == (byte) 0xFE && bom[1] == (byte) 0xFF
|| // BE
bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE) {
return new BomCharset("UTF-16", false); // in all Javas
} else if (bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF) {
return new BomCharset("UTF-8", true); // in all Javas
// 16 and 32 decoders consume the BOM to determine be/le; utf-8 should be consumed here
}
return null;
}
private static class BomCharset {
private final String charset;
private final boolean offset;
public BomCharset(String charset, boolean offset) {
this.charset = charset;
this.offset = offset;
}
}
}