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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
|
/*
* Copyright (c) 2007 Henri Sivonen
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package nu.validator.htmlparser.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import nu.validator.htmlparser.common.ByteReadable;
import nu.validator.htmlparser.common.Heuristics;
import nu.validator.htmlparser.common.XmlViolationPolicy;
import nu.validator.htmlparser.extra.IcuDetectorSniffer;
import nu.validator.htmlparser.impl.Tokenizer;
import org.xml.sax.ErrorHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* Be very careful with this class. It is not a general-purpose subclass of of
* <code>Reader</code>. Instead, it is the minimal implementation that does
* what <code>Tokenizer</code> needs while being an instance of
* <code>Reader</code>.
*
* The only reason why this is a public class is that it needs to be visible to
* test code in another package.
*
* @version $Id$
* @author hsivonen
*/
public final class HtmlInputStreamReader extends Reader implements
ByteReadable, Locator {
private static final int SNIFFING_LIMIT = 1024;
private final InputStream inputStream;
private final ErrorHandler errorHandler;
private final Tokenizer tokenizer;
private final Driver driver;
private CharsetDecoder decoder = null;
private boolean sniffing = true;
private int limit = 0;
private int position = 0;
private int bytesRead = 0;
private boolean eofSeen = false;
private boolean shouldReadBytes = false;
private boolean charsetBoundaryPassed = false;
private final byte[] byteArray = new byte[4096]; // Length must be >=
// SNIFFING_LIMIT
private final ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
private boolean needToNotifyTokenizer = false;
private boolean flushing = false;
private int line = -1;
private int col = -1;
private int lineColPos;
private boolean hasPendingReplacementCharacter = false;
private boolean nextCharOnNewLine;
private boolean prevWasCR;
/**
* @param inputStream
* @param errorHandler
* @param locator
* @throws IOException
* @throws SAXException
*/
public HtmlInputStreamReader(InputStream inputStream,
ErrorHandler errorHandler, Tokenizer tokenizer, Driver driver,
Heuristics heuristics) throws SAXException, IOException {
this.inputStream = inputStream;
this.errorHandler = errorHandler;
this.tokenizer = tokenizer;
this.driver = driver;
this.sniffing = true;
Encoding encoding = (new BomSniffer(this)).sniff();
if (encoding == null) {
position = 0;
encoding = (new MetaSniffer(errorHandler, this)).sniff(this);
if (encoding == null
&& (heuristics == Heuristics.ICU || heuristics == Heuristics.ALL)) {
position = 0;
encoding = (new IcuDetectorSniffer(this)).sniff();
}
sniffing = false;
if (encoding == null) {
encoding = Encoding.WINDOWS1252;
}
if (driver != null) {
driver.setEncoding(encoding, Confidence.TENTATIVE);
}
} else {
if (encoding == Encoding.UTF8) {
if (driver != null) {
driver.setEncoding(Encoding.UTF8, Confidence.CERTAIN);
}
} else {
if (driver != null) {
driver.setEncoding(Encoding.UTF16, Confidence.CERTAIN);
}
}
}
this.decoder = encoding.newDecoder();
sniffing = false;
position = 0;
bytesRead = 0;
byteBuffer.position(position);
byteBuffer.limit(limit);
initDecoder();
}
/**
*
*/
private void initDecoder() {
this.decoder.onMalformedInput(CodingErrorAction.REPORT);
this.decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
}
public HtmlInputStreamReader(InputStream inputStream,
ErrorHandler errorHandler, Tokenizer tokenizer, Driver driver,
Encoding encoding) throws SAXException, IOException {
this.inputStream = inputStream;
this.errorHandler = errorHandler;
this.tokenizer = tokenizer;
this.driver = driver;
this.decoder = encoding.newDecoder();
this.sniffing = false;
position = 0;
bytesRead = 0;
byteBuffer.position(0);
byteBuffer.limit(0);
shouldReadBytes = true;
initDecoder();
}
@Override public void close() throws IOException {
inputStream.close();
}
@Override public int read(char[] charArray) throws IOException {
lineColPos = 0;
assert !sniffing;
assert charArray.length >= 2;
if (needToNotifyTokenizer) {
if (driver != null) {
driver.notifyAboutMetaBoundary();
}
needToNotifyTokenizer = false;
}
CharBuffer charBuffer = CharBuffer.wrap(charArray);
charBuffer.limit(charArray.length);
charBuffer.position(0);
if (flushing) {
decoder.flush(charBuffer);
// return -1 if zero
int cPos = charBuffer.position();
return cPos == 0 ? -1 : cPos;
}
if (hasPendingReplacementCharacter) {
charBuffer.put('\uFFFD');
hasPendingReplacementCharacter = false;
}
for (;;) {
if (shouldReadBytes) {
int oldLimit = byteBuffer.limit();
int readLen;
if (charsetBoundaryPassed) {
readLen = byteArray.length - oldLimit;
} else {
readLen = SNIFFING_LIMIT - oldLimit;
}
int num = inputStream.read(byteArray, oldLimit, readLen);
if (num == -1) {
eofSeen = true;
inputStream.close();
} else {
byteBuffer.position(0);
byteBuffer.limit(oldLimit + num);
}
shouldReadBytes = false;
}
boolean finalDecode = false;
for (;;) {
int oldBytePos = byteBuffer.position();
CoderResult cr = decoder.decode(byteBuffer, charBuffer,
finalDecode);
bytesRead += byteBuffer.position() - oldBytePos;
if (cr == CoderResult.OVERFLOW) {
// Decoder will remember surrogates
return charBuffer.position();
} else if (cr == CoderResult.UNDERFLOW) {
int remaining = byteBuffer.remaining();
if (!charsetBoundaryPassed) {
if (bytesRead + remaining >= SNIFFING_LIMIT) {
needToNotifyTokenizer = true;
charsetBoundaryPassed = true;
}
}
// XXX what happens if the entire byte buffer consists of
// a pathologically long malformed sequence?
// If the buffer was not fully consumed, there may be an
// incomplete byte sequence that needs to seed the next
// buffer.
if (remaining > 0) {
System.arraycopy(byteArray, byteBuffer.position(),
byteArray, 0, remaining);
}
byteBuffer.position(0);
byteBuffer.limit(remaining);
if (flushing) {
// The final decode was successful. Not sure if this
// ever happens.
// Let's get out in any case.
int cPos = charBuffer.position();
return cPos == 0 ? -1 : cPos;
} else if (eofSeen) {
// If there's something left, it isn't something that
// would be
// consumed in the middle of the stream. Rerun the loop
// once
// in the final mode.
shouldReadBytes = false;
finalDecode = true;
flushing = true;
continue;
} else {
// The usual stuff. Want more bytes next time.
shouldReadBytes = true;
// return -1 if zero
int cPos = charBuffer.position();
return cPos == 0 ? -1 : cPos;
}
} else {
// The result is in error. No need to test.
StringBuilder sb = new StringBuilder();
for (int i = 0; i < cr.length(); i++) {
if (i > 0) {
sb.append(", ");
}
sb.append('\u201C');
sb.append(Integer.toHexString(byteBuffer.get() & 0xFF));
bytesRead++;
sb.append('\u201D');
}
if (charBuffer.hasRemaining()) {
charBuffer.put('\uFFFD');
} else {
hasPendingReplacementCharacter = true;
}
calculateLineAndCol(charBuffer);
if (cr.isMalformed()) {
err("Malformed byte sequence: " + sb + ".");
} else if (cr.isUnmappable()) {
err("Unmappable byte sequence: " + sb + ".");
} else {
throw new RuntimeException(
"CoderResult was none of overflow, underflow, malformed or unmappable.");
}
if (finalDecode) {
// These were the last bytes of input. Return without
// relooping.
// return -1 if zero
int cPos = charBuffer.position();
return cPos == 0 ? -1 : cPos;
}
}
}
}
}
private void calculateLineAndCol(CharBuffer charBuffer) {
if (tokenizer != null) {
if (lineColPos == 0) {
line = tokenizer.getLine();
col = tokenizer.getCol();
nextCharOnNewLine = tokenizer.isNextCharOnNewLine();
prevWasCR = tokenizer.isPrevCR();
}
char[] charArray = charBuffer.array();
int i = lineColPos;
while (i < charBuffer.position()) {
char c;
if (nextCharOnNewLine) {
line++;
col = 1;
nextCharOnNewLine = false;
} else {
col++;
}
c = charArray[i];
switch (c) {
case '\r':
nextCharOnNewLine = true;
prevWasCR = true;
break;
case '\n':
if (prevWasCR) {
col--;
} else {
nextCharOnNewLine = true;
}
break;
}
i++;
}
lineColPos = i;
}
}
public int readByte() throws IOException {
if (!sniffing) {
throw new IllegalStateException(
"readByte() called when not in the sniffing state.");
}
if (position == SNIFFING_LIMIT) {
return -1;
} else if (position < limit) {
return byteArray[position++] & 0xFF;
} else {
int num = inputStream.read(byteArray, limit, SNIFFING_LIMIT - limit);
if (num == -1) {
return -1;
} else {
limit += num;
return byteArray[position++] & 0xFF;
}
}
}
public static void main(String[] args) {
CharsetDecoder dec = Charset.forName("UTF-8").newDecoder();
dec.onMalformedInput(CodingErrorAction.REPORT);
dec.onUnmappableCharacter(CodingErrorAction.REPORT);
byte[] bytes = { (byte) 0xF0, (byte) 0x9D, (byte) 0x80, (byte) 0x80 };
byte[] bytes2 = { (byte) 0xB8, (byte) 0x80, 0x63, 0x64, 0x65 };
ByteBuffer byteBuf = ByteBuffer.wrap(bytes);
ByteBuffer byteBuf2 = ByteBuffer.wrap(bytes2);
char[] chars = new char[1];
CharBuffer charBuf = CharBuffer.wrap(chars);
CoderResult cr = dec.decode(byteBuf, charBuf, false);
System.out.println(cr);
System.out.println(byteBuf);
// byteBuf.get();
cr = dec.decode(byteBuf2, charBuf, false);
System.out.println(cr);
System.out.println(byteBuf2);
}
public int getColumnNumber() {
if (tokenizer != null) {
return col;
}
return -1;
}
public int getLineNumber() {
if (tokenizer != null) {
return line;
}
return -1;
}
public String getPublicId() {
if (tokenizer != null) {
return tokenizer.getPublicId();
}
return null;
}
public String getSystemId() {
if (tokenizer != null) {
return tokenizer.getSystemId();
}
return null;
}
/**
* @param string
* @throws SAXException
*/
private void err(String message) throws IOException {
// TODO remove wrapping when changing read() to take a CharBuffer
try {
if (errorHandler != null) {
SAXParseException spe = new SAXParseException(message, this);
errorHandler.error(spe);
}
} catch (SAXException e) {
throw (IOException) new IOException(e.getMessage()).initCause(e);
}
}
public Charset getCharset() {
return decoder.charset();
}
/**
* @see java.io.Reader#read()
*/
@Override public int read() throws IOException {
throw new UnsupportedOperationException();
}
/**
* @see java.io.Reader#read(char[], int, int)
*/
@Override public int read(char[] cbuf, int off, int len) throws IOException {
throw new UnsupportedOperationException();
}
/**
* @see java.io.Reader#read(java.nio.CharBuffer)
*/
@Override public int read(CharBuffer target) throws IOException {
throw new UnsupportedOperationException();
}
public void switchEncoding(Encoding newEnc) {
this.decoder = newEnc.newDecoder();
initDecoder();
}
}
|