1package org.jsoup.helper;
2
3import org.jsoup.nodes.Document;
4import org.jsoup.nodes.Element;
5import org.jsoup.parser.Parser;
6
7import java.io.*;
8import java.nio.ByteBuffer;
9import java.nio.charset.Charset;
10import java.nio.charset.IllegalCharsetNameException;
11import java.util.regex.Matcher;
12import java.util.regex.Pattern;
13import java.util.Locale;
14
15/**
16 * Internal static utilities for handling data.
17 *
18 */
19public class DataUtil {
20 private static final Pattern charsetPattern = Pattern.compile("(?i)\\bcharset=\\s*(?:\"|')?([^\\s,;\"']*)");
21 static final String defaultCharset = "UTF-8"; // used if not found in header or meta charset
22 private static final int bufferSize = 0x20000; // ~130K.
23
24 private DataUtil() {}
25
26 /**
…lines 27–81 unchanged (55 lines)
82 Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first();
83 if (meta != null) { // if not found, will keep utf-8 as best attempt
84
85 String foundCharset;
86 if (meta.hasAttr("http-equiv")) {
87 foundCharset = getCharsetFromContentType(meta.attr("content"));
88 if (foundCharset == null && meta.hasAttr("charset")) {
89 try {
90 if (Charset.isSupported(meta.attr("charset"))) {
91 foundCharset = meta.attr("charset");
92 }
93 } catch (IllegalCharsetNameException e) {
94 foundCharset = null;
95 }
96 }
97 } else {
98 foundCharset = meta.attr("charset");
99 }
100
101 if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { // need to re-decode
102 foundCharset = foundCharset.trim().replaceAll("[\"']", "");
103 charsetName = foundCharset;
104 byteData.rewind();
105 docData = Charset.forName(foundCharset).decode(byteData).toString();
106 doc = null;
107 }
108 }
…lines 109–165 unchanged (57 lines)
166 */
167 static String getCharsetFromContentType(String contentType) {
168 if (contentType == null) return null;
169 Matcher m = charsetPattern.matcher(contentType);
170 if (m.find()) {
171 String charset = m.group(1).trim();
172 charset = charset.replace("charset=", "");
173 if (charset.isEmpty()) return null;
174 try {
175 if (Charset.isSupported(charset)) return charset;
176 charset = charset.toUpperCase(Locale.ENGLISH);
177 if (Charset.isSupported(charset)) return charset;
178 } catch (IllegalCharsetNameException e) {
179 // if our advanced charset matching fails.... we just take the default
180 return null;
181 }
182 }
183 return null;
184 }
185
186
187}
188