APIdia Launch Partner
Top Description Fields Constructors Methods
javax.swing.text.html.parser

public Class Parser

extends Object
implements DTDConstants
Class Inheritance
All Implemented Interfaces
javax.swing.text.html.parser.DTDConstants
Known Direct Subclasses
javax.swing.text.html.parser.DocumentParser
Imports
javax.swing.text.SimpleAttributeSet, .ChangedCharSetException, javax.swing.text.html.HTML, java.io.*, java.util.Hashtable, .Properties, .Vector, .Enumeration, java.net.URL

A simple DTD-driven HTML parser. The parser reads an HTML file from an InputStream and calls various methods (which should be overridden in a subclass) when tags and data are encountered.

Unfortunately there are many badly implemented HTML parsers out there, and as a result there are many badly formatted HTML files. This parser attempts to parse most HTML files. This means that the implementation sometimes deviates from the SGML specification in favor of HTML.

The parser treats \r and \r\n as \n. Newlines after starttags and before end tags are ignored just as specified in the SGML/HTML specification.

The html spec does not specify how spaces are to be coalesced very well. Specifically, the following scenarios are not discussed (note that a space should be used here, but I am using &nbsp to force the space to be displayed):

'<b>blah <i> <strike> foo' which can be treated as: '<b>blah <i><strike>foo'

as well as: '<p><a href="xx"> <em>Using</em></a></p>' which appears to be treated as: '<p><a href="xx"><em>Using</em></a></p>'

If strict is false, when a tag that breaks flow, (TagElement.breaksFlows) or trailing whitespace is encountered, all whitespace will be ignored until a non whitespace character is encountered. This appears to give behavior closer to the popular browsers.

Authors
Arthur van Hoff, Sunita Mani
See Also
DTD, TagElement, SimpleAttributeSet

Field Summary

Modifier and TypeField and Description
private SimpleAttributeSet
private char[]
private int
private static final char[]
cp1252Map

array for mapping numeric references in range 130-159 to displayable Unicode characters.

private int
crCount

Number of \r's encountered.

private int
crlfCount

Number of \r\n's encountered.

private int
currentBlockStartPos

The start position of the current block.

private int
protected DTD
dtd

The dtd.

private static final String
private boolean
ignoreSpace

The html spec does not specify how spaces are coalesced very well.

private Reader
private TagElement
private int
lastBlockStartPos

Start position of the last block.

private TagElement
private int
private int
lfCount

Number of \n's encountered.

private int
private int
private Element
private static final char[]
private static final char[]
private boolean
private boolean
private boolean
private boolean
private boolean
private TagStack
private static final String
private char[]
protected boolean
strict

This flag determines whether or not the Parser will be strict in enforcing SGML compatibility.

private int
private char[]
private int

Constructor Summary

AccessConstructor and Description
public
Parser(DTD
the dtd.
dtd
)

Creates parser with the specified dtd.

Method Summary

Modifier and TypeMethod and Description
pack-priv void
addString(int c)

Add a char to the string buffer.

protected void
endTag(boolean
true if the tag is no actually present in the document, but is supposed by the parser
omitted
)

Handle an end tag.

protected void
error(String
the error type
err
,
String
the 1st error message argument
arg1
,
String
the 2nd error message argument
arg2
,
String
the 3rd error message argument
arg3
)

Invokes the error handler.

protected void
error(String
the error type
err
,
String
the 1st error message argument
arg1
,
String
the 2nd error message argument
arg2
)

Invokes the error handler with the 3rd error message argument "?".

protected void
error(String
the error type
err
,
String
the 1st error message argument
arg1
)

Invokes the error handler with the 2nd and 3rd error message argument "?".

protected void
error(String
the error type
err
)

Invokes the error handler with the 1st, 2nd and 3rd error message argument "?".

pack-priv void
errorContext()

Error context.

protected void
flushAttributes()

Removes the current attributes.

protected SimpleAttributeSet

Returns:

SimpleAttributeSet containing the attributes
getAttributes
()

Returns attributes for the current tag.

pack-priv int

Returns:

the start position of the current block
getBlockStartPosition
()

Returns the start position of the current block.

pack-priv char[]
getChars(int pos)

pack-priv char[]
getChars(int pos, int endPos)

protected int

Returns:

the line number of the line currently being parsed
getCurrentLine
()

Returns the line number of the line currently being parsed.

protected int

Returns:

the current position
getCurrentPos
()

Returns the current position.

pack-priv String
getEndOfLineString()

Returns the end of line string.

pack-priv String
getString(int pos)

Get the string that's been accumulated.

protected void
handleComment(char[]
the comment being handled
text
)

Called when an HTML comment is encountered.

protected void
handleEmptyTag(TagElement
the tag being handled
tag
)

Called when an empty tag is encountered.

protected void
handleEndTag(TagElement
the tag being handled
tag
)

Called when an end tag is encountered.

protected void
handleEOFInComment()

Called when the content terminates without closing the HTML comment.

protected void
handleError(int
the number of line containing the error
ln
,
String
the error message
msg
)

An error has occurred.

protected void
handleStartTag(TagElement
the tag being handled
tag
)

Called when a start tag is encountered.

protected void
handleText(char[]
the section text
text
)

Called when PCDATA is encountered.

pack-priv void
handleText(TagElement tag)

Output text.

protected void
handleTitle(char[]
the title text
text
)

Called when an HTML title tag is encountered.

pack-priv boolean
pack-priv boolean
legalElementContext(Element elem)

Create a legal content for an element.

pack-priv void
legalTagContext(TagElement tag)

Create a legal context for a tag.

protected TagElement

Returns:

the created TagElement
makeTag
(Element
the element storing the tag definition
elem
,
boolean
the value of the flag "fictional" to be set for the tag
fictional
)

Makes a TagElement.

protected TagElement

Returns:

the created TagElement
makeTag
(Element
the element storing the tag definition
elem
)

Makes a TagElement.

private char[]

Returns:

a char array corresponding to the reference code.
mapNumericReference
(int
the code of numeric character reference.
c
)

Converts numeric character reference to char array.

protected void
markFirstTime(Element
the element represented by the tag
elem
)

Marks the first time a tag has been seen in a document

public synchronized void
parse(Reader
the reader to read the source from
in
)

Parse an HTML stream, given a DTD.

pack-priv void
parseAttributeSpecificationList(Element elem)

Parse attribute specification List.

pack-priv String
parseAttributeValue(boolean lower)

Parse attribute value.

pack-priv void
parseComment()

Parse a comment.

pack-priv void
parseContent()

Parse Content.

public String

Returns:

the string representation of the markup declaration
parseDTDMarkup
()

Parses the Document Type Declaration markup declaration.

private char[]
parseEntityReference()

Parse an entity reference.

pack-priv boolean
parseIdentifier(boolean lower)

Parse identifier.

pack-priv void
parseInvalidTag()

Parse an invalid tag.

pack-priv void
parseLiteral(boolean replace)

Parse literal content.

protected boolean

Returns:

true if this is a valid markup declaration; otherwise false
parseMarkupDeclarations
(StringBuffer
the markup declaration
strBuff
)

Parse markup declarations.

pack-priv void
pack-priv void
parseTag()

Parse a start or end tag.

private int
pack-priv void
pack-priv void
skipSpace()

Skip space.

protected void
startTag(TagElement
the tag
tag
)

Handle a start tag.

pack-priv int
strIndexOf(char target)

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

attributesback to summary
private SimpleAttributeSet attributes
bufback to summary
private char[] buf
chback to summary
private int ch
cp1252Mapback to summary
private static final char[] cp1252Map

array for mapping numeric references in range 130-159 to displayable Unicode characters.

crCountback to summary
private int crCount

Number of \r's encountered. A \r\n will not increment this.

crlfCountback to summary
private int crlfCount

Number of \r\n's encountered.

currentBlockStartPosback to summary
private int currentBlockStartPos

The start position of the current block. Block is overloaded here, it really means the current start position for the current comment, tag, text. Use getBlockStartPosition to access this.

currentPositionback to summary
private int currentPosition
dtdback to summary
protected DTD dtd

The dtd.

END_COMMENTback to summary
private static final String END_COMMENT
ignoreSpaceback to summary
private boolean ignoreSpace

The html spec does not specify how spaces are coalesced very well. If strict == false, ignoreSpace is used to try and mimic the behavior of the popular browsers.

The problematic scenarios are: '<b>blah <i> <strike> foo' which can be treated as: '<b>blah <i><strike>foo' as well as: '<p><a href="xx"> <em>Using</em></a></p>' which appears to be treated as: '<p><a href="xx"><em>Using</em></a></p>'

When a tag that breaks flow, or trailing whitespace is encountered ignoreSpace is set to true. From then on, all whitespace will be ignored. ignoreSpace will be set back to false the first time a non whitespace character is encountered. This appears to give behavior closer to the popular browsers.

inback to summary
private Reader in
lastback to summary
private TagElement last
lastBlockStartPosback to summary
private int lastBlockStartPos

Start position of the last block.

lastFormSentback to summary
private TagElement lastFormSent
lenback to summary
private int len
lfCountback to summary
private int lfCount

Number of \n's encountered. A \r\n will not increment this.

lnback to summary
private int ln
posback to summary
private int pos
recentback to summary
private Element recent
SCRIPT_END_TAGback to summary
private static final char[] SCRIPT_END_TAG
SCRIPT_END_TAG_UPPER_CASEback to summary
private static final char[] SCRIPT_END_TAG_UPPER_CASE
seenBodyback to summary
private boolean seenBody
seenHeadback to summary
private boolean seenHead
seenHtmlback to summary
private boolean seenHtml
skipTagback to summary
private boolean skipTag
spaceback to summary
private boolean space
stackback to summary
private TagStack stack
START_COMMENTback to summary
private static final String START_COMMENT
strback to summary
private char[] str
strictback to summary
protected boolean strict

This flag determines whether or not the Parser will be strict in enforcing SGML compatibility. If false, it will be lenient with certain common classes of erroneous HTML constructs. Strict or not, in either case an error will be recorded.

strposback to summary
private int strpos
textback to summary
private char[] text
textposback to summary
private int textpos

Constructor Detail

Parserback to summary
public Parser(DTD dtd)

Creates parser with the specified dtd.

Parameters
dtd:DTD

the dtd.

Method Detail

addStringback to summary
pack-priv void addString(int c)

Add a char to the string buffer.

endTagback to summary
protected void endTag(boolean omitted)

Handle an end tag. The end tag is popped from the tag stack.

Parameters
omitted:boolean

true if the tag is no actually present in the document, but is supposed by the parser

errorback to summary
protected void error(String err, String arg1, String arg2, String arg3)

Invokes the error handler.

Parameters
err:String

the error type

arg1:String

the 1st error message argument

arg2:String

the 2nd error message argument

arg3:String

the 3rd error message argument

errorback to summary
protected void error(String err, String arg1, String arg2)

Invokes the error handler with the 3rd error message argument "?".

Parameters
err:String

the error type

arg1:String

the 1st error message argument

arg2:String

the 2nd error message argument

errorback to summary
protected void error(String err, String arg1)

Invokes the error handler with the 2nd and 3rd error message argument "?".

Parameters
err:String

the error type

arg1:String

the 1st error message argument

errorback to summary
protected void error(String err)

Invokes the error handler with the 1st, 2nd and 3rd error message argument "?".

Parameters
err:String

the error type

errorContextback to summary
pack-priv void errorContext() throws ChangedCharSetException

Error context. Something went wrong, make sure we are in the document's body context

flushAttributesback to summary
protected void flushAttributes()

Removes the current attributes.

getAttributesback to summary
protected SimpleAttributeSet getAttributes()

Returns attributes for the current tag.

Returns:SimpleAttributeSet

SimpleAttributeSet containing the attributes

getBlockStartPositionback to summary
pack-priv int getBlockStartPosition()

Returns the start position of the current block. Block is overloaded here, it really means the current start position for the current comment tag, text, block.... This is provided for subclassers that wish to know the start of the current block when called with one of the handleXXX methods.

Returns:int

the start position of the current block

getCharsback to summary
pack-priv char[] getChars(int pos)
getCharsback to summary
pack-priv char[] getChars(int pos, int endPos)
getCurrentLineback to summary
protected int getCurrentLine()

Returns the line number of the line currently being parsed.

Returns:int

the line number of the line currently being parsed

getCurrentPosback to summary
protected int getCurrentPos()

Returns the current position.

Returns:int

the current position

getEndOfLineStringback to summary
pack-priv String getEndOfLineString()

Returns the end of line string. This will return the end of line string that has been encountered the most, one of \r, \n or \r\n.

getStringback to summary
pack-priv String getString(int pos)

Get the string that's been accumulated.

handleCommentback to summary
protected void handleComment(char[] text)

Called when an HTML comment is encountered.

Parameters
text:char[]

the comment being handled

handleEmptyTagback to summary
protected void handleEmptyTag(TagElement tag) throws ChangedCharSetException

Called when an empty tag is encountered.

Parameters
tag:TagElement

the tag being handled

Exceptions
ChangedCharSetException:
if the document charset was changed
handleEndTagback to summary
protected void handleEndTag(TagElement tag)

Called when an end tag is encountered.

Parameters
tag:TagElement

the tag being handled

handleEOFInCommentback to summary
protected void handleEOFInComment()

Called when the content terminates without closing the HTML comment.

handleErrorback to summary
protected void handleError(int ln, String msg)

An error has occurred.

Parameters
ln:int

the number of line containing the error

msg:String

the error message

handleStartTagback to summary
protected void handleStartTag(TagElement tag)

Called when a start tag is encountered.

Parameters
tag:TagElement

the tag being handled

handleTextback to summary
protected void handleText(char[] text)

Called when PCDATA is encountered.

Parameters
text:char[]

the section text

handleTextback to summary
pack-priv void handleText(TagElement tag)

Output text.

handleTitleback to summary
protected void handleTitle(char[] text)

Called when an HTML title tag is encountered.

Parameters
text:char[]

the title text

ignoreElementback to summary
pack-priv boolean ignoreElement(Element elem)
legalElementContextback to summary
pack-priv boolean legalElementContext(Element elem) throws ChangedCharSetException

Create a legal content for an element.

legalTagContextback to summary
pack-priv void legalTagContext(TagElement tag) throws ChangedCharSetException

Create a legal context for a tag.

makeTagback to summary
protected TagElement makeTag(Element elem, boolean fictional)

Makes a TagElement.

Parameters
elem:Element

the element storing the tag definition

fictional:boolean

the value of the flag "fictional" to be set for the tag

Returns:TagElement

the created TagElement

makeTagback to summary
protected TagElement makeTag(Element elem)

Makes a TagElement.

Parameters
elem:Element

the element storing the tag definition

Returns:TagElement

the created TagElement

mapNumericReferenceback to summary
private char[] mapNumericReference(int c)

Converts numeric character reference to char array. Normally the code in a reference should be always converted to the Unicode character with the same code, but due to wide usage of Cp1252 charset most browsers map numeric references in the range 130-159 (which are control chars in Unicode set) to displayable characters with other codes.

Parameters
c:int

the code of numeric character reference.

Returns:char[]

a char array corresponding to the reference code.

markFirstTimeback to summary
protected void markFirstTime(Element elem)

Marks the first time a tag has been seen in a document

Parameters
elem:Element

the element represented by the tag

parseback to summary
public synchronized void parse(Reader in) throws IOException

Parse an HTML stream, given a DTD.

Parameters
in:Reader

the reader to read the source from

Exceptions
IOException:
if an I/O error occurs
parseAttributeSpecificationListback to summary
pack-priv void parseAttributeSpecificationList(Element elem) throws IOException

Parse attribute specification List. [31] 327:17

parseAttributeValueback to summary
pack-priv String parseAttributeValue(boolean lower) throws IOException

Parse attribute value. [33] 331:1

Annotations
@SuppressWarnings:fallthrough
parseCommentback to summary
pack-priv void parseComment() throws IOException

Parse a comment. [92] 391:7

parseContentback to summary
pack-priv void parseContent() throws IOException

Parse Content. [24] 320:1

parseDTDMarkupback to summary
public String parseDTDMarkup() throws IOException

Parses the Document Type Declaration markup declaration. Currently ignores it.

Returns:String

the string representation of the markup declaration

Exceptions
IOException:
if an I/O error occurs
parseEntityReferenceback to summary
private char[] parseEntityReference() throws IOException

Parse an entity reference. [59] 350:17

parseIdentifierback to summary
pack-priv boolean parseIdentifier(boolean lower) throws IOException

Parse identifier. Uppercase characters are folded to lowercase when lower is true. Returns false if no identifier is found. [55] 346:17

parseInvalidTagback to summary
pack-priv void parseInvalidTag() throws IOException

Parse an invalid tag.

parseLiteralback to summary
pack-priv void parseLiteral(boolean replace) throws IOException

Parse literal content. [46] 343:1 and [47] 344:1

parseMarkupDeclarationsback to summary
protected boolean parseMarkupDeclarations(StringBuffer strBuff) throws IOException

Parse markup declarations. Currently only handles the Document Type Declaration markup. Returns true if it is a markup declaration false otherwise.

Parameters
strBuff:StringBuffer

the markup declaration

Returns:boolean

true if this is a valid markup declaration; otherwise false

Exceptions
IOException:
if an I/O error occurs
parseScriptback to summary
pack-priv void parseScript() throws IOException
parseTagback to summary
pack-priv void parseTag() throws IOException

Parse a start or end tag.

Annotations
@SuppressWarnings:fallthrough
readChback to summary
private int readCh() throws IOException
resetStrBufferback to summary
pack-priv void resetStrBuffer()
skipSpaceback to summary
pack-priv void skipSpace() throws IOException

Skip space. [5] 297:5

startTagback to summary
protected void startTag(TagElement tag) throws ChangedCharSetException

Handle a start tag. The new tag is pushed onto the tag stack. The attribute list is checked for required attributes.

Parameters
tag:TagElement

the tag

Exceptions
ChangedCharSetException:
if the document charset was changed
strIndexOfback to summary
pack-priv int strIndexOf(char target)