/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* This is how the parser talks to its input entities, of all kinds.
* The entities are in a stack.
* <p/>
* <P> For internal entities, the character arrays are referenced here,
* and read from as needed (they're read-only). External entities have
* mutable buffers, that are read into as needed.
* <p/>
* <P> <em>Note:</em> This maps CRLF (and CR) to LF without regard for
* whether it's in an external (parsed) entity or not. The XML 1.0 spec
* is inconsistent in explaining EOL handling; this is the sensible way.
*
* @author David Brownell
* @author Janet Koenig
* @version 1.4 00/08/05
*/
public class InputEntity {
private char buf [];
private boolean returnedFirstHalf = false;
private boolean maybeInCRLF = false;
// name of entity (never main document or unnamed DTD PE)
// for system and public IDs in diagnostics
// this is a buffer; some buffers can be replenished.
private boolean isClosed;
private int startRemember;
// record if this is a PE, so endParsedEntity won't be called
private boolean isPE;
// InputStreamReader throws an internal per-read exception, so
// we minimize reads. We also add a byte to compensate for the
// "ungetc" byte we keep, so that our downstream reads are as
// nicely sized as we can make them.
retval.errHandler = h;
return retval;
}
private InputEntity() {
}
//
// predicate: return true iff this is an internal entity reader,
// and so may safely be "popped" as needed. external entities have
// syntax to uphold; internal parameter entities have at most validity
// constraints to monitor. also, only external entities get decent
// location diagnostics.
//
public boolean isInternal() {
}
//
// predicate: return true iff this is the toplevel document
//
public boolean isDocument() {
}
//
// predicate: return true iff this is a PE expansion (so that
// LexicalEventListner.endParsedEntity won't be called)
//
public boolean isParameterEntity() {
return isPE;
}
//
// return name of current entity
//
return name;
}
//
// use this for an external parsed entity
//
boolean isPE)
throws IOException, SAXException {
.openStream());
in.getEncoding());
else
}
}
//
// use this for an internal parsed entity; buffer is readonly
//
throws SAXException {
buf = b;
}
throws SAXException {
return;
}
}
// caller has ensured there's nothing left to read
close();
return next;
}
/**
* returns true iff there's no more data to consume ...
*/
// called to ensure WF-ness of included entities and to pop
// input entities appropriately ... EOF is not always legal.
fillbuf();
} else
return false;
}
/**
* Returns the name of the encoding in use, else null; the name
* returned is in as standard a form as we can get.
*/
return null;
// XXX prefer a java2std() call to normalize names...
if (reader instanceof InputStreamReader)
return null;
}
/**
* returns the next name char, or NUL ... faster than getc(),
* and the common "name or nmtoken must be next" case won't
* need ungetc().
*/
fillbuf();
if (XmlChars.isNameChar(c))
return c;
start--;
}
return 0;
}
/**
* gets the next Java character -- might be part of an XML
* text character represented by a surrogate pair, or be
* the end of the entity.
*/
fillbuf();
// [2] Char ::= #x0009 | #x000A | #x000D
// | [#x0020-#xD7FF]
// | [#xE000-#xFFFD]
// plus surrogate _pairs_ representing [#x10000-#x10ffff]
if (returnedFirstHalf) {
if (c >= 0xdc00 && c <= 0xdfff) {
returnedFirstHalf = false;
return c;
} else
}
if ((c >= 0x0020 && c <= 0xD7FF)
|| c == 0x0009
// no surrogates!
|| (c >= 0xE000 && c <= 0xFFFD))
return c;
//
// CRLF and CR are both line ends; map both to LF, and
// keep line count correct.
//
else if (c == '\r' && !isInternal()) {
maybeInCRLF = true;
c = getc();
if (c != '\n')
ungetc();
maybeInCRLF = false;
lineNumber++;
return '\n';
} else if (c == '\n' || c == '\r') { // LF, or 2nd char in CRLF
if (!isInternal() && !maybeInCRLF)
lineNumber++;
return c;
}
// surrogates...
if (c >= 0xd800 && c < 0xdc00) {
returnedFirstHalf = true;
return c;
}
}
throw new EndOfInputException();
}
/**
* lookahead one character
*/
fillbuf();
start++;
return true;
} else
return false;
}
return false;
}
/**
* two character pushback is guaranteed
*/
public void ungetc() {
if (start == 0)
throw new InternalError("ungetc");
start--;
if (!isInternal())
lineNumber--;
} else if (returnedFirstHalf)
returnedFirstHalf = false;
}
/**
* optional grammatical whitespace (discarded)
*/
public boolean maybeWhitespace()
throws IOException, SAXException {
char c;
boolean isSpace = false;
boolean sawCR = false;
// [3] S ::= #20 | #09 | #0D | #0A
for (; ;) {
fillbuf();
return isSpace;
if (c == 0x20 || c == 0x09 || c == '\n' || c == '\r') {
isSpace = true;
//
// CR, LF are line endings ... CLRF is one, not two!
//
if (!(c == '\n' && sawCR)) {
lineNumber++;
sawCR = false;
}
if (c == '\r')
sawCR = true;
}
} else {
start--;
return isSpace;
}
}
}
/**
* normal content; whitespace in markup may be handled
* specially if the parser uses the content model.
* <p/>
* <P> content terminates with markup delimiter characters,
* namely ampersand (&amp;) and left angle bracket (&lt;).
* <p/>
* <P> the document handler's characters() method is called
* on all the content found
*/
/*ElementValidator validator*/)
throws IOException, SAXException {
// [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
int first; // first char to return
int last; // last char to return
boolean sawContent; // sent any chars?
char c;
// deliver right out of the buffer, until delimiter, EOF,
// or error, refilling as we go
// buffer empty?
// validator.text ();
sawContent = true;
}
if (isEOF()) // calls fillbuf
return sawContent;
continue;
}
//
// pass most chars through ASAP; this inlines the code of
// [2] !XmlChars.isChar(c) leaving only characters needing
// special treatment ... line ends, surrogates, and:
// 0x0026 == '&'
// 0x003C == '<'
// 0x005D == ']'
// Comparisons ordered for speed on 'typical' text
//
if ((c > 0x005D && c <= 0xD7FF) // a-z and more
|| (c < 0x0026 && c >= 0x0020) // space & punct
|| (c > 0x003C && c < 0x005D) // A-Z & punct
|| (c > 0x0026 && c < 0x003C) // 0-9 & punct
|| c == 0x0009
|| (c >= 0xE000 && c <= 0xFFFD)
)
continue;
// terminate on markup delimiters
if (c == '<' || c == '&')
break;
// count lines
if (c == '\n') {
if (!isInternal())
lineNumber++;
continue;
}
// External entities get CR, CRLF --> LF mapping
// Internal ones got it already, and we can't repeat
// else we break char ref handling!!
if (c == '\r') {
if (isInternal())
continue;
sawContent = true;
lineNumber++;
last++;
} else { // CR at end of buffer
// XXX case not yet handled: CRLF here will look like two lines
}
continue;
}
// ']]>' is a WF error -- must fail if we see it
if (c == ']') {
// for suspicious end-of-buffer cases, get more data
// into the buffer to rule out this sequence.
case 2:
continue;
// FALLTHROUGH
case 1:
continue;
throw new InternalError("fillbuf");
last--;
// validator.text ();
sawContent = true;
}
fillbuf();
continue;
// otherwise any "]]>" would be buffered, and we can
// see right away if that's what we have
default:
continue;
}
}
// correctly paired surrogates are OK
if (c >= 0xd800 && c <= 0xdfff) {
// validator.text ();
sawContent = true;
}
if (isEOF()) { // calls fillbuf
fatal("P-081",
}
continue;
}
if (checkSurrogatePair(last))
last++;
else {
last--;
// also terminate on surrogate pair oddities
break;
}
continue;
}
}
return sawContent;
// validator.text ();
return true;
}
/**
* CDATA -- character data, terminated by "]]>" and optionally
* including unescaped markup delimiters (ampersand and left angle
* bracket). This should otherwise be exactly like character data,
* modulo differences in error report details.
* <p/>
* <P> The document handler's characters() or ignorableWhitespace()
* methods are invoked on all the character data found
*
* @param docHandler gets callbacks for character data
* @param ignorableWhitespace if true, whitespace characters will
* be reported using docHandler.ignorableWhitespace(); implicitly,
* non-whitespace characters will cause validation errors
* @param whitespaceInvalidMessage if true, ignorable whitespace
* causes a validity error report as well as a callback
*/
/*ElementValidator validator,*/
boolean ignorableWhitespace,
throws IOException, SAXException {
// [18] CDSect ::= CDStart CData CDEnd
// [19] CDStart ::= '<![CDATA['
// [20] CData ::= (Char* - (Char* ']]>' Char*))
// [21] CDEnd ::= ']]>'
// caller peeked the leading '<' ...
return false;
// only a literal ']]>' stops this ...
int last;
for (; ;) { // until ']]>' seen
boolean done = false;
char c;
// don't report ignorable whitespace as "text" for
// validation purposes.
boolean white = ignorableWhitespace;
//
// Reject illegal characters.
//
white = false;
if (c >= 0xd800 && c <= 0xdfff) {
if (checkSurrogatePair(last)) {
last++;
continue;
} else {
last--;
break;
}
}
}
if (c == '\n') {
if (!isInternal())
lineNumber++;
continue;
}
if (c == '\r') {
if (isInternal())
continue;
if (white) {
if (whitespaceInvalidMessage != null)
} else {
// validator.text ();
}
lineNumber++;
last++;
} else { // CR at end of buffer
// XXX case not yet handled ... as above
}
continue;
}
if (c != ']') {
if (c != ' ' && c != '\t')
white = false;
continue;
}
done = true;
break;
}
white = false;
continue;
} else {
//last--;
break;
}
}
if (white) {
if (whitespaceInvalidMessage != null)
} else {
// validator.text ();
}
if (done) {
break;
}
if (isEOF())
}
return true;
}
// return false to backstep at end of buffer)
throws SAXException {
return false;
return true;
});
return false;
}
/**
* whitespace in markup (flagged to app, discardable)
* <p/>
* <P> the document handler's ignorableWhitespace() method
* is called on all the whitespace found
*/
throws IOException, SAXException {
char c;
boolean isSpace = false;
int first;
// [3] S ::= #20 | #09 | #0D | #0A
if (isSpace)
fillbuf();
}
return isSpace;
switch (c) {
case '\n':
if (!isInternal())
lineNumber++;
// XXX handles Macintosh line endings wrong
// fallthrough
case 0x09:
case 0x20:
isSpace = true;
continue;
case '\r':
isSpace = true;
if (!isInternal())
lineNumber++;
++start;
continue;
default:
ungetc();
if (isSpace)
return isSpace;
}
}
}
/**
* returns false iff 'next' string isn't as provided,
* else skips that text and returns true.
* <p/>
* <P> NOTE: two alternative string representations are
* both passed in, since one is faster.
*/
throws IOException, SAXException {
int len;
int i;
else
// buffer should hold the whole thing ... give it a
// chance for the end-of-buffer case and cope with EOF
// by letting fillbuf compact and fill
fillbuf();
// can't peek past EOF
return false;
// compare the string; consume iff it matches
return false;
}
} else {
return false;
}
}
// if the first fillbuf didn't get enough data, give
// fillbuf another chance to read
if (i < len) {
return false;
//
// This diagnostic "knows" that the only way big strings would
// fail to be peeked is where it's a symbol ... e.g. for an
// </EndTag> construct. That knowledge could also be applied
// to get rid of the symbol length constraint, since having
// the wrong symbol is a fatal error anyway ...
//
fillbuf();
}
return true;
}
//
// Support for reporting the internal DTD subset, so <!DOCTYPE...>
// declarations can be recreated. This is collected as a single
// string; such subsets are normally small, and many applications
// don't even care about this.
//
public void startRemembering() {
if (startRemember != 0)
throw new InternalError();
}
// If the internal subset crossed a buffer boundary, we
// created a temporary buffer.
if (rememberedText != null) {
start - startRemember);
} else
start - startRemember);
startRemember = 0;
return retval;
}
InputEntity current = this;
// don't report locations within internal entities!
}
/**
* Returns the public ID of this input source, if known
*/
if (where == this)
return input.getPublicId();
return where.getPublicId();
}
/**
* Returns the system ID of this input source, if known
*/
if (where == this)
return input.getSystemId();
return where.getSystemId();
}
/**
* Returns the current line number in this input source
*/
public int getLineNumber() {
if (where == this)
return lineNumber;
return where.getLineNumber();
}
/**
* returns -1; maintaining column numbers hurts performance
*/
public int getColumnNumber() {
return -1; // not maintained (speed)
}
//
// n.b. for non-EOF end-of-buffer cases, reader should return
// at least a handful of bytes so various lookaheads behave.
//
// two character pushback exists except at first; characters
// represented by surrogate pairs can't be pushed back (they'd
// only be in character data anyway).
//
// DTD exception thrown on char conversion problems; line number
// will be low, as a rule.
//
// don't touched fixed buffers, that'll usually
// change entity values (and isn't needed anyway)
// likewise, ignore closed streams
return;
// if remembering DTD text, copy!
if (startRemember != 0) {
if (rememberedText == null)
start - startRemember);
}
int len;
if (extra) // extra pushback
start--;
start = 0;
try {
} catch (UnsupportedEncodingException e) {
} catch (CharConversionException e) {
}
if (len >= 0)
else
close();
if (extra) // extra pushback
start++;
if (startRemember != 0)
// assert extra == true
startRemember = 1;
}
public void close() {
try {
isClosed = true;
} catch (IOException e) {
/* NOTHING */
}
}
throws SAXException {
SAXParseException x = new SAXParseException(DTDParser.messages.getMessage(locale, messageId, params), null);
// not continuable ... e.g. WF errors
close();
errHandler.fatalError(x);
throw x;
}
}