Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Licensed to the Apache Software Foundation (ASF) under one or more
    * contributor license agreements.  See the NOTICE file distributed with
    * this work for additional information regarding copyright ownership.
    * The ASF licenses this file to You 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.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation and was
   * originally based on software copyright (c) 1999, International
   * Business Machines, Inc., http://www.apache.org.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  
  package org.apache.jasper.xmlparser;
  
  import static org.jboss.web.JasperMessages.MESSAGES;
  
  import java.io.Reader;
  import java.util.Locale;
  
  
  public class XMLEncodingDetector {
      
      private InputStream stream;
      private String encoding;
      private boolean isEncodingSetInProlog;
      private boolean isBomPresent;
      private int skip;
      private Boolean isBigEndian;
      private Reader reader;
      
      // org.apache.xerces.impl.XMLEntityManager fields
      public static final int DEFAULT_BUFFER_SIZE = 2048;
      public static final int DEFAULT_XMLDECL_BUFFER_SIZE = 64;
      private boolean fAllowJavaEncodings;
      private SymbolTable fSymbolTable;
      private XMLEncodingDetector fCurrentEntity;
      private int fBufferSize = ;
      
      // org.apache.xerces.impl.XMLEntityManager.ScannedEntity fields
      private int lineNumber = 1;
      private int columnNumber = 1;
      private boolean literal;
      private char[] ch = new char[];
      private int position;
      private int count;
      private boolean mayReadChunks = false;
      
      // org.apache.xerces.impl.XMLScanner fields
      private XMLString fString = new XMLString();    
      private XMLStringBuffer fStringBuffer = new XMLStringBuffer();
      private XMLStringBuffer fStringBuffer2 = new XMLStringBuffer();
      private final static String fVersionSymbol = "version";
      private final static String fEncodingSymbol = "encoding";
      private final static String fStandaloneSymbol = "standalone";
      
      // org.apache.xerces.impl.XMLDocumentFragmentScannerImpl fields
      private int fMarkupDepth = 0;
      private String[] fStrings = new String[3];
  
      private ErrorDispatcher err;

    
Constructor
  
      public XMLEncodingDetector() {
           = new SymbolTable();
           = this;
      }

    
Autodetects the encoding of the XML document supplied by the given input stream. Encoding autodetection is done according to the XML 1.0 specification, Appendix F.1: Detection Without External Encoding Information.

Returns:
Two-element array, where the first element (of type java.lang.String) contains the name of the (auto)detected encoding, and the second element (of type java.lang.Boolean) specifies whether the encoding was specified using the 'encoding' attribute of an XML prolog (TRUE) or autodetected (FALSE).
 
     public static Object[] getEncoding(String fnameJarFile jarFile,
                                        JspCompilationContext ctxt,
                                        ErrorDispatcher err)
         throws IOExceptionJasperException
     {
         InputStream inStream = JspUtil.getInputStream(fnamejarFilectxt,
                                                       err);
         XMLEncodingDetector detector = new XMLEncodingDetector();
         Object[] ret = detector.getEncoding(inStreamerr);
         inStream.close();
 
         return ret;
     }
 
     private Object[] getEncoding(InputStream inErrorDispatcher err)
         throws IOExceptionJasperException
     {
         this. = in;
         this.=err;
         createInitialReader();
         scanXMLDecl();
 	
         return new Object[] { this.,
                               Boolean.valueOf(this.),
                               Boolean.valueOf(this.),
                               Integer.valueOf(this.) };
     }
     
     // stub method
     void endEntity() {
     }
     
     // Adapted from:
     // org.apache.xerces.impl.XMLEntityManager.startEntity()
     private void createInitialReader() throws IOExceptionJasperException {
 
 	// wrap this stream in RewindableInputStream
 
 	// perform auto-detect of encoding if necessary
 	if ( == null) {
 	    // read first four bytes and determine encoding
 	    final byte[] b4 = new byte[4];
 	    int count = 0;
 	    for (; count<4; count++ ) {
 		b4[count] = (byte).read();
 	    }
 	    if (count == 4) {
 		Object [] encodingDesc = getEncodingName(b4count);
 		 = (String)(encodingDesc[0]);
 		 = (Boolean)(encodingDesc[1]);
         
         if (encodingDesc.length > 3) {
              = (Boolean)(encodingDesc[2]);
              = (Integer)(encodingDesc[3]);
         } else {
              = true;
              = (Integer)(encodingDesc[2]);
         }
 
 		// Special case UTF-8 files with BOM created by Microsoft
 		// tools. It's more efficient to consume the BOM than make
 		// the reader perform extra checks. -Ac
 		if (count > 2 && .equals("UTF-8")) {
 		    int b0 = b4[0] & 0xFF;
 		    int b1 = b4[1] & 0xFF;
 		    int b2 = b4[2] & 0xFF;
 		    if (b0 == 0xEF && b1 == 0xBB && b2 == 0xBF) {
 			// ignore first three bytes...
 		    }
 		}
 	    } else {
 	    }
 	}
     }
 
     // Adapted from:
     // org.apache.xerces.impl.XMLEntityManager.createReader
     
Creates a reader capable of reading the given input stream in the specified encoding.

Parameters:
inputStream The input stream.
encoding The encoding name that the input stream is encoded using. If the user has specified that Java encoding names are allowed, then the encoding name may be a Java encoding name; otherwise, it is an ianaEncoding name.
isBigEndian For encodings (like uCS-4), whose names cannot specify a byte order, this tells whether the order is bigEndian. null means unknown or not relevant.
Returns:
Returns a reader.
 
     private Reader createReader(InputStream inputStreamString encoding,
 				Boolean isBigEndian)
                 throws IOExceptionJasperException {
 
         // normalize encoding name
         if (encoding == null) {
             encoding = "UTF-8";
         }
 
         // try to use an optimized reader
         String ENCODING = encoding.toUpperCase(.);
         if (ENCODING.equals("UTF-8")) {
             return new UTF8Reader(inputStream);
         }
         if (ENCODING.equals("US-ASCII")) {
             return new ASCIIReader(inputStream);
         }
         if (ENCODING.equals("ISO-10646-UCS-4")) {
             if (isBigEndian != null) {
                 boolean isBE = isBigEndian.booleanValue();
                 if (isBE) {
                     return new UCSReader(inputStream.);
                 } else {
                     return new UCSReader(inputStream.);
                 }
             } else {
                 .jspError(.unsupportedByteOrderForEncoding(encoding));
             }
         }
         if (ENCODING.equals("ISO-10646-UCS-2")) {
             if (isBigEndian != null) { // sould never happen with this encoding...
                 boolean isBE = isBigEndian.booleanValue();
                 if (isBE) {
                     return new UCSReader(inputStream.);
                 } else {
                     return new UCSReader(inputStream.);
                 }
             } else {
                 .jspError(.unsupportedByteOrderForEncoding(encoding));
             }
         }
 
         // check for valid name
         boolean validIANA = XMLChar.isValidIANAEncoding(encoding);
         boolean validJava = XMLChar.isValidJavaEncoding(encoding);
         if (!validIANA || ( && !validJava)) {
             .jspError(.invalidEncodingDeclared(encoding));
             // NOTE: AndyH suggested that, on failure, we use ISO Latin 1
             //       because every byte is a valid ISO Latin 1 character.
             //       It may not translate correctly but if we failed on
             //       the encoding anyway, then we're expecting the content
             //       of the document to be bad. This will just prevent an
             //       invalid UTF-8 sequence to be detected. This is only
             //       important when continue-after-fatal-error is turned
             //       on. -Ac
             encoding = "ISO-8859-1";
         }
 
         // try to use a Java reader
         String javaEncoding = EncodingMap.getIANA2JavaMapping(ENCODING);
         if (javaEncoding == null) {
             if () {
 		javaEncoding = encoding;
             } else {
                 .jspError(.invalidEncodingDeclared(encoding));
                 // see comment above.
                 javaEncoding = "ISO8859_1";
             }
         }
         return new InputStreamReader(inputStreamjavaEncoding);
 
     } // createReader(InputStream,String, Boolean): Reader
 
     // Adapted from:
     // org.apache.xerces.impl.XMLEntityManager.getEncodingName
     
Returns the IANA encoding name that is auto-detected from the bytes specified, with the endian-ness of that encoding where appropriate.

Parameters:
b4 The first four bytes of the input.
count The number of bytes actually read.
Returns:
a 2-element array: the first element, an IANA-encoding string, the second element a Boolean which is true iff the document is big endian, false if it's little-endian, and null if the distinction isn't relevant.
 
     private Object[] getEncodingName(byte[] b4int count) {
 
         if (count < 2) {
             return new Object[]{"UTF-8"null., Integer.valueOf(0)};
         }
 
         // UTF-16, with BOM
         int b0 = b4[0] & 0xFF;
         int b1 = b4[1] & 0xFF;
         if (b0 == 0xFE && b1 == 0xFF) {
             // UTF-16, big-endian
             return new Object [] {"UTF-16BE"., Integer.valueOf(2)};
         }
         if (b0 == 0xFF && b1 == 0xFE) {
             // UTF-16, little-endian
             return new Object [] {"UTF-16LE"., Integer.valueOf(2)};
         }
 
         // default to UTF-8 if we don't have enough bytes to make a
         // good determination of the encoding
         if (count < 3) {
             return new Object [] {"UTF-8"null., Integer.valueOf(0)};
         }
 
         // UTF-8 with a BOM
         int b2 = b4[2] & 0xFF;
         if (b0 == 0xEF && b1 == 0xBB && b2 == 0xBF) {
             return new Object [] {"UTF-8"null, Integer.valueOf(3)};
         }
 
         // default to UTF-8 if we don't have enough bytes to make a
         // good determination of the encoding
         if (count < 4) {
             return new Object [] {"UTF-8"null, Integer.valueOf(0)};
         }
 
         // other encodings
         int b3 = b4[3] & 0xFF;
         if (b0 == 0x00 && b1 == 0x00 && b2 == 0x00 && b3 == 0x3C) {
             // UCS-4, big endian (1234)
             return new Object [] {"ISO-10646-UCS-4"new Boolean(true), Integer.valueOf(4)};
         }
         if (b0 == 0x3C && b1 == 0x00 && b2 == 0x00 && b3 == 0x00) {
             // UCS-4, little endian (4321)
             return new Object [] {"ISO-10646-UCS-4"new Boolean(false), Integer.valueOf(4)};
         }
         if (b0 == 0x00 && b1 == 0x00 && b2 == 0x3C && b3 == 0x00) {
             // UCS-4, unusual octet order (2143)
             // REVISIT: What should this be?
             return new Object [] {"ISO-10646-UCS-4"null, Integer.valueOf(4)};
         }
         if (b0 == 0x00 && b1 == 0x3C && b2 == 0x00 && b3 == 0x00) {
             // UCS-4, unusual octect order (3412)
             // REVISIT: What should this be?
             return new Object [] {"ISO-10646-UCS-4"null, Integer.valueOf(4)};
         }
         if (b0 == 0x00 && b1 == 0x3C && b2 == 0x00 && b3 == 0x3F) {
             // UTF-16, big-endian, no BOM
             // (or could turn out to be UCS-2...
             // REVISIT: What should this be?
             return new Object [] {"UTF-16BE"new Boolean(true), Integer.valueOf(4)};
         }
         if (b0 == 0x3C && b1 == 0x00 && b2 == 0x3F && b3 == 0x00) {
             // UTF-16, little-endian, no BOM
             // (or could turn out to be UCS-2...
             return new Object [] {"UTF-16LE"new Boolean(false), Integer.valueOf(4)};
         }
         if (b0 == 0x4C && b1 == 0x6F && b2 == 0xA7 && b3 == 0x94) {
             // EBCDIC
             // a la xerces1, return CP037 instead of EBCDIC here
             return new Object [] {"CP037"null, Integer.valueOf(4)};
         }
 
         // default encoding
         return new Object [] {"UTF-8"null., Integer.valueOf(0)};
 
     }
 
     // Adapted from:
     // org.apache.xerces.impl.XMLEntityManager.EntityScanner.isExternal
     
Returns true if the current entity being scanned is external.
 
     public boolean isExternal() {
 	return true;
     }
 
     // Adapted from:
     // org.apache.xerces.impl.XMLEntityManager.EntityScanner.peekChar
     
Returns the next character on the input.

Note: The character is not consumed.

Throws:
java.io.IOException Thrown if i/o error occurs.
java.io.EOFException Thrown on end of file.
 
     public int peekChar() throws IOException {
 	
 	// load more characters, if needed
 	    load(0, true);
 	}
 	
 	// peek at character
 
 	// return peeked character
 	    return c != '\r' ? c : '\n';
 	}
 	else {
 	    return c;
 	}
 	
     } // peekChar():int
     
     // Adapted from:
     // org.apache.xerces.impl.XMLEntityManager.EntityScanner.scanChar
     
Returns the next character on the input.

Note: The character is consumed.

Throws:
java.io.IOException Thrown if i/o error occurs.
java.io.EOFException Thrown on end of file.
 
     public int scanChar() throws IOException {
 
 	// load more characters, if needed
 	    load(0, true);
 	}
 
 	// scan character
 	boolean external = false;
 	if (c == '\n' ||
 	    (c == '\r' && (external = .isExternal()))) {
 		.[0] = (char)c;
 		load(1, false);
 	    }
 	    if (c == '\r' && external) {
 		if (.[.++] != '\n') {
 		}
 		c = '\n';
 	    }
 	}
 
 	// return character that was scanned
 	return c;
 	
     }
 
     // Adapted from:
     // org.apache.xerces.impl.XMLEntityManager.EntityScanner.scanName
     
Returns a string matching the Name production appearing immediately on the input as a symbol, or null if no Name string is present.

Note: The Name characters are consumed.

Note: The string returned must be a symbol. The SymbolTable can be used for this purpose.

Throws:
java.io.IOException Thrown if i/o error occurs.
java.io.EOFException Thrown on end of file.
See also:
SymbolTable
XMLChar.isName(int)
XMLChar.isNameStart(int)
 
     public String scanName() throws IOException {
 	
 	// load more characters, if needed
 	    load(0, true);
 	}
 	
 	// scan name
 	int offset = .;
 	if (XMLChar.isNameStart(.[offset])) {
 	    if (++. == .) {
 		offset = 0;
 		if (load(1, false)) {
 							   0, 1);
 		    return symbol;
 		}
 	    }
 	    while (XMLChar.isName(.[.])) {
 		    int length = . - offset;
 		    if (length == ) {
 			// bad luck we have to resize our buffer
 			char[] tmp = new char[ * 2];
 			System.arraycopy(.offset,
 					 tmp, 0, length);
 			. = tmp;
 			 *= 2;
 		    } else {
 			System.arraycopy(.offset,
 					 ., 0, length);
 		    }
 		    offset = 0;
 		    if (load(lengthfalse)) {
 			break;
 		    }
 		}
 	    }
 	}
 	int length = . - offset;
 
 	// return name
 	String symbol = null;
 	if (length > 0) {
 	    symbol = .addSymbol(.offsetlength);
 	}
 	return symbol;
 	
     }
 
     // Adapted from:
     // org.apache.xerces.impl.XMLEntityManager.EntityScanner.scanLiteral
     
Scans a range of attribute value data, setting the fields of the XMLString structure, appropriately.

Note: The characters are consumed.

Note: This method does not guarantee to return the longest run of attribute value data. This method may return before the quote character due to reaching the end of the input buffer or any other reason.

Note: The fields contained in the XMLString structure are not guaranteed to remain valid upon subsequent calls to the entity scanner. Therefore, the caller is responsible for immediately using the returned character data or making a copy of the character data.

Parameters:
quote The quote character that signifies the end of the attribute value data.
content The content structure to fill.
Returns:
Returns the next character on the input, if known. This value may be -1 but this does note designate end of file.
Throws:
java.io.IOException Thrown if i/o error occurs.
java.io.EOFException Thrown on end of file.
 
     public int scanLiteral(int quoteXMLString content)
 	throws IOException {
 
 	// load more characters, if needed
 	    load(0, true);
 	} else if (. == . - 1) {
 	    load(1, false);
 	    . = 0;
 	}
 
 	// normalize newlines
 	int offset = .;
 	int c = .[offset];
 	int newlines = 0;
 	boolean external = .isExternal();
 	if (c == '\n' || (c == '\r' && external)) {
 	    do {
 		if (c == '\r' && external) {
 		    newlines++;
 			offset = 0;
 			. = newlines;
 			if (load(newlinesfalse)) {
 			    break;
 			}
 		    }
 		    if (.[.] == '\n') {
 			offset++;
 		    }
    
NEWLINE NORMALIZATION *
 
 		    else {
 			newlines++;
 		    }
    
 
 		}
 		else if (c == '\n') {
 		    newlines++;
 			offset = 0;
 			. = newlines;
 			if (load(newlinesfalse)) {
 			    break;
 			}
 		    }
    
NEWLINE NORMALIZATION *** if (fCurrentEntity.ch[fCurrentEntity.position] == '\r' && external) { fCurrentEntity.position++; offset++; } /*
 
 		}
 		else {
 		    break;
 		}
 	    } while (. < . - 1);
 	    for (int i = offseti < .i++) {
 		.[i] = '\n';
 	    }
 	    int length = . - offset;
 	    if (. == . - 1) {
 		content.setValues(.offsetlength);
 		return -1;
 	    }
 	}
 
 	// scan literal value
 	    if ((c == quote &&
 		 (!. || external))
 		|| c == '%' || !XMLChar.isContent(c)) {
 		break;
 	    }
 	}
 	int length = . - offset;
 	. += length - newlines;
 	content.setValues(.offsetlength);
 
 	// return next character
 	    // NOTE: We don't want to accidentally signal the
 	    //       end of the literal if we're expanding an
 	    //       entity appearing in the literal. -Ac
 	    if (c == quote && .) {
 		c = -1;
 	    }
 	}
 	else {
 	    c = -1;
 	}
 	return c;
 
     }

    
Scans a range of character data up to the specified delimiter, setting the fields of the XMLString structure, appropriately.

Note: The characters are consumed.

Note: This assumes that the internal buffer is at least the same size, or bigger, than the length of the delimiter and that the delimiter contains at least one character.

Note: This method does not guarantee to return the longest run of character data. This method may return before the delimiter due to reaching the end of the input buffer or any other reason.

Note: The fields contained in the XMLString structure are not guaranteed to remain valid upon subsequent calls to the entity scanner. Therefore, the caller is responsible for immediately using the returned character data or making a copy of the character data.

Parameters:
delimiter The string that signifies the end of the character data to be scanned.
buffer The data structure to fill.
Returns:
Returns true if there is more data to scan, false otherwise.
Throws:
java.io.IOException Thrown if i/o error occurs.
java.io.EOFException Thrown on end of file.
 
     public boolean scanData(String delimiterXMLStringBuffer buffer)
 	throws IOException {
 
 	boolean done = false;
 	int delimLen = delimiter.length();
 	char charAt0 = delimiter.charAt(0);
 	boolean external = .isExternal();
 	do {
     
 	    // load more characters, if needed
     
 		load(0, true);
 	    }
 	    else if (. >= . - delimLen) {
 	    } 
 	    if (. >= . - delimLen) {
 		// something must be wrong with the input: e.g., file ends an
 		// unterminated comment
 			       length); 
 		load(0,true);
 		return false;
 	    }
     
 	    // normalize newlines
 	    int offset = .;
 	    int c = .[offset];
 	    int newlines = 0;
 	    if (c == '\n' || (c == '\r' && external)) {
 		do {
 		    if (c == '\r' && external) {
 			newlines++;
 			    offset = 0;
 			    . = newlines;
 			    if (load(newlinesfalse)) {
 				break;
 			    }
 			}
 			    offset++;
 			}
NEWLINE NORMALIZATION *
 
 			else {
 			    newlines++;
 			}
 		    }
 		    else if (c == '\n') {
 			newlines++;
 			    offset = 0;
 			    . = newlines;
 			    . = newlines;
 			    if (load(newlinesfalse)) {
 				break;
 			    }
 			}
 		    }
 		    else {
 			break;
 		    }
 		for (int i = offseti < .i++) {
 		    .[i] = '\n';
 		}
 		int length = . - offset;
 		    buffer.append(.offsetlength);
 		    return true;
 		}
 	    }
     
 	    // iterate over buffer looking for delimiter
 	OUTER: while (. < .) {
 	    if (c == charAt0) {
 		// looks like we just hit the delimiter
 		int delimOffset = . - 1;
 		for (int i = 1; i < delimLeni++) {
 			break OUTER;
 		    }
 		    if (delimiter.charAt(i) != c) {
 			break;
 		    }
 		}
 		if (. == delimOffset + delimLen) {
 		    done = true;
 		    break;
 		}
 	    }
 	    else if (c == '\n' || (external && c == '\r')) {
 		break;
 	    }
 	    else if (XMLChar.isInvalid(c)) {
 		int length = . - offset;
 		. += length - newlines;
 		buffer.append(.offsetlength); 
 		return true;
 	    }
 	}
 	    int length = . - offset;
 	    . += length - newlines;
 	    if (done) {
 		length -= delimLen;
 	    }
 	    buffer.append (.offsetlength);
     
 	    // return true if string was skipped
 	} while (!done);
 	return !done;
 
     }
 
     // Adapted from:
     // org.apache.xerces.impl.XMLEntityManager.EntityScanner.skipChar
     
Skips a character appearing immediately on the input.

Note: The character is consumed only if it matches the specified character.

Parameters:
c The character to skip.
Returns:
Returns true if the character was skipped.
Throws:
java.io.IOException Thrown if i/o error occurs.
java.io.EOFException Thrown on end of file.
 
     public boolean skipChar(int cthrows IOException {
 
 	// load more characters, if needed
 	    load(0, true);
 	}
 
 	// skip character
 	if (cc == c) {
 	    if (c == '\n') {
 	    }
 	    else {
 	    }
 	    return true;
 	} else if (c == '\n' && cc == '\r' && .isExternal()) {
 	    // handle newlines
 		.[0] = (char)cc;
 		load(1, false);
 	    }
 	    if (.[.] == '\n') {
 	    }
 	    return true;
 	}
 
 	// character was not skipped
 	return false;
 
     }
 
     // Adapted from:
     // org.apache.xerces.impl.XMLEntityManager.EntityScanner.skipSpaces
     
Skips space characters appearing immediately on the input.

Note: The characters are consumed only if they are space characters.

Returns:
Returns true if at least one space character was skipped.
Throws:
java.io.IOException Thrown if i/o error occurs.
java.io.EOFException Thrown on end of file.
See also:
XMLChar.isSpace(int)
 
     public boolean skipSpaces() throws IOException {
 
 	// load more characters, if needed
 	    load(0, true);
 	}
 
 	// skip spaces
 	if (XMLChar.isSpace(c)) {
 	    boolean external = .isExternal();
 	    do {
 		boolean entityChanged = false;
 		// handle newlines
 		if (c == '\n' || (external && c == '\r')) {
 		    if (. == . - 1) {
 			.[0] = (char)c;
 			entityChanged = load(1, true);
 			if (!entityChanged)
                                 // the load change the position to be 1,
                                 // need to restore it when entity not changed
 			    . = 0;
 		    }
 		    if (c == '\r' && external) {
 			// REVISIT: Does this need to be updated to fix the
 			//          #x0D ^#x0A newline normalization problem? -Ac
 			if (.[++.] != '\n') {
 			}
 		    }
    
NEWLINE NORMALIZATION *** else { if (fCurrentEntity.ch[fCurrentEntity.position + 1] == '\r' && external) { fCurrentEntity.position++; } } /*
 
 		}
 		else {
 		}
 		// load more characters, if needed
 		if (!entityChanged)
 		    load(0, true);
 		}
 	    } while (XMLChar.isSpace(c = .[.]));
 	    return true;
 	}
 
 	// no spaces were found
 	return false;
 
     }

    
Skips the specified string appearing immediately on the input.

Note: The characters are consumed only if they are space characters.

Parameters:
s The string to skip.
Returns:
Returns true if the string was skipped.
Throws:
java.io.IOException Thrown if i/o error occurs.
java.io.EOFException Thrown on end of file.
 
     public boolean skipString(String sthrows IOException {
 
 	// load more characters, if needed
 	    load(0, true);
 	}
 
 	// skip string
 	final int length = s.length();
 	for (int i = 0; i < lengthi++) {
 	    char c = .[.++];
 	    if (c != s.charAt(i)) {
 		. -= i + 1;
 		return false;
 	    }
 	    if (i < length - 1 && . == .) {
 		System.arraycopy(.. - i - 1, ., 0, i + 1);
 		// REVISIT: Can a string to be skipped cross an
 		//          entity boundary? -Ac
 		if (load(i + 1, false)) {
 		    . -= i + 1;
 		    return false;
 		}
 	    }
 	}
 	return true;
 
     }
 
     // Adapted from:
     // org.apache.xerces.impl.XMLEntityManager.EntityScanner.load
     
Loads a chunk of text.

Parameters:
offset The offset into the character buffer to read the next batch of characters.
changeEntity True if the load should change entities at the end of the entity, otherwise leave the current entity in place and the entity boundary will be signaled by the return value.
Returns:
Returns true if the entity changed as a result of this load operation.
    final boolean load(int offsetboolean changeEntity)
	throws IOException {
	// read characters
	    (.. - offset):
	int count = ..read(.offset,
					       length);
	// reset count and position
	boolean entityChanged = false;
	if (count != -1) {
	    if (count != 0) {
		. = count + offset;
	    }
	// end of this entity
	else {
	    . = offset;
	    . = offset;
	    entityChanged = true;
	    if (changeEntity) {
		if ( == null) {
		    throw new EOFException();
		// handle the trailing edges
		    load(0, false);
	    }
	return entityChanged;
    }
    // Adapted from:
    // org.apache.xerces.impl.XMLEntityManager.RewindableInputStream
    
This class wraps the byte inputstreams we're presented with. We need it because java.io.InputStreams don't provide functionality to reread processed bytes, and they have a habit of reading more than one character when you call their read() methods. This means that, once we discover the true (declared) encoding of a document, we can neither backtrack to read the whole doc again nor start reading where we are with a new reader. This class allows rewinding an inputStream by allowing a mark to be set, and the stream reset to that position. The class assumes that it needs to read one character per invocation when it's read() method is inovked, but uses the underlying InputStream's read(char[], offset length) method--it won't buffer data read this way!

Author(s):
Neil Graham, IBM
Glenn Marcy, IBM
    private final class RewindableInputStream extends InputStream {
        private InputStream fInputStream;
        private byte[] fData;
        private int fStartOffset;
        private int fEndOffset;
        private int fOffset;
        private int fLength;
        private int fMark;
        public RewindableInputStream(InputStream is) {
             = new byte[];
             = is;
             = 0;
             = -1;
             = 0;
             = 0;
             = 0;
        }
        public void setStartOffset(int offset) {
             = offset;
        }
        public void rewind() {
             = ;
        }
        public int read() throws IOException {
            int b = 0;
            if ( < ) {
                return [++] & 0xff;
            }
            if ( == ) {
                return -1;
            }
            if ( == .) {
                byte[] newData = new byte[ << 1];
                System.arraycopy(, 0, newData, 0, );
                 = newData;
            }
            b = .read();
            if (b == -1) {
                 = ;
                return -1;
            }
            [++] = (byte)b;
            ++;
            return b & 0xff;
        }
        public int read(byte[] bint offint lenthrows IOException {
            int bytesLeft =  - ;
            if (bytesLeft == 0) {
                if ( == ) {
                    return -1;
                }
                // better get some more for the voracious reader...
                if (.) {
                    return .read(bofflen);
                }
                int returnedVal = read();
                if (returnedVal == -1) {
                     = ;
                    return -1;
                }
                b[off] = (byte)returnedVal;
                return 1;
            }
            if (len < bytesLeft) {
                if (len <= 0) {
                    return 0;
                }
            }
            else {
                len = bytesLeft;
            }
            if (b != null) {
                System.arraycopy(bofflen);
            }
             += len;
            return len;
        }
        public long skip(long n)
            throws IOException
        {
            int bytesLeft;
            if (n <= 0) {
                return 0;
            }
            bytesLeft =  - ;
            if (bytesLeft == 0) {
                if ( == ) {
                    return 0;
                }
                return .skip(n);
            }
            if (n <= bytesLeft) {
                 += n;
                return n;
            }
             += bytesLeft;
            if ( == ) {
                return bytesLeft;
            }
            n -= bytesLeft;
	    /*
	     * In a manner of speaking, when this class isn't permitting more
	     * than one byte at a time to be read, it is "blocking".  The
	     * available() method should indicate how much can be read without
	     * blocking, so while we're in this mode, it should only indicate
	     * that bytes in its buffer are available; otherwise, the result of
	     * available() on the underlying InputStream is appropriate.
	     */
            return .skip(n) + bytesLeft;
        }
        public int available() throws IOException {
            int bytesLeft =  - ;
            if (bytesLeft == 0) {
                if ( == ) {
                    return -1;
                }
                return . ? .available()
		    : 0;
            }
            return bytesLeft;
        }