code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
<body bgcolor='white'> | zzh-simple-hr | Znekohtml/data/test064.html | HTML | art | 22 |
&#foo; | zzh-simple-hr | Znekohtml/data/test029.html | HTML | art | 6 |
<HTML><HEAD>
<script><!--/** that's a comment containing a single quote */var head="display:''"//--></script></HEAD><BODY></BODY></HTML> | zzh-simple-hr | Znekohtml/data/test-quote-in-script-comment.html | HTML | art | 139 |
<table><tr><td><table><td> | zzh-simple-hr | Znekohtml/data/test-table-in-td.html | HTML | art | 26 |
<li>Item1<ul></li><li>Item2 | zzh-simple-hr | Znekohtml/data/test034.html | HTML | art | 27 |
&foo; | zzh-simple-hr | Znekohtml/data/test022.html | HTML | art | 5 |
<html><head><title>This doesn't work</title></head><body>Body</body></html> | zzh-simple-hr | Znekohtml/data/test-title-bug1922810.html | HTML | art | 75 |
<P><?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><IMG></P> | zzh-simple-hr | Znekohtml/data/test075.html | HTML | art | 88 |
<noscript><div>hello <span>world</span></noscript> | zzh-simple-hr | Znekohtml/data/noxxx/test-noscript-parseit.html | HTML | art | 50 |
<noscript><div>hello <span>world</span></noscript> | zzh-simple-hr | Znekohtml/data/noxxx/test-noscript.html | HTML | art | 50 |
<html>
<noframes>
<p>hello
</noframes>
<body>
<p>hello again
</body>
</html> | zzh-simple-hr | Znekohtml/data/noxxx/test-noframes.html | HTML | art | 76 |
<html><head></head><h:body xmlns:h='urn:not-a-html-ns'> | zzh-simple-hr | Znekohtml/data/test-non-html-ns.html | HTML | art | 55 |
</html><h1>foo</h1> | zzh-simple-hr | Znekohtml/data/test098.html | HTML | art | 19 |
<html><head><title>first</title></head>
<frameset cols='100%'>
<frame src='foo' id='frame1'/>
</frameset></html> | zzh-simple-hr | Znekohtml/data/frameset/test-frameset.html | HTML | art | 114 |
<a href=/path/>blah</a> | zzh-simple-hr | Znekohtml/data/test018.html | HTML | art | 23 |
<html><head>
<script src='/foo.js'><!-- this shouldn't be a problem --></script>
<script src='/foo.js'><!-- this shouldn't be a problem either --> </script>
</head><body></body></html> | zzh-simple-hr | Znekohtml/data/test-quote-in-comment.html | HTML | art | 184 |
<HTML>Hello<p>World | zzh-simple-hr | Znekohtml/data/test088.html | HTML | art | 19 |
<textarea>arf "woof</textarea> | zzh-simple-hr | Znekohtml/data/test-quote-in-textarea.html | HTML | art | 30 |
<p>P1<![CDATA[<h1>Header</h1>]]>
<p>P2 | zzh-simple-hr | Znekohtml/data/test080.html | HTML | art | 39 |
<table><tr><th><div></th></tr>
<tr><td></td></tr>
</table> | zzh-simple-hr | Znekohtml/data/test-th-closes-div.html | HTML | art | 58 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
/**
* Pre-defined HTML entities.
*
* @author Andy Clark
*
* @version $Id: HTMLEntities.java,v 1.5 2005/02/14 03:56:54 andyc Exp $
*/
public class HTMLEntities {
//
// Constants
//
/** Entities. */
protected static final Properties ENTITIES = new Properties();
/** Reverse mapping from characters to names. */
protected static final IntProperties SEITITNE = new IntProperties();
//
// Static initialization
//
static {
// load entities
load0("res/HTMLlat1.properties");
load0("res/HTMLspecial.properties");
load0("res/HTMLsymbol.properties");
load0("res/XMLbuiltin.properties");
// store reverse mappings
Enumeration keys = ENTITIES.propertyNames();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
String value = ENTITIES.getProperty(key);
if (value.length() == 1) {
int ivalue = value.charAt(0);
SEITITNE.put(ivalue, key);
}
}
}
//
// Public static methods
//
/**
* Returns the character associated to the given entity name, or
* -1 if the name is not known.
*/
public static int get(String name) {
String value = (String)ENTITIES.get(name);
return value != null ? value.charAt(0) : -1;
} // get(String):char
/**
* Returns the name associated to the given character or null if
* the character is not known.
*/
public static String get(int c) {
return SEITITNE.get(c);
} // get(int):String
//
// Private static methods
//
/** Loads the entity values in the specified resource. */
private static void load0(String filename) {
try {
ENTITIES.load(HTMLEntities.class.getResourceAsStream(filename));
}
catch (IOException e) {
System.err.println("error: unable to load resource \""+filename+"\"");
}
} // load0(String)
//
// Classes
//
static class IntProperties {
private Entry[] entries = new Entry[101];
public void put(int key, String value) {
int hash = key % entries.length;
Entry entry = new Entry(key, value, entries[hash]);
entries[hash] = entry;
}
public String get(int key) {
int hash = key % entries.length;
Entry entry = entries[hash];
while (entry != null) {
if (entry.key == key) {
return entry.value;
}
entry = entry.next;
}
return null;
}
static class Entry {
public int key;
public String value;
public Entry next;
public Entry(int key, String value, Entry next) {
this.key = key;
this.value = value;
this.next = next;
}
}
}
} // class HTMLEntities
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/HTMLEntities.java | Java | art | 3,789 |
/*
* Copyright 2004-2008 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html;
import org.apache.xerces.xni.parser.XMLComponent;
/**
* This interface extends the XNI <code>XMLComponent</code> interface
* to add methods that allow the preferred default values for features
* and properties to be queried.
*
* @author Andy Clark
*
* @version $Id: HTMLComponent.java,v 1.4 2005/02/14 03:56:54 andyc Exp $
*/
public interface HTMLComponent
extends XMLComponent {
//
// HTMLComponent methods
//
/**
* Returns the default state for a feature, or null if this
* component does not want to report a default value for this
* feature.
*/
public Boolean getFeatureDefault(String featureId);
/**
* Returns the default state for a property, or null if this
* component does not want to report a default value for this
* property.
*/
public Object getPropertyDefault(String propertyId);
} // interface HTMLComponent
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/HTMLComponent.java | Java | art | 1,559 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html;
/**
* Collection of HTML element information.
*
* @author Andy Clark
* @author Ahmed Ashour
* @author Marc Guillemot
*
* @version $Id: HTMLElements.java,v 1.12 2005/02/14 07:16:59 andyc Exp $
*/
public class HTMLElements {
//
// Constants
//
// element codes
// NOTE: The element codes *must* start with 0 and increment in
// sequence. The parent and closes references depends on
// this assumption. -Ac
public static final short A = 0;
public static final short ABBR = A+1;
public static final short ACRONYM = ABBR+1;
public static final short ADDRESS = ACRONYM+1;
public static final short APPLET = ADDRESS+1;
public static final short AREA = APPLET+1;
public static final short B = AREA+1;
public static final short BASE = B+1;
public static final short BASEFONT = BASE+1;
public static final short BDO = BASEFONT+1;
public static final short BGSOUND = BDO+1;
public static final short BIG = BGSOUND+1;
public static final short BLINK = BIG+1;
public static final short BLOCKQUOTE = BLINK+1;
public static final short BODY = BLOCKQUOTE+1;
public static final short BR = BODY+1;
public static final short BUTTON = BR+1;
public static final short CAPTION = BUTTON+1;
public static final short CENTER = CAPTION+1;
public static final short CITE = CENTER+1;
public static final short CODE = CITE+1;
public static final short COL = CODE+1;
public static final short COLGROUP = COL+1;
public static final short COMMENT = COLGROUP+1;
public static final short DEL = COMMENT+1;
public static final short DFN = DEL+1;
public static final short DIR = DFN+1;
public static final short DIV = DIR+1;
public static final short DD = DIV+1;
public static final short DL = DD+1;
public static final short DT = DL+1;
public static final short EM = DT+1;
public static final short EMBED = EM+1;
public static final short FIELDSET = EMBED+1;
public static final short FONT = FIELDSET+1;
public static final short FORM = FONT+1;
public static final short FRAME = FORM+1;
public static final short FRAMESET = FRAME+1;
public static final short H1 = FRAMESET+1;
public static final short H2 = H1+1;
public static final short H3 = H2+1;
public static final short H4 = H3+1;
public static final short H5 = H4+1;
public static final short H6 = H5+1;
public static final short HEAD = H6+1;
public static final short HR = HEAD+1;
public static final short HTML = HR+1;
public static final short I = HTML+1;
public static final short IFRAME = I+1;
public static final short ILAYER = IFRAME+1;
public static final short IMG = ILAYER+1;
public static final short INPUT = IMG+1;
public static final short INS = INPUT+1;
public static final short ISINDEX = INS+1;
public static final short KBD = ISINDEX+1;
public static final short KEYGEN = KBD+1;
public static final short LABEL = KEYGEN+1;
public static final short LAYER = LABEL+1;
public static final short LEGEND = LAYER+1;
public static final short LI = LEGEND+1;
public static final short LINK = LI+1;
public static final short LISTING = LINK+1;
public static final short MAP = LISTING+1;
public static final short MARQUEE = MAP+1;
public static final short MENU = MARQUEE+1;
public static final short META = MENU+1;
public static final short MULTICOL = META+1;
public static final short NEXTID = MULTICOL+1;
public static final short NOBR = NEXTID+1;
public static final short NOEMBED = NOBR+1;
public static final short NOFRAMES = NOEMBED+1;
public static final short NOLAYER = NOFRAMES+1;
public static final short NOSCRIPT = NOLAYER+1;
public static final short OBJECT = NOSCRIPT+1;
public static final short OL = OBJECT+1;
public static final short OPTION = OL+1;
public static final short OPTGROUP = OPTION+1;
public static final short P = OPTGROUP+1;
public static final short PARAM = P+1;
public static final short PLAINTEXT = PARAM+1;
public static final short PRE = PLAINTEXT+1;
public static final short Q = PRE+1;
public static final short RB = Q+1;
public static final short RBC = RB+1;
public static final short RP = RBC+1;
public static final short RT = RP+1;
public static final short RTC = RT+1;
public static final short RUBY = RTC+1;
public static final short S = RUBY+1;
public static final short SAMP = S+1;
public static final short SCRIPT = SAMP+1;
public static final short SELECT = SCRIPT+1;
public static final short SMALL = SELECT+1;
public static final short SOUND = SMALL+1;
public static final short SPACER = SOUND+1;
public static final short SPAN = SPACER+1;
public static final short STRIKE = SPAN+1;
public static final short STRONG = STRIKE+1;
public static final short STYLE = STRONG+1;
public static final short SUB = STYLE+1;
public static final short SUP = SUB+1;
public static final short TABLE = SUP+1;
public static final short TBODY = TABLE+1;
public static final short TD = TBODY+1;
public static final short TEXTAREA = TD+1;
public static final short TFOOT = TEXTAREA+1;
public static final short TH = TFOOT+1;
public static final short THEAD = TH+1;
public static final short TITLE = THEAD+1;
public static final short TR = TITLE+1;
public static final short TT = TR+1;
public static final short U = TT+1;
public static final short UL = U+1;
public static final short VAR = UL+1;
public static final short WBR = VAR+1;
public static final short XML = WBR+1;
public static final short XMP = XML+1;
public static final short UNKNOWN = XMP+1;
// information
/** Element information organized by first letter. */
protected static final Element[][] ELEMENTS_ARRAY = new Element[26][];
/** Element information as a contiguous list. */
protected static final ElementList ELEMENTS = new ElementList();
/** No such element. */
public static final Element NO_SUCH_ELEMENT = new Element(UNKNOWN, "", Element.CONTAINER, new short[]{BODY,HEAD}/*HTML*/, null);
//
// Static initializer
//
/**
* Initializes the element information.
* <p>
* <strong>Note:</strong>
* The <code>getElement</code> method requires that the HTML elements
* are added to the list in alphabetical order. If new elements are
* added, then they <em>must</em> be inserted in alphabetical order.
*/
static {
// <!ENTITY % heading "H1|H2|H3|H4|H5|H6">
// <!ENTITY % fontstyle "TT | I | B | BIG | SMALL">
// <!ENTITY % phrase "EM | STRONG | DFN | CODE | SAMP | KBD | VAR | CITE | ABBR | ACRONYM" >
// <!ENTITY % special "A | IMG | OBJECT | BR | SCRIPT | MAP | Q | SUB | SUP | SPAN | BDO">
// <!ENTITY % formctrl "INPUT | SELECT | TEXTAREA | LABEL | BUTTON">
// <!ENTITY % inline "#PCDATA | %fontstyle; | %phrase; | %special; | %formctrl;">
// <!ENTITY % block "P | %heading; | %list; | %preformatted; | DL | DIV | NOSCRIPT | BLOCKQUOTE | FORM | HR | TABLE | FIELDSET | ADDRESS">
// <!ENTITY % flow "%block; | %inline;">
// initialize array of element information
ELEMENTS_ARRAY['A'-'A'] = new Element[] {
// A - - (%inline;)* -(A)
new Element(A, "A", Element.INLINE, BODY, new short[] {A}),
// ABBR - - (%inline;)*
new Element(ABBR, "ABBR", Element.INLINE, BODY, null),
// ACRONYM - - (%inline;)*
new Element(ACRONYM, "ACRONYM", Element.INLINE, BODY, null),
// ADDRESS - - (%inline;)*
new Element(ADDRESS, "ADDRESS", Element.BLOCK, BODY, null),
// APPLET
new Element(APPLET, "APPLET", 0, BODY, null),
// AREA - O EMPTY
new Element(AREA, "AREA", Element.EMPTY, MAP, null),
};
ELEMENTS_ARRAY['B'-'A'] = new Element[] {
// B - - (%inline;)*
new Element(B, "B", Element.INLINE, BODY, null),
// BASE - O EMPTY
new Element(BASE, "BASE", Element.EMPTY, HEAD, null),
// BASEFONT
new Element(BASEFONT, "BASEFONT", 0, HEAD, null),
// BDO - - (%inline;)*
new Element(BDO, "BDO", Element.INLINE, BODY, null),
// BGSOUND
new Element(BGSOUND, "BGSOUND", Element.EMPTY, HEAD, null),
// BIG - - (%inline;)*
new Element(BIG, "BIG", Element.INLINE, BODY, null),
// BLINK
new Element(BLINK, "BLINK", Element.INLINE, BODY, null),
// BLOCKQUOTE - - (%block;|SCRIPT)+
new Element(BLOCKQUOTE, "BLOCKQUOTE", Element.BLOCK, BODY, new short[]{P}),
// BODY O O (%block;|SCRIPT)+ +(INS|DEL)
new Element(BODY, "BODY", Element.CONTAINER, HTML, new short[]{HEAD}),
// BR - O EMPTY
new Element(BR, "BR", Element.EMPTY, BODY, null),
// BUTTON - - (%flow;)* -(A|%formctrl;|FORM|FIELDSET)
new Element(BUTTON, "BUTTON", 0, BODY, null),
};
ELEMENTS_ARRAY['C'-'A'] = new Element[] {
// CAPTION - - (%inline;)*
new Element(CAPTION, "CAPTION", Element.INLINE, TABLE, null),
// CENTER,
new Element(CENTER, "CENTER", 0, BODY, null),
// CITE - - (%inline;)*
new Element(CITE, "CITE", Element.INLINE, BODY, null),
// CODE - - (%inline;)*
new Element(CODE, "CODE", Element.INLINE, BODY, null),
// COL - O EMPTY
new Element(COL, "COL", Element.EMPTY, TABLE, null),
// COLGROUP - O (COL)*
new Element(COLGROUP, "COLGROUP", 0, TABLE, new short[]{COL,COLGROUP}),
// COMMENT
new Element(COMMENT, "COMMENT", Element.SPECIAL, HTML, null),
};
ELEMENTS_ARRAY['D'-'A'] = new Element[] {
// DEL - - (%flow;)*
new Element(DEL, "DEL", 0, BODY, null),
// DFN - - (%inline;)*
new Element(DFN, "DFN", Element.INLINE, BODY, null),
// DIR
new Element(DIR, "DIR", 0, BODY, null),
// DIV - - (%flow;)*
new Element(DIV, "DIV", Element.BLOCK, BODY, new short[]{P}),
// DD - O (%flow;)*
new Element(DD, "DD", 0, DL, new short[]{DT,DD}),
// DL - - (DT|DD)+
new Element(DL, "DL", Element.BLOCK, BODY, null),
// DT - O (%inline;)*
new Element(DT, "DT", 0, DL, new short[]{DT,DD}),
};
ELEMENTS_ARRAY['E'-'A'] = new Element[] {
// EM - - (%inline;)*
new Element(EM, "EM", Element.INLINE, BODY, null),
// EMBED
new Element(EMBED, "EMBED", 0, BODY, null),
};
ELEMENTS_ARRAY['F'-'A'] = new Element[] {
// FIELDSET - - (#PCDATA,LEGEND,(%flow;)*)
new Element(FIELDSET, "FIELDSET", 0, BODY, null),
// FONT
new Element(FONT, "FONT", Element.CONTAINER, BODY, null),
// FORM - - (%block;|SCRIPT)+ -(FORM)
new Element(FORM, "FORM", Element.CONTAINER, new short[]{BODY,TD,DIV}, new short[]{BUTTON,P}),
// FRAME - O EMPTY
new Element(FRAME, "FRAME", Element.EMPTY, FRAMESET, null),
// FRAMESET - - ((FRAMESET|FRAME)+ & NOFRAMES?)
new Element(FRAMESET, "FRAMESET", 0, HTML, null),
};
ELEMENTS_ARRAY['H'-'A'] = new Element[] {
// (H1|H2|H3|H4|H5|H6) - - (%inline;)*
new Element(H1, "H1", Element.BLOCK, new short[]{BODY,A}, new short[]{H1,H2,H3,H4,H5,H6,P}),
new Element(H2, "H2", Element.BLOCK, new short[]{BODY,A}, new short[]{H1,H2,H3,H4,H5,H6,P}),
new Element(H3, "H3", Element.BLOCK, new short[]{BODY,A}, new short[]{H1,H2,H3,H4,H5,H6,P}),
new Element(H4, "H4", Element.BLOCK, new short[]{BODY,A}, new short[]{H1,H2,H3,H4,H5,H6,P}),
new Element(H5, "H5", Element.BLOCK, new short[]{BODY,A}, new short[]{H1,H2,H3,H4,H5,H6,P}),
new Element(H6, "H6", Element.BLOCK, new short[]{BODY,A}, new short[]{H1,H2,H3,H4,H5,H6,P}),
// HEAD O O (%head.content;) +(%head.misc;)
new Element(HEAD, "HEAD", 0, HTML, null),
// HR - O EMPTY
new Element(HR, "HR", Element.EMPTY, BODY, new short[]{P}),
// HTML O O (%html.content;)
new Element(HTML, "HTML", 0, null, null),
};
ELEMENTS_ARRAY['I'-'A'] = new Element[] {
// I - - (%inline;)*
new Element(I, "I", Element.INLINE, BODY, null),
// IFRAME
new Element(IFRAME, "IFRAME", Element.BLOCK, BODY, null),
// ILAYER
new Element(ILAYER, "ILAYER", Element.BLOCK, BODY, null),
// IMG - O EMPTY
new Element(IMG, "IMG", Element.EMPTY, BODY, null),
// INPUT - O EMPTY
new Element(INPUT, "INPUT", Element.EMPTY, BODY, null),
// INS - - (%flow;)*
new Element(INS, "INS", 0, BODY, null),
// ISINDEX
new Element(ISINDEX, "ISINDEX", 0, HEAD, null),
};
ELEMENTS_ARRAY['K'-'A'] = new Element[] {
// KBD - - (%inline;)*
new Element(KBD, "KBD", Element.INLINE, BODY, null),
// KEYGEN
new Element(KEYGEN, "KEYGEN", 0, BODY, null),
};
ELEMENTS_ARRAY['L'-'A'] = new Element[] {
// LABEL - - (%inline;)* -(LABEL)
new Element(LABEL, "LABEL", 0, BODY, null),
// LAYER
new Element(LAYER, "LAYER", Element.BLOCK, BODY, null),
// LEGEND - - (%inline;)*
new Element(LEGEND, "LEGEND", Element.INLINE, FIELDSET, null),
// LI - O (%flow;)*
new Element(LI, "LI", 0, new short[]{BODY,UL,OL}, new short[]{LI}),
// LINK - O EMPTY
new Element(LINK, "LINK", Element.EMPTY, HEAD, null),
// LISTING
new Element(LISTING, "LISTING", 0, BODY, null),
};
ELEMENTS_ARRAY['M'-'A'] = new Element[] {
// MAP - - ((%block;) | AREA)+
new Element(MAP, "MAP", Element.INLINE, BODY, null),
// MARQUEE
new Element(MARQUEE, "MARQUEE", 0, BODY, null),
// MENU
new Element(MENU, "MENU", 0, BODY, null),
// META - O EMPTY
new Element(META, "META", Element.EMPTY, HEAD, new short[]{STYLE,TITLE}),
// MULTICOL
new Element(MULTICOL, "MULTICOL", 0, BODY, null),
};
ELEMENTS_ARRAY['N'-'A'] = new Element[] {
// NEXTID
new Element(NEXTID, "NEXTID", Element.EMPTY, BODY, null),
// NOBR
new Element(NOBR, "NOBR", Element.INLINE, BODY, null),
// NOEMBED
new Element(NOEMBED, "NOEMBED", 0, BODY, null),
// NOFRAMES - - (BODY) -(NOFRAMES)
new Element(NOFRAMES, "NOFRAMES", 0, null, null),
// NOLAYER
new Element(NOLAYER, "NOLAYER", 0, BODY, null),
// NOSCRIPT - - (%block;)+
new Element(NOSCRIPT, "NOSCRIPT", 0, new short[]{BODY}, null),
};
ELEMENTS_ARRAY['O'-'A'] = new Element[] {
// OBJECT - - (PARAM | %flow;)*
new Element(OBJECT, "OBJECT", 0, BODY, null),
// OL - - (LI)+
new Element(OL, "OL", Element.BLOCK, BODY, null),
// OPTGROUP - - (OPTION)+
new Element(OPTGROUP, "OPTGROUP", 0, SELECT, new short[]{OPTION}),
// OPTION - O (#PCDATA)
new Element(OPTION, "OPTION", 0, SELECT, new short[]{OPTION}),
};
ELEMENTS_ARRAY['P'-'A'] = new Element[] {
// P - O (%inline;)*
new Element(P, "P", Element.CONTAINER, BODY, new short[]{P}),
// PARAM - O EMPTY
new Element(PARAM, "PARAM", Element.EMPTY, new short[]{OBJECT,APPLET}, null),
// PLAINTEXT
new Element(PLAINTEXT, "PLAINTEXT", Element.SPECIAL, BODY, null),
// PRE - - (%inline;)* -(%pre.exclusion;)
new Element(PRE, "PRE", 0, BODY, null),
};
ELEMENTS_ARRAY['Q'-'A'] = new Element[] {
// Q - - (%inline;)*
new Element(Q, "Q", Element.INLINE, BODY, null),
};
ELEMENTS_ARRAY['R'-'A'] = new Element[] {
// RB
new Element(RB, "RB", Element.INLINE, RUBY, new short[]{RB}),
// RBC
new Element(RBC, "RBC", 0, RUBY, null),
// RP
new Element(RP, "RP", Element.INLINE, RUBY, new short[]{RB}),
// RT
new Element(RT, "RT", Element.INLINE, RUBY, new short[]{RB,RP}),
// RTC
new Element(RTC, "RTC", 0, RUBY, new short[]{RBC}),
// RUBY
new Element(RUBY, "RUBY", 0, BODY, new short[]{RUBY}),
};
ELEMENTS_ARRAY['S'-'A'] = new Element[] {
// S
new Element(S, "S", 0, BODY, null),
// SAMP - - (%inline;)*
new Element(SAMP, "SAMP", Element.INLINE, BODY, null),
// SCRIPT - - %Script;
new Element(SCRIPT, "SCRIPT", Element.SPECIAL, new short[]{HEAD,BODY}, null),
// SELECT - - (OPTGROUP|OPTION)+
new Element(SELECT, "SELECT", Element.CONTAINER, BODY, new short[]{SELECT}),
// SMALL - - (%inline;)*
new Element(SMALL, "SMALL", Element.INLINE, BODY, null),
// SOUND
new Element(SOUND, "SOUND", Element.EMPTY, HEAD, null),
// SPACER
new Element(SPACER, "SPACER", Element.EMPTY, BODY, null),
// SPAN - - (%inline;)*
new Element(SPAN, "SPAN", Element.CONTAINER, BODY, null),
// STRIKE
new Element(STRIKE, "STRIKE", Element.INLINE, BODY, null),
// STRONG - - (%inline;)*
new Element(STRONG, "STRONG", Element.INLINE, BODY, null),
// STYLE - - %StyleSheet;
new Element(STYLE, "STYLE", Element.SPECIAL, new short[]{HEAD,BODY}, new short[]{STYLE,TITLE,META}),
// SUB - - (%inline;)*
new Element(SUB, "SUB", Element.INLINE, BODY, null),
// SUP - - (%inline;)*
new Element(SUP, "SUP", Element.INLINE, BODY, null),
};
ELEMENTS_ARRAY['T'-'A'] = new Element[] {
// TABLE - - (CAPTION?, (COL*|COLGROUP*), THEAD?, TFOOT?, TBODY+)
new Element(TABLE, "TABLE", Element.BLOCK|Element.CONTAINER, BODY, null),
// TBODY O O (TR)+
new Element(TBODY, "TBODY", 0, TABLE, new short[]{THEAD,TBODY,TFOOT,TD,TH,TR,COLGROUP}),
// TD - O (%flow;)*
new Element(TD, "TD", Element.CONTAINER, TR, TABLE, new short[]{TD,TH}),
// TEXTAREA - - (#PCDATA)
new Element(TEXTAREA, "TEXTAREA", Element.SPECIAL, BODY, null),
// TFOOT - O (TR)+
new Element(TFOOT, "TFOOT", 0, TABLE, new short[]{THEAD,TBODY,TFOOT,TD,TH,TR}),
// TH - O (%flow;)*
new Element(TH, "TH", Element.CONTAINER, TR, TABLE, new short[]{TD,TH}),
// THEAD - O (TR)+
new Element(THEAD, "THEAD", 0, TABLE, new short[]{THEAD,TBODY,TFOOT,TD,TH,TR,COLGROUP}),
// TITLE - - (#PCDATA) -(%head.misc;)
new Element(TITLE, "TITLE", Element.SPECIAL, new short[]{HEAD,BODY}, null),
// TR - O (TH|TD)+
new Element(TR, "TR", Element.BLOCK, new short[]{TBODY, THEAD, TFOOT}, TABLE, new short[]{TD,TH,TR,COLGROUP}),
// TT - - (%inline;)*
new Element(TT, "TT", Element.INLINE, BODY, null),
};
ELEMENTS_ARRAY['U'-'A'] = new Element[] {
// U,
new Element(U, "U", Element.INLINE, BODY, null),
// UL - - (LI)+
new Element(UL, "UL", Element.BLOCK, BODY, null),
};
ELEMENTS_ARRAY['V'-'A'] = new Element[] {
// VAR - - (%inline;)*
new Element(VAR, "VAR", Element.INLINE, BODY, null),
};
ELEMENTS_ARRAY['W'-'A'] = new Element[] {
// WBR
new Element(WBR, "WBR", Element.EMPTY, BODY, null),
};
ELEMENTS_ARRAY['X'-'A'] = new Element[] {
// XML
new Element(XML, "XML", 0, BODY, null),
// XMP
new Element(XMP, "XMP", Element.SPECIAL, BODY, null),
};
// keep contiguous list of elements for lookups by code
for (int i = 0; i < ELEMENTS_ARRAY.length; i++) {
Element[] elements = ELEMENTS_ARRAY[i];
if (elements != null) {
for (int j = 0; j < elements.length; j++) {
Element element = elements[j];
ELEMENTS.addElement(element);
}
}
}
ELEMENTS.addElement(NO_SUCH_ELEMENT);
// initialize cross references to parent elements
for (int i = 0; i < ELEMENTS.size; i++) {
Element element = ELEMENTS.data[i];
if (element.parentCodes != null) {
element.parent = new Element[element.parentCodes.length];
for (int j = 0; j < element.parentCodes.length; j++) {
element.parent[j] = ELEMENTS.data[element.parentCodes[j]];
}
element.parentCodes = null;
}
}
} // <clinit>()
//
// Public static methods
//
/**
* Returns the element information for the specified element code.
*
* @param code The element code.
*/
public static final Element getElement(short code) {
return ELEMENTS.data[code];
} // getElement(short):Element
/**
* Returns the element information for the specified element name.
*
* @param ename The element name.
*/
public static final Element getElement(String ename) {
return getElement(ename, NO_SUCH_ELEMENT);
} // getElement(String):Element
/**
* Returns the element information for the specified element name.
*
* @param ename The element name.
* @param element The default element to return if not found.
*/
public static final Element getElement(String ename, Element element) {
if (ename.length() > 0) {
int c = ename.charAt(0);
if (c >= 'a' && c <= 'z') {
c = 'A' + c - 'a';
}
if (c >= 'A' && c <= 'Z') {
Element[] elements = ELEMENTS_ARRAY[c - 'A'];
if (elements != null) {
for (int i = 0; i < elements.length; i++) {
Element elem = elements[i];
if (elem.name.equalsIgnoreCase(ename)) {
return elem;
}
}
}
}
}
return element;
} // getElement(String):Element
//
// Classes
//
/**
* Element information.
*
* @author Andy Clark
*/
public static class Element {
//
// Constants
//
/** Inline element. */
public static final int INLINE = 0x01;
/** Block element. */
public static final int BLOCK = 0x02;
/** Empty element. */
public static final int EMPTY = 0x04;
/** Container element. */
public static final int CONTAINER = 0x08;
/** Special element. */
public static final int SPECIAL = 0x10;
//
// Data
//
/** The element code. */
public short code;
/** The element name. */
public String name;
/** Informational flags. */
public int flags;
/** Parent elements. */
public short[] parentCodes;
/** Parent elements. */
public Element[] parent;
/** The bounding element code. */
public short bounds;
/** List of elements this element can close. */
public short[] closes;
//
// Constructors
//
/**
* Constructs an element object.
*
* @param code The element code.
* @param name The element name.
* @param flags Informational flags
* @param parent Natural closing parent name.
* @param closes List of elements this element can close.
*/
public Element(short code, String name, int flags,
short parent, short[] closes) {
this(code, name, flags, new short[]{parent}, (short)-1, closes);
} // <init>(short,String,int,short,short[]);
/**
* Constructs an element object.
*
* @param code The element code.
* @param name The element name.
* @param flags Informational flags
* @param parent Natural closing parent name.
* @param closes List of elements this element can close.
*/
public Element(short code, String name, int flags,
short parent, short bounds, short[] closes) {
this(code, name, flags, new short[]{parent}, bounds, closes);
} // <init>(short,String,int,short,short,short[])
/**
* Constructs an element object.
*
* @param code The element code.
* @param name The element name.
* @param flags Informational flags
* @param parents Natural closing parent names.
* @param closes List of elements this element can close.
*/
public Element(short code, String name, int flags,
short[] parents, short[] closes) {
this(code, name, flags, parents, (short)-1, closes);
} // <init>(short,String,int,short[],short[])
/**
* Constructs an element object.
*
* @param code The element code.
* @param name The element name.
* @param flags Informational flags
* @param parents Natural closing parent names.
* @param closes List of elements this element can close.
*/
public Element(short code, String name, int flags,
short[] parents, short bounds, short[] closes) {
this.code = code;
this.name = name;
this.flags = flags;
this.parentCodes = parents;
this.parent = null;
this.bounds = bounds;
this.closes = closes;
} // <init>(short,String,int,short[],short,short[])
//
// Public methods
//
/** Returns true if this element is an inline element. */
public final boolean isInline() {
return (flags & INLINE) != 0;
} // isInline():boolean
/** Returns true if this element is a block element. */
public final boolean isBlock() {
return (flags & BLOCK) != 0;
} // isBlock():boolean
/** Returns true if this element is an empty element. */
public final boolean isEmpty() {
return (flags & EMPTY) != 0;
} // isEmpty():boolean
/** Returns true if this element is a container element. */
public final boolean isContainer() {
return (flags & CONTAINER) != 0;
} // isContainer():boolean
/**
* Returns true if this element is special -- if its content
* should be parsed ignoring markup.
*/
public final boolean isSpecial() {
return (flags & SPECIAL) != 0;
} // isSpecial():boolean
/**
* Returns true if this element can close the specified Element.
*
* @param tag The element.
*/
public boolean closes(short tag) {
if (closes != null) {
for (int i = 0; i < closes.length; i++) {
if (closes[i] == tag) {
return true;
}
}
}
return false;
} // closes(short):boolean
//
// Object methods
//
/** Returns a hash code for this object. */
public int hashCode() {
return name.hashCode();
} // hashCode():int
/** Returns true if the objects are equal. */
public boolean equals(Object o) {
return name.equals(o);
} // equals(Object):boolean
/**
* Provides a simple representation to make debugging easier
*/
public String toString() {
return super.toString() + "(name=" + name + ")";
}
/**
* Indicates if the provided element is an accepted parent of current element
* @param element the element to test for "paternity"
* @return <code>true</code> if <code>element</code> belongs to the {@link #parent}
*/
public boolean isParent(final Element element) {
if (parent == null)
return false;
else {
for (int i=0; i<parent.length; ++i) {
if (element.code == parent[i].code)
return true;
}
}
return false;
}
} // class Element
/** Unsynchronized list of elements. */
public static class ElementList {
//
// Data
//
/** The size of the list. */
public int size;
/** The data in the list. */
public Element[] data = new Element[120];
//
// Public methods
//
/** Adds an element to list, resizing if necessary. */
public void addElement(Element element) {
if (size == data.length) {
Element[] newarray = new Element[size + 20];
System.arraycopy(data, 0, newarray, 0, size);
data = newarray;
}
data[size++] = element;
} // addElement(Element)
} // class Element
} // class HTMLElements
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/HTMLElements.java | Java | art | 30,843 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html;
/**
* This interface is used to pass augmentated information to the
* application through the XNI pipeline.
*
* @author Andy Clark
*
* @version $Id: HTMLEventInfo.java,v 1.4 2005/02/14 03:56:54 andyc Exp $
*/
public interface HTMLEventInfo {
//
// HTMLEventInfo methods
//
// location information
/** Returns the line number of the beginning of this event.*/
public int getBeginLineNumber();
/** Returns the column number of the beginning of this event.*/
public int getBeginColumnNumber();
/** Returns the character offset of the beginning of this event.*/
public int getBeginCharacterOffset();
/** Returns the line number of the end of this event.*/
public int getEndLineNumber();
/** Returns the column number of the end of this event.*/
public int getEndColumnNumber();
/** Returns the character offset of the end of this event.*/
public int getEndCharacterOffset();
// other information
/** Returns true if this corresponding event was synthesized. */
public boolean isSynthesized();
/**
* Synthesized infoset item.
*
* @author Andy Clark
*/
public static class SynthesizedItem
implements HTMLEventInfo {
//
// HTMLEventInfo methods
//
// location information
/** Returns the line number of the beginning of this event.*/
public int getBeginLineNumber() {
return -1;
} // getBeginLineNumber():int
/** Returns the column number of the beginning of this event.*/
public int getBeginColumnNumber() {
return -1;
} // getBeginColumnNumber():int
/** Returns the character offset of the beginning of this event.*/
public int getBeginCharacterOffset() {
return -1;
} // getBeginCharacterOffset():int
/** Returns the line number of the end of this event.*/
public int getEndLineNumber() {
return -1;
} // getEndLineNumber():int
/** Returns the column number of the end of this event.*/
public int getEndColumnNumber() {
return -1;
} // getEndColumnNumber():int
/** Returns the character offset of the end of this event.*/
public int getEndCharacterOffset() {
return -1;
} // getEndCharacterOffset():int
// other information
/** Returns true if this corresponding event was synthesized. */
public boolean isSynthesized() {
return true;
} // isSynthesized():boolean
//
// Object methods
//
/** Returns a string representation of this object. */
public String toString() {
return "synthesized";
} // toString():String
} // class SynthesizedItem
} // interface HTMLEventInfo
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/HTMLEventInfo.java | Java | art | 3,517 |
/*
* Copyright Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLString;
/**
* Container for text that should be hold and re-feed later like text before <html> that will be re-feed
* in <body>
* @author Marc Guillemot
*
* @version $Id: LostText.java 226 2009-02-09 20:48:44Z mguillem $
*/
class LostText
{
/**
* Pair of (text, augmentation)
*/
static class Entry
{
private XMLString text_;
private Augmentations augs_;
public Entry(final XMLString text, final Augmentations augs)
{
final char[] chars = new char[text.length];
System.arraycopy(text.ch, text.offset, chars, 0, text.length);
text_ = new XMLString(chars, 0, chars.length);
if (augs != null)
augs_ = new HTMLAugmentations(augs);
}
}
private final List entries = new ArrayList();
/**
* Adds some text that need to be re-feed later. The information gets copied.
*/
public void add(final XMLString text, final Augmentations augs)
{
if (!entries.isEmpty() || text.toString().trim().length() > 0)
entries.add(new Entry(text, augs));
}
/**
* Pushes the characters into the {@link XMLDocumentHandler}
* @param tagBalancer the tag balancer that will receive the events
*/
public void refeed(final XMLDocumentHandler tagBalancer) {
for (final Iterator iter = entries.iterator(); iter.hasNext();) {
final LostText.Entry entry = (LostText.Entry) iter.next();
tagBalancer.characters(entry.text_, entry.augs_);
}
// not needed anymore once it has been used -> clear to free memory
entries.clear();
}
/**
* Indicates if this container contains something
* @return <code>true</code> if no lost text has been collected
*/
public boolean isEmpty() {
return entries.isEmpty();
}
} | zzh-simple-hr | Znekohtml/src/org/cyberneko/html/LostText.java | Java | art | 2,524 |
/*
* Copyright Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html.xercesbridge;
import org.apache.xerces.xni.NamespaceContext;
/**
* Xerces bridge for use with Xerces 2.3 and higher
* @author Marc Guillemot
*/
public class XercesBridge_2_3 extends XercesBridge_2_2
{
/**
* Should fail for Xerces version less than 2.3
* @throws InstantiationException if instantiation failed
*/
public XercesBridge_2_3() throws InstantiationException {
try {
final Class[] args = {String.class, String.class};
NamespaceContext.class.getMethod("declarePrefix", args);
}
catch (final NoSuchMethodException e) {
// means that we're not using Xerces 2.3 or higher
throw new InstantiationException(e.getMessage());
}
}
public void NamespaceContext_declarePrefix(final NamespaceContext namespaceContext,
final String ns, String avalue) {
namespaceContext.declarePrefix(ns, avalue);
}
}
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/xercesbridge/XercesBridge_2_3.java | Java | art | 1,524 |
/*
* Copyright Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html.xercesbridge;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import org.apache.xerces.xni.parser.XMLDocumentSource;
/**
* This class allows to transparently handle Xerces methods that have changed among versions.
* @author Marc Guillemot
*/
public abstract class XercesBridge
{
static private final XercesBridge instance = makeInstance();
/**
* The access point for the bridge.
* @return the instance corresponding to the Xerces version being currently used.
*/
public static XercesBridge getInstance()
{
return instance;
}
private static XercesBridge makeInstance()
{
final String[] classNames = {
"org.cyberneko.html.xercesbridge.XercesBridge_2_3",
"org.cyberneko.html.xercesbridge.XercesBridge_2_2",
"org.cyberneko.html.xercesbridge.XercesBridge_2_1",
"org.cyberneko.html.xercesbridge.XercesBridge_2_0"
};
for (int i = 0; i != classNames.length; ++i) {
final String className = classNames[i];
XercesBridge bridge = (XercesBridge) newInstanceOrNull(className);
if (bridge != null) {
return bridge;
}
}
throw new IllegalStateException("Failed to create XercesBridge instance");
}
private static XercesBridge newInstanceOrNull(final String className) {
try {
return (XercesBridge) Class.forName(className).newInstance();
}
catch (ClassNotFoundException ex) { }
catch (SecurityException ex) { }
catch (LinkageError ex) { }
catch (IllegalArgumentException e) { }
catch (IllegalAccessException e) { }
catch (InstantiationException e) { }
return null;
}
/**
* Default implementation does nothing
* @param namespaceContext
* @param ns
* @param avalue
*/
public void NamespaceContext_declarePrefix(NamespaceContext namespaceContext, String ns, String avalue) {
// nothing
}
/**
* Gets the Xerces version used
* @return the version
*/
public abstract String getVersion();
/**
* Calls startDocument on the {@link XMLDocumentHandler}.
*/
public abstract void XMLDocumentHandler_startDocument(XMLDocumentHandler documentHandler, XMLLocator locator,
String encoding, NamespaceContext nscontext, Augmentations augs);
/**
* Calls startPrefixMapping on the {@link XMLDocumentHandler}.
*/
public void XMLDocumentHandler_startPrefixMapping(
XMLDocumentHandler documentHandler, String prefix, String uri,
Augmentations augs) {
// default does nothing
}
/**
* Calls endPrefixMapping on the {@link XMLDocumentHandler}.
*/
public void XMLDocumentHandler_endPrefixMapping(
XMLDocumentHandler documentHandler, String prefix,
Augmentations augs) {
// default does nothing
}
/**
* Calls setDocumentSource (if available in the Xerces version used) on the {@link XMLDocumentFilter}.
* This implementation does nothing.
*/
public void XMLDocumentFilter_setDocumentSource(XMLDocumentFilter filter,
XMLDocumentSource lastSource)
{
// nothing, it didn't exist on old Xerces versions
}
}
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/xercesbridge/XercesBridge.java | Java | art | 3,891 |
/*
* Copyright Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html.xercesbridge;
import org.apache.xerces.impl.Version;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import org.apache.xerces.xni.parser.XMLDocumentSource;
/**
* Xerces bridge for use with Xerces 2.2 and higher
* @author Marc Guillemot
*/
public class XercesBridge_2_2 extends XercesBridge
{
/**
* Should fail for Xerces version less than 2.2
* @throws InstantiationException if instantiation failed
*/
protected XercesBridge_2_2() throws InstantiationException {
try {
getVersion();
}
catch (final Throwable e) {
throw new InstantiationException(e.getMessage());
}
}
public String getVersion() {
return Version.getVersion();
}
public void XMLDocumentHandler_startPrefixMapping(
XMLDocumentHandler documentHandler, String prefix, String uri,
Augmentations augs) {
// does nothing, not needed
}
public void XMLDocumentHandler_startDocument(XMLDocumentHandler documentHandler, XMLLocator locator,
String encoding, NamespaceContext nscontext, Augmentations augs) {
documentHandler.startDocument(locator, encoding, nscontext, augs);
}
public void XMLDocumentFilter_setDocumentSource(XMLDocumentFilter filter,
XMLDocumentSource lastSource) {
filter.setDocumentSource(lastSource);
}
}
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/xercesbridge/XercesBridge_2_2.java | Java | art | 2,097 |
/*
* Copyright Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html.xercesbridge;
import org.apache.xerces.impl.Version;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import org.apache.xerces.xni.parser.XMLDocumentSource;
/**
* Xerces bridge for use with Xerces 2.1.<br/>
* This file won't compile with recent versions of Xerces, this is normal.
* @author Marc Guillemot
*/
public class XercesBridge_2_1 extends XercesBridge
{
/**
* Should fail for Xerces version less than 2.1
* @throws InstantiationException if instantiation failed
*/
public XercesBridge_2_1() throws InstantiationException {
try {
// Just try and see if if we're called with Xerces 2.1 or higher
getVersion();
} catch (final Error e) {
throw new InstantiationException(e.getMessage());
}
}
public String getVersion() {
return new Version().getVersion();
}
public void XMLDocumentHandler_startDocument(XMLDocumentHandler documentHandler, XMLLocator locator,
String encoding, NamespaceContext nscontext, Augmentations augs) {
// documentHandler.startDocument(locator, encoding, augs);
}
public void XMLDocumentFilter_setDocumentSource(XMLDocumentFilter filter,
XMLDocumentSource lastSource) {
filter.setDocumentSource(lastSource);
}
}
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/xercesbridge/XercesBridge_2_1.java | Java | art | 2,050 |
/*
* Copyright Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html.xercesbridge;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.xerces.impl.Version;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLLocator;
/**
* Xerces bridge for use with Xerces 2.0.<br/>
* This file won't compile with recent versions of Xerces, this is normal.
* @author Marc Guillemot
*/
public class XercesBridge_2_0 extends XercesBridge
{
protected XercesBridge_2_0() {
// nothing, this is the last one that will be tried
}
public String getVersion() {
return Version.fVersion;
}
public void XMLDocumentHandler_startPrefixMapping(
XMLDocumentHandler documentHandler, String prefix, String uri,
Augmentations augs) {
// documentHandler.startPrefixMapping(prefix, uri, augs);
}
public void XMLDocumentHandler_endPrefixMapping(
XMLDocumentHandler documentHandler, String prefix,
Augmentations augs) {
// documentHandler.endPrefixMapping(prefix, augs);
}
public void XMLDocumentHandler_startDocument(XMLDocumentHandler documentHandler, XMLLocator locator,
String encoding, NamespaceContext nscontext, Augmentations augs) {
// documentHandler.startDocument(locator, encoding, augs);
}
}
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/xercesbridge/XercesBridge_2_0.java | Java | art | 1,939 |
/*
* Copyright 2002-2008 The Apache Software Foundation.
*
* Licensed 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.
*/
package org.cyberneko.html;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
/**
* This class is duplicated for each JAXP subpackage so keep it in sync.
* It is package private and therefore is not exposed as part of the JAXP
* API.
*
* Base class with security related methods that work on JDK 1.1.
*/
class SecuritySupport {
/*
* Make this of type Object so that the verifier won't try to
* prove its type, thus possibly trying to load the SecuritySupport12
* class.
*/
private static final Object securitySupport;
static {
SecuritySupport ss = null;
try {
Class c = Class.forName("java.security.AccessController");
// if that worked, we're on 1.2.
/*
// don't reference the class explicitly so it doesn't
// get dragged in accidentally.
c = Class.forName("javax.mail.SecuritySupport12");
Constructor cons = c.getConstructor(new Class[] { });
ss = (SecuritySupport)cons.newInstance(new Object[] { });
*/
/*
* Unfortunately, we can't load the class using reflection
* because the class is package private. And the class has
* to be package private so the APIs aren't exposed to other
* code that could use them to circumvent security. Thus,
* we accept the risk that the direct reference might fail
* on some JDK 1.1 JVMs, even though we would never execute
* this code in such a case. Sigh...
*/
ss = new SecuritySupport12();
} catch (Exception ex) {
// ignore it
} finally {
if (ss == null)
ss = new SecuritySupport();
securitySupport = ss;
}
}
/**
* Return an appropriate instance of this class, depending on whether
* we're on a JDK 1.1 or J2SE 1.2 (or later) system.
*/
static SecuritySupport getInstance() {
return (SecuritySupport)securitySupport;
}
ClassLoader getContextClassLoader() {
return null;
}
ClassLoader getSystemClassLoader() {
return null;
}
ClassLoader getParentClassLoader(ClassLoader cl) {
return null;
}
String getSystemProperty(String propName) {
return System.getProperty(propName);
}
FileInputStream getFileInputStream(File file)
throws FileNotFoundException
{
return new FileInputStream(file);
}
InputStream getResourceAsStream(ClassLoader cl, String name) {
InputStream ris;
if (cl == null) {
ris = ClassLoader.getSystemResourceAsStream(name);
} else {
ris = cl.getResourceAsStream(name);
}
return ris;
}
boolean getFileExists(File f) {
return f.exists();
}
long getLastModified(File f) {
return f.lastModified();
}
}
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/SecuritySupport.java | Java | art | 3,443 |
/*
* Copyright 2002-2008 The Apache Software Foundation.
*
* Licensed 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.
*/
package org.cyberneko.html;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
/**
* This class is duplicated for each JAXP subpackage so keep it in sync.
* It is package private and therefore is not exposed as part of the JAXP
* API.
*
* Security related methods that only work on J2SE 1.2 and newer.
*/
class SecuritySupport12 extends SecuritySupport {
ClassLoader getContextClassLoader() {
return (ClassLoader)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
} catch (SecurityException ex) { }
return cl;
}
});
}
ClassLoader getSystemClassLoader() {
return (ClassLoader)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ClassLoader cl = null;
try {
cl = ClassLoader.getSystemClassLoader();
} catch (SecurityException ex) {}
return cl;
}
});
}
ClassLoader getParentClassLoader(final ClassLoader cl) {
return (ClassLoader)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ClassLoader parent = null;
try {
parent = cl.getParent();
} catch (SecurityException ex) {}
// eliminate loops in case of the boot
// ClassLoader returning itself as a parent
return (parent == cl) ? null : parent;
}
});
}
String getSystemProperty(final String propName) {
return (String)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return System.getProperty(propName);
}
});
}
FileInputStream getFileInputStream(final File file)
throws FileNotFoundException
{
try {
return (FileInputStream)
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws FileNotFoundException {
return new FileInputStream(file);
}
});
} catch (PrivilegedActionException e) {
throw (FileNotFoundException)e.getException();
}
}
InputStream getResourceAsStream(final ClassLoader cl,
final String name)
{
return (InputStream)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
InputStream ris;
if (cl == null) {
ris = ClassLoader.getSystemResourceAsStream(name);
} else {
ris = cl.getResourceAsStream(name);
}
return ris;
}
});
}
boolean getFileExists(final File f) {
return ((Boolean)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return new Boolean(f.exists());
}
})).booleanValue();
}
long getLastModified(final File f) {
return ((Long)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return new Long(f.lastModified());
}
})).longValue();
}
}
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/SecuritySupport12.java | Java | art | 4,489 |
/*
* Copyright 2001-2008 The Apache Software Foundation.
*
* Licensed 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.
*/
package org.cyberneko.html;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
/**
* This class is duplicated for each JAXP subpackage so keep it in sync.
* It is package private and therefore is not exposed as part of the JAXP
* API.
* <p>
* This code is designed to implement the JAXP 1.1 spec pluggability
* feature and is designed to run on JDK version 1.1 and
* later, and to compile on JDK 1.2 and onward.
* The code also runs both as part of an unbundled jar file and
* when bundled as part of the JDK.
* <p>
*
* @version $Id: ObjectFactory.java,v 1.1 2004/03/31 20:00:21 andyc Exp $
*/
class ObjectFactory {
//
// Constants
//
// name of default properties file to look for in JDK's jre/lib directory
private static final String DEFAULT_PROPERTIES_FILENAME = "xerces.properties";
/** Set to true for debugging */
private static final boolean DEBUG = false;
/**
* Default columns per line.
*/
private static final int DEFAULT_LINE_LENGTH = 80;
/** cache the contents of the xerces.properties file.
* Until an attempt has been made to read this file, this will
* be null; if the file does not exist or we encounter some other error
* during the read, this will be empty.
*/
private static Properties fXercesProperties = null;
/***
* Cache the time stamp of the xerces.properties file so
* that we know if it's been modified and can invalidate
* the cache when necessary.
*/
private static long fLastModified = -1;
//
// static methods
//
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId, String fallbackClassName)
throws ConfigurationError {
return createObject(factoryId, null, fallbackClassName);
} // createObject(String,String):Object
/**
* Finds the implementation Class object in the specified order. The
* specified order is the following:
* <ol>
* <li>query the system property using <code>System.getProperty</code>
* <li>read <code>$java.home/lib/<i>propertiesFilename</i></code> file
* <li>read <code>META-INF/services/<i>factoryId</i></code> file
* <li>use fallback classname
* </ol>
*
* @return Class object of factory, never null
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param propertiesFilename The filename in the $java.home/lib directory
* of the properties file. If none specified,
* ${java.home}/lib/xerces.properties will be used.
* @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback.
*
* @exception ObjectFactory.ConfigurationError
*/
static Object createObject(String factoryId,
String propertiesFilename,
String fallbackClassName)
throws ConfigurationError
{
if (DEBUG) debugPrintln("debug is on");
SecuritySupport ss = SecuritySupport.getInstance();
ClassLoader cl = findClassLoader();
// Use the system property first
try {
String systemProp = ss.getSystemProperty(factoryId);
if (systemProp != null) {
if (DEBUG) debugPrintln("found system property, value=" + systemProp);
return newInstance(systemProp, cl, true);
}
} catch (SecurityException se) {
// Ignore and continue w/ next location
}
// Try to read from propertiesFilename, or $java.home/lib/xerces.properties
String factoryClassName = null;
// no properties file name specified; use $JAVA_HOME/lib/xerces.properties:
if (propertiesFilename == null) {
File propertiesFile = null;
boolean propertiesFileExists = false;
try {
String javah = ss.getSystemProperty("java.home");
propertiesFilename = javah + File.separator +
"lib" + File.separator + DEFAULT_PROPERTIES_FILENAME;
propertiesFile = new File(propertiesFilename);
propertiesFileExists = ss.getFileExists(propertiesFile);
} catch (SecurityException e) {
// try again...
fLastModified = -1;
fXercesProperties = null;
}
synchronized (ObjectFactory.class) {
boolean loadProperties = false;
try {
// file existed last time
if(fLastModified >= 0) {
if(propertiesFileExists &&
(fLastModified < (fLastModified = ss.getLastModified(propertiesFile)))) {
loadProperties = true;
} else {
// file has stopped existing...
if(!propertiesFileExists) {
fLastModified = -1;
fXercesProperties = null;
} // else, file wasn't modified!
}
} else {
// file has started to exist:
if(propertiesFileExists) {
loadProperties = true;
fLastModified = ss.getLastModified(propertiesFile);
} // else, nothing's changed
}
if(loadProperties) {
// must never have attempted to read xerces.properties before (or it's outdeated)
fXercesProperties = new Properties();
FileInputStream fis = ss.getFileInputStream(propertiesFile);
fXercesProperties.load(fis);
fis.close();
}
} catch (Exception x) {
fXercesProperties = null;
fLastModified = -1;
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
}
if(fXercesProperties != null) {
factoryClassName = fXercesProperties.getProperty(factoryId);
}
} else {
try {
FileInputStream fis = ss.getFileInputStream(new File(propertiesFilename));
Properties props = new Properties();
props.load(fis);
fis.close();
factoryClassName = props.getProperty(factoryId);
} catch (Exception x) {
// assert(x instanceof FileNotFoundException
// || x instanceof SecurityException)
// In both cases, ignore and continue w/ next location
}
}
if (factoryClassName != null) {
if (DEBUG) debugPrintln("found in " + propertiesFilename + ", value=" + factoryClassName);
return newInstance(factoryClassName, cl, true);
}
// Try Jar Service Provider Mechanism
Object provider = findJarServiceProvider(factoryId);
if (provider != null) {
return provider;
}
if (fallbackClassName == null) {
throw new ConfigurationError(
"Provider for " + factoryId + " cannot be found", null);
}
if (DEBUG) debugPrintln("using fallback, value=" + fallbackClassName);
return newInstance(fallbackClassName, cl, true);
} // createObject(String,String,String):Object
//
// Private static methods
//
/** Prints a message to standard error if debugging is enabled. */
private static void debugPrintln(String msg) {
if (DEBUG) {
System.err.println("JAXP: " + msg);
}
} // debugPrintln(String)
/**
* Figure out which ClassLoader to use. For JDK 1.2 and later use
* the context ClassLoader.
*/
static ClassLoader findClassLoader()
throws ConfigurationError
{
SecuritySupport ss = SecuritySupport.getInstance();
// Figure out which ClassLoader to use for loading the provider
// class. If there is a Context ClassLoader then use it.
ClassLoader context = ss.getContextClassLoader();
ClassLoader system = ss.getSystemClassLoader();
ClassLoader chain = system;
while (true) {
if (context == chain) {
// Assert: we are on JDK 1.1 or we have no Context ClassLoader
// or any Context ClassLoader in chain of system classloader
// (including extension ClassLoader) so extend to widest
// ClassLoader (always look in system ClassLoader if Xerces
// is in boot/extension/system classpath and in current
// ClassLoader otherwise); normal classloaders delegate
// back to system ClassLoader first so this widening doesn't
// change the fact that context ClassLoader will be consulted
ClassLoader current = ObjectFactory.class.getClassLoader();
chain = system;
while (true) {
if (current == chain) {
// Assert: Current ClassLoader in chain of
// boot/extension/system ClassLoaders
return system;
}
if (chain == null) {
break;
}
chain = ss.getParentClassLoader(chain);
}
// Assert: Current ClassLoader not in chain of
// boot/extension/system ClassLoaders
return current;
}
if (chain == null) {
// boot ClassLoader reached
break;
}
// Check for any extension ClassLoaders in chain up to
// boot ClassLoader
chain = ss.getParentClassLoader(chain);
};
// Assert: Context ClassLoader not in chain of
// boot/extension/system ClassLoaders
return context;
} // findClassLoader():ClassLoader
/**
* Create an instance of a class using the specified ClassLoader
*/
static Object newInstance(String className, ClassLoader cl,
boolean doFallback)
throws ConfigurationError
{
// assert(className != null);
try{
Class providerClass = findProviderClass(className, cl, doFallback);
Object instance = providerClass.newInstance();
if (DEBUG) debugPrintln("created new instance of " + providerClass +
" using ClassLoader: " + cl);
return instance;
} catch (ClassNotFoundException x) {
throw new ConfigurationError(
"Provider " + className + " not found", x);
} catch (Exception x) {
throw new ConfigurationError(
"Provider " + className + " could not be instantiated: " + x,
x);
}
}
/**
* Find a Class using the specified ClassLoader
*/
static Class findProviderClass(String className, ClassLoader cl,
boolean doFallback)
throws ClassNotFoundException, ConfigurationError
{
//throw security exception if the calling thread is not allowed to access the package
//restrict the access to package as speicified in java.security policy
SecurityManager security = System.getSecurityManager();
try{
if (security != null) {
final int lastDot = className.lastIndexOf(".");
String packageName = className;
if (lastDot != -1) packageName = className.substring(0, lastDot);
security.checkPackageAccess(packageName);
}
}catch(SecurityException e){
throw e ;
}
Class providerClass;
if (cl == null) {
// XXX Use the bootstrap ClassLoader. There is no way to
// load a class using the bootstrap ClassLoader that works
// in both JDK 1.1 and Java 2. However, this should still
// work b/c the following should be true:
//
// (cl == null) iff current ClassLoader == null
//
// Thus Class.forName(String) will use the current
// ClassLoader which will be the bootstrap ClassLoader.
providerClass = Class.forName(className);
} else {
try {
providerClass = cl.loadClass(className);
} catch (ClassNotFoundException x) {
if (doFallback) {
// Fall back to current classloader
ClassLoader current = ObjectFactory.class.getClassLoader();
if (current == null) {
providerClass = Class.forName(className);
} else if (cl != current) {
cl = current;
providerClass = cl.loadClass(className);
} else {
throw x;
}
} else {
throw x;
}
}
}
return providerClass;
}
/*
* Try to find provider using Jar Service Provider Mechanism
*
* @return instance of provider class if found or null
*/
private static Object findJarServiceProvider(String factoryId)
throws ConfigurationError
{
SecuritySupport ss = SecuritySupport.getInstance();
String serviceId = "META-INF/services/" + factoryId;
InputStream is = null;
// First try the Context ClassLoader
ClassLoader cl = findClassLoader();
is = ss.getResourceAsStream(cl, serviceId);
// If no provider found then try the current ClassLoader
if (is == null) {
ClassLoader current = ObjectFactory.class.getClassLoader();
if (cl != current) {
cl = current;
is = ss.getResourceAsStream(cl, serviceId);
}
}
if (is == null) {
// No provider found
return null;
}
if (DEBUG) debugPrintln("found jar resource=" + serviceId +
" using ClassLoader: " + cl);
// Read the service provider name in UTF-8 as specified in
// the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
// doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
// VJ++ this is apparently ASCII, which is a subset of
// UTF-8... and since the strings we'll be reading here are
// also primarily limited to the 7-bit ASCII range (at
// least, in English versions), this should work well
// enough to keep us on the air until we're ready to
// officially decommit from VJ++. [Edited comment from
// jkesselm]
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"), DEFAULT_LINE_LENGTH);
} catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is), DEFAULT_LINE_LENGTH);
}
String factoryClassName = null;
try {
// XXX Does not handle all possible input as specified by the
// Jar Service Provider specification
factoryClassName = rd.readLine();
rd.close();
} catch (IOException x) {
// No provider found
return null;
}
if (factoryClassName != null &&
! "".equals(factoryClassName)) {
if (DEBUG) debugPrintln("found in resource, value="
+ factoryClassName);
// Note: here we do not want to fall back to the current
// ClassLoader because we want to avoid the case where the
// resource file was found using one ClassLoader and the
// provider class was instantiated using a different one.
return newInstance(factoryClassName, cl, false);
}
// No provider found
return null;
}
//
// Classes
//
/**
* A configuration error.
*/
static class ConfigurationError
extends Error {
//
// Data
//
/** Exception. */
private Exception exception;
//
// Constructors
//
/**
* Construct a new instance with the specified detail string and
* exception.
*/
ConfigurationError(String msg, Exception x) {
super(msg);
this.exception = x;
} // <init>(String,Exception)
//
// methods
//
/** Returns the exception associated to this error. */
Exception getException() {
return exception;
} // getException():Exception
} // class ConfigurationError
} // class ObjectFactory
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/ObjectFactory.java | Java | art | 19,283 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html.filters;
import java.util.Hashtable;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
/**
* This class is a document filter capable of removing specified
* elements from the processing stream. There are two options for
* processing document elements:
* <ul>
* <li>specifying those elements which should be accepted and,
* optionally, which attributes of that element should be
* kept; and
* <li>specifying those elements whose tags and content should be
* completely removed from the event stream.
* </ul>
* <p>
* The first option allows the application to specify which elements
* appearing in the event stream should be accepted and, therefore,
* passed on to the next stage in the pipeline. All elements
* <em>not</em> in the list of acceptable elements have their start
* and end tags stripped from the event stream <em>unless</em> those
* elements appear in the list of elements to be removed.
* <p>
* The second option allows the application to specify which elements
* should be completely removed from the event stream. When an element
* appears that is to be removed, the element's start and end tag as
* well as all of that element's content is removed from the event
* stream.
* <p>
* A common use of this filter would be to only allow rich-text
* and linking elements as well as the character content to pass
* through the filter — all other elements would be stripped.
* The following code shows how to configure this filter to perform
* this task:
* <pre>
* ElementRemover remover = new ElementRemover();
* remover.acceptElement("b", null);
* remover.acceptElement("i", null);
* remover.acceptElement("u", null);
* remover.acceptElement("a", new String[] { "href" });
* </pre>
* <p>
* However, this would still allow the text content of other
* elements to pass through, which may not be desirable. In order
* to further "clean" the input, the <code>removeElement</code>
* option can be used. The following piece of code adds the ability
* to completely remove any <SCRIPT> tags and content
* from the stream.
* <pre>
* remover.removeElement("script");
* </pre>
* <p>
* <strong>Note:</strong>
* All text and accepted element children of a stripped element is
* retained. To completely remove an element's content, use the
* <code>removeElement</code> method.
* <p>
* <strong>Note:</strong>
* Care should be taken when using this filter because the output
* may not be a well-balanced tree. Specifically, if the application
* removes the <HTML> element (with or without retaining its
* children), the resulting document event stream will no longer be
* well-formed.
*
* @author Andy Clark
*
* @version $Id: ElementRemover.java,v 1.5 2005/02/14 03:56:54 andyc Exp $
*/
public class ElementRemover
extends DefaultFilter {
//
// Constants
//
/** A "null" object. */
protected static final Object NULL = new Object();
//
// Data
//
// information
/** Accepted elements. */
protected Hashtable fAcceptedElements = new Hashtable();
/** Removed elements. */
protected Hashtable fRemovedElements = new Hashtable();
// state
/** The element depth. */
protected int fElementDepth;
/** The element depth at element removal. */
protected int fRemovalElementDepth;
//
// Public methods
//
/**
* Specifies that the given element should be accepted and, optionally,
* which attributes of that element should be kept.
*
* @param element The element to accept.
* @param attributes The list of attributes to be kept or null if no
* attributes should be kept for this element.
*
* see #removeElement
*/
public void acceptElement(String element, String[] attributes) {
Object key = element.toLowerCase();
Object value = NULL;
if (attributes != null) {
String[] newarray = new String[attributes.length];
for (int i = 0; i < attributes.length; i++) {
newarray[i] = attributes[i].toLowerCase();
}
value = attributes;
}
fAcceptedElements.put(key, value);
} // acceptElement(String,String[])
/**
* Specifies that the given element should be completely removed. If an
* element is encountered during processing that is on the remove list,
* the element's start and end tags as well as all of content contained
* within the element will be removed from the processing stream.
*
* @param element The element to completely remove.
*/
public void removeElement(String element) {
Object key = element.toLowerCase();
Object value = NULL;
fRemovedElements.put(key, value);
} // removeElement(String)
//
// XMLDocumentHandler methods
//
// since Xerces-J 2.2.0
/** Start document. */
public void startDocument(XMLLocator locator, String encoding,
NamespaceContext nscontext, Augmentations augs)
throws XNIException {
fElementDepth = 0;
fRemovalElementDepth = Integer.MAX_VALUE;
super.startDocument(locator, encoding, nscontext, augs);
} // startDocument(XMLLocator,String,NamespaceContext,Augmentations)
// old methods
/** Start document. */
public void startDocument(XMLLocator locator, String encoding, Augmentations augs)
throws XNIException {
startDocument(locator, encoding, null, augs);
} // startDocument(XMLLocator,String,Augmentations)
/** Start prefix mapping. */
public void startPrefixMapping(String prefix, String uri, Augmentations augs)
throws XNIException {
if (fElementDepth <= fRemovalElementDepth) {
super.startPrefixMapping(prefix, uri, augs);
}
} // startPrefixMapping(String,String,Augmentations)
/** Start element. */
public void startElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
if (fElementDepth <= fRemovalElementDepth && handleOpenTag(element, attributes)) {
super.startElement(element, attributes, augs);
}
fElementDepth++;
} // startElement(QName,XMLAttributes,Augmentations)
/** Empty element. */
public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
if (fElementDepth <= fRemovalElementDepth && handleOpenTag(element, attributes)) {
super.emptyElement(element, attributes, augs);
}
} // emptyElement(QName,XMLAttributes,Augmentations)
/** Comment. */
public void comment(XMLString text, Augmentations augs)
throws XNIException {
if (fElementDepth <= fRemovalElementDepth) {
super.comment(text, augs);
}
} // comment(XMLString,Augmentations)
/** Processing instruction. */
public void processingInstruction(String target, XMLString data, Augmentations augs)
throws XNIException {
if (fElementDepth <= fRemovalElementDepth) {
super.processingInstruction(target, data, augs);
}
} // processingInstruction(String,XMLString,Augmentations)
/** Characters. */
public void characters(XMLString text, Augmentations augs)
throws XNIException {
if (fElementDepth <= fRemovalElementDepth) {
super.characters(text, augs);
}
} // characters(XMLString,Augmentations)
/** Ignorable whitespace. */
public void ignorableWhitespace(XMLString text, Augmentations augs)
throws XNIException {
if (fElementDepth <= fRemovalElementDepth) {
super.ignorableWhitespace(text, augs);
}
} // ignorableWhitespace(XMLString,Augmentations)
/** Start general entity. */
public void startGeneralEntity(String name, XMLResourceIdentifier id, String encoding, Augmentations augs)
throws XNIException {
if (fElementDepth <= fRemovalElementDepth) {
super.startGeneralEntity(name, id, encoding, augs);
}
} // startGeneralEntity(String,XMLResourceIdentifier,String,Augmentations)
/** Text declaration. */
public void textDecl(String version, String encoding, Augmentations augs)
throws XNIException {
if (fElementDepth <= fRemovalElementDepth) {
super.textDecl(version, encoding, augs);
}
} // textDecl(String,String,Augmentations)
/** End general entity. */
public void endGeneralEntity(String name, Augmentations augs)
throws XNIException {
if (fElementDepth <= fRemovalElementDepth) {
super.endGeneralEntity(name, augs);
}
} // endGeneralEntity(String,Augmentations)
/** Start CDATA section. */
public void startCDATA(Augmentations augs) throws XNIException {
if (fElementDepth <= fRemovalElementDepth) {
super.startCDATA(augs);
}
} // startCDATA(Augmentations)
/** End CDATA section. */
public void endCDATA(Augmentations augs) throws XNIException {
if (fElementDepth <= fRemovalElementDepth) {
super.endCDATA(augs);
}
} // endCDATA(Augmentations)
/** End element. */
public void endElement(QName element, Augmentations augs)
throws XNIException {
if (fElementDepth <= fRemovalElementDepth && elementAccepted(element.rawname)) {
super.endElement(element, augs);
}
fElementDepth--;
if (fElementDepth == fRemovalElementDepth) {
fRemovalElementDepth = Integer.MAX_VALUE;
}
} // endElement(QName,Augmentations)
/** End prefix mapping. */
public void endPrefixMapping(String prefix, Augmentations augs)
throws XNIException {
if (fElementDepth <= fRemovalElementDepth) {
super.endPrefixMapping(prefix, augs);
}
} // endPrefixMapping(String,Augmentations)
//
// Protected methods
//
/** Returns true if the specified element is accepted. */
protected boolean elementAccepted(String element) {
Object key = element.toLowerCase();
return fAcceptedElements.containsKey(key);
} // elementAccepted(String):boolean
/** Returns true if the specified element should be removed. */
protected boolean elementRemoved(String element) {
Object key = element.toLowerCase();
return fRemovedElements.containsKey(key);
} // elementRemoved(String):boolean
/** Handles an open tag. */
protected boolean handleOpenTag(QName element, XMLAttributes attributes) {
if (elementAccepted(element.rawname)) {
Object key = element.rawname.toLowerCase();
Object value = fAcceptedElements.get(key);
if (value != NULL) {
String[] anames = (String[])value;
int attributeCount = attributes.getLength();
LOOP: for (int i = 0; i < attributeCount; i++) {
String aname = attributes.getQName(i).toLowerCase();
for (int j = 0; j < anames.length; j++) {
if (anames[j].equals(aname)) {
continue LOOP;
}
}
attributes.removeAttributeAt(i--);
attributeCount--;
}
}
else {
attributes.removeAllAttributes();
}
return true;
}
else if (elementRemoved(element.rawname)) {
fRemovalElementDepth = fElementDepth;
}
return false;
} // handleOpenTag(QName,XMLAttributes):boolean
} // class DefaultFilter
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/filters/ElementRemover.java | Java | art | 12,742 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html.filters;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XNIException;
import org.cyberneko.html.HTMLEventInfo;
/**
* This filter performs the identity operation of the original
* document event stream generated by the HTML scanner by removing
* events that are synthesized by the tag balancer. This operation
* is essentially the same as turning off tag-balancing in the
* parser. However, this filter is useful when you want the tag
* balancer to report "errors" but do not want the synthesized
* events in the output.
* <p>
* <strong>Note:</strong>
* This filter requires the augmentations feature to be turned on.
* For example:
* <pre>
* XMLParserConfiguration parser = new HTMLConfiguration();
* parser.setFeature("http://cyberneko.org/html/features/augmentations", true);
* </pre>
* <p>
* <strong>Note:</strong>
* This isn't <em>exactly</em> the identify transform because the
* element and attributes names may have been modified from the
* original document. For example, by default, NekoHTML converts
* element names to upper-case and attribute names to lower-case.
*
* @author Andy Clark
*
* @version $Id: Identity.java,v 1.4 2005/02/14 03:56:54 andyc Exp $
*/
public class Identity
extends DefaultFilter {
//
// Constants
//
/** Augmentations feature identifier. */
protected static final String AUGMENTATIONS = "http://cyberneko.org/html/features/augmentations";
/** Filters property identifier. */
protected static final String FILTERS = "http://cyberneko.org/html/properties/filters";
//
// XMLDocumentHandler methods
//
/** Start element. */
public void startElement(QName element, XMLAttributes attributes,
Augmentations augs) throws XNIException {
if (augs == null || !synthesized(augs)) {
super.startElement(element, attributes, augs);
}
} // startElement(QName,XMLAttributes,Augmentations)
/** Empty element. */
public void emptyElement(QName element, XMLAttributes attributes,
Augmentations augs) throws XNIException {
if (augs == null || !synthesized(augs)) {
super.emptyElement(element, attributes, augs);
}
} // emptyElement(QName,XMLAttributes,Augmentations)
/** End element. */
public void endElement(QName element, Augmentations augs)
throws XNIException {
if (augs == null || !synthesized(augs)) {
super.endElement(element, augs);
}
} // endElement(QName,XMLAttributes,Augmentations)
//
// Protected static methods
//
/** Returns true if the information provided is synthesized. */
protected static boolean synthesized(Augmentations augs) {
HTMLEventInfo info = (HTMLEventInfo)augs.getItem(AUGMENTATIONS);
return info != null ? info.isSynthesized() : false;
} // synthesized(Augmentations):boolean
} // class Identity
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/filters/Identity.java | Java | art | 3,709 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html.filters;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import org.apache.xerces.xni.parser.XMLDocumentSource;
import org.cyberneko.html.HTMLComponent;
import org.cyberneko.html.xercesbridge.XercesBridge;
/**
* This class implements a filter that simply passes document
* events to the next handler. It can be used as a base class to
* simplify the development of new document filters.
*
* @author Andy Clark
*
* @version $Id: DefaultFilter.java,v 1.7 2005/02/14 03:56:54 andyc Exp $
*/
public class DefaultFilter
implements XMLDocumentFilter, HTMLComponent {
//
// Data
//
/** Document handler. */
protected XMLDocumentHandler fDocumentHandler;
/** Document source. */
protected XMLDocumentSource fDocumentSource;
//
// XMLDocumentSource methods
//
/** Sets the document handler. */
public void setDocumentHandler(XMLDocumentHandler handler) {
fDocumentHandler = handler;
} // setDocumentHandler(XMLDocumentHandler)
// @since Xerces 2.1.0
/** Returns the document handler. */
public XMLDocumentHandler getDocumentHandler() {
return fDocumentHandler;
} // getDocumentHandler():XMLDocumentHandler
/** Sets the document source. */
public void setDocumentSource(XMLDocumentSource source) {
fDocumentSource = source;
} // setDocumentSource(XMLDocumentSource)
/** Returns the document source. */
public XMLDocumentSource getDocumentSource() {
return fDocumentSource;
} // getDocumentSource():XMLDocumentSource
//
// XMLDocumentHandler methods
//
// since Xerces-J 2.2.0
/** Start document. */
public void startDocument(XMLLocator locator, String encoding,
NamespaceContext nscontext, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
XercesBridge.getInstance().XMLDocumentHandler_startDocument(fDocumentHandler, locator, encoding, nscontext, augs);
}
} // startDocument(XMLLocator,String,Augmentations)
// old methods
/** XML declaration. */
public void xmlDecl(String version, String encoding, String standalone, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.xmlDecl(version, encoding, standalone, augs);
}
} // xmlDecl(String,String,String,Augmentations)
/** Doctype declaration. */
public void doctypeDecl(String root, String publicId, String systemId, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.doctypeDecl(root, publicId, systemId, augs);
}
} // doctypeDecl(String,String,String,Augmentations)
/** Comment. */
public void comment(XMLString text, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.comment(text, augs);
}
} // comment(XMLString,Augmentations)
/** Processing instruction. */
public void processingInstruction(String target, XMLString data, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.processingInstruction(target, data, augs);
}
} // processingInstruction(String,XMLString,Augmentations)
/** Start element. */
public void startElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.startElement(element, attributes, augs);
}
} // startElement(QName,XMLAttributes,Augmentations)
/** Empty element. */
public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.emptyElement(element, attributes, augs);
}
} // emptyElement(QName,XMLAttributes,Augmentations)
/** Characters. */
public void characters(XMLString text, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.characters(text, augs);
}
} // characters(XMLString,Augmentations)
/** Ignorable whitespace. */
public void ignorableWhitespace(XMLString text, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.ignorableWhitespace(text, augs);
}
} // ignorableWhitespace(XMLString,Augmentations)
/** Start general entity. */
public void startGeneralEntity(String name, XMLResourceIdentifier id, String encoding, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.startGeneralEntity(name, id, encoding, augs);
}
} // startGeneralEntity(String,XMLResourceIdentifier,String,Augmentations)
/** Text declaration. */
public void textDecl(String version, String encoding, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.textDecl(version, encoding, augs);
}
} // textDecl(String,String,Augmentations)
/** End general entity. */
public void endGeneralEntity(String name, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.endGeneralEntity(name, augs);
}
} // endGeneralEntity(String,Augmentations)
/** Start CDATA section. */
public void startCDATA(Augmentations augs) throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.startCDATA(augs);
}
} // startCDATA(Augmentations)
/** End CDATA section. */
public void endCDATA(Augmentations augs) throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.endCDATA(augs);
}
} // endCDATA(Augmentations)
/** End element. */
public void endElement(QName element, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.endElement(element, augs);
}
} // endElement(QName,Augmentations)
/** End document. */
public void endDocument(Augmentations augs) throws XNIException {
if (fDocumentHandler != null) {
fDocumentHandler.endDocument(augs);
}
} // endDocument(Augmentations)
// removed since Xerces-J 2.3.0
/** Start document. */
public void startDocument(XMLLocator locator, String encoding, Augmentations augs)
throws XNIException {
startDocument(locator, encoding, null, augs);
} // startDocument(XMLLocator,String,Augmentations)
/** Start prefix mapping. */
public void startPrefixMapping(String prefix, String uri, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
XercesBridge.getInstance().XMLDocumentHandler_startPrefixMapping(fDocumentHandler, prefix, uri, augs);
}
} // startPrefixMapping(String,String,Augmentations)
/** End prefix mapping. */
public void endPrefixMapping(String prefix, Augmentations augs)
throws XNIException {
if (fDocumentHandler != null) {
XercesBridge.getInstance().XMLDocumentHandler_endPrefixMapping(fDocumentHandler, prefix, augs);
}
} // endPrefixMapping(String,Augmentations)
//
// HTMLComponent methods
//
/**
* Returns a list of feature identifiers that are recognized by
* this component. This method may return null if no features
* are recognized by this component.
*/
public String[] getRecognizedFeatures() {
return null;
} // getRecognizedFeatures():String[]
/**
* Returns the default state for a feature, or null if this
* component does not want to report a default value for this
* feature.
*/
public Boolean getFeatureDefault(String featureId) {
return null;
} // getFeatureDefault(String):Boolean
/**
* Returns a list of property identifiers that are recognized by
* this component. This method may return null if no properties
* are recognized by this component.
*/
public String[] getRecognizedProperties() {
return null;
} // getRecognizedProperties():String[]
/**
* Returns the default state for a property, or null if this
* component does not want to report a default value for this
* property.
*/
public Object getPropertyDefault(String propertyId) {
return null;
} // getPropertyDefault(String):Object
/**
* Resets the component. The component can query the component manager
* about any features and properties that affect the operation of the
* component.
*
* @param componentManager The component manager.
*
* @throws XNIException Thrown by component on initialization error.
*/
public void reset(XMLComponentManager componentManager)
throws XMLConfigurationException {
} // reset(XMLComponentManager)
/**
* Sets the state of a feature. This method is called by the component
* manager any time after reset when a feature changes state.
* <p>
* <strong>Note:</strong> Components should silently ignore features
* that do not affect the operation of the component.
*
* @param featureId The feature identifier.
* @param state The state of the feature.
*
* @throws XMLConfigurationException Thrown for configuration error.
* In general, components should
* only throw this exception if
* it is <strong>really</strong>
* a critical error.
*/
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
} // setFeature(String,boolean)
/**
* Sets the value of a property. This method is called by the component
* manager any time after reset when a property changes value.
* <p>
* <strong>Note:</strong> Components should silently ignore properties
* that do not affect the operation of the component.
*
* @param propertyId The property identifier.
* @param value The value of the property.
*
* @throws XMLConfigurationException Thrown for configuration error.
* In general, components should
* only throw this exception if
* it is <strong>really</strong>
* a critical error.
*/
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
} // setProperty(String,Object)
//
// Protected static methods
//
/**
* Utility method for merging string arrays for recognized features
* and recognized properties.
*/
protected static String[] merge(String[] array1, String[] array2) {
// shortcut merge
if (array1 == array2) {
return array1;
}
if (array1 == null) {
return array2;
}
if (array2 == null) {
return array1;
}
// full merge
String[] array3 = new String[array1.length + array2.length];
System.arraycopy(array1, 0, array3, 0, array1.length);
System.arraycopy(array2, 0, array3, array1.length, array2.length);
return array3;
} // merge(String[],String[]):String[]
} // class DefaultFilter
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/filters/DefaultFilter.java | Java | art | 12,932 |
/*
* Copyright 2004-2008 Andy Clark
*
* Licensed 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.
*/
package org.cyberneko.html.filters;
import java.util.Enumeration;
import java.util.Vector;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.cyberneko.html.HTMLElements;
import org.cyberneko.html.xercesbridge.XercesBridge;
/**
* This filter binds namespaces if namespace processing is turned on
* by setting the feature "http://xml.org/sax/features/namespaces" is
* set to <code>true</code>.
* <p>
* This configuration recognizes the following features:
* <ul>
* <li>http://xml.org/sax/features/namespaces
* </ul>
*
* @author Andy Clark
*
* @version $Id: NamespaceBinder.java,v 1.8 2005/05/30 00:19:28 andyc Exp $
*/
public class NamespaceBinder
extends DefaultFilter {
//
// Constants
//
// namespace uris
/** XHTML 1.0 namespace URI (http://www.w3.org/1999/xhtml). */
public static final String XHTML_1_0_URI = "http://www.w3.org/1999/xhtml";
/** XML namespace URI (http://www.w3.org/XML/1998/namespace). */
public static final String XML_URI = "http://www.w3.org/XML/1998/namespace";
/** XMLNS namespace URI (http://www.w3.org/2000/xmlns/). */
public static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/";
// features
/** Namespaces. */
protected static final String NAMESPACES = "http://xml.org/sax/features/namespaces";
/** Override namespace binding URI. */
protected static final String OVERRIDE_NAMESPACES = "http://cyberneko.org/html/features/override-namespaces";
/** Insert namespace binding URIs. */
protected static final String INSERT_NAMESPACES = "http://cyberneko.org/html/features/insert-namespaces";
/** Recognized features. */
private static final String[] RECOGNIZED_FEATURES = {
NAMESPACES,
OVERRIDE_NAMESPACES,
INSERT_NAMESPACES,
};
/** Feature defaults. */
private static final Boolean[] FEATURE_DEFAULTS = {
null,
Boolean.FALSE,
Boolean.FALSE,
};
// properties
/** Modify HTML element names: { "upper", "lower", "default" }. */
protected static final String NAMES_ELEMS = "http://cyberneko.org/html/properties/names/elems";
/** Modify HTML attribute names: { "upper", "lower", "default" }. */
protected static final String NAMES_ATTRS = "http://cyberneko.org/html/properties/names/attrs";
/** Namespaces URI. */
protected static final String NAMESPACES_URI = "http://cyberneko.org/html/properties/namespaces-uri";
/** Recognized properties. */
private static final String[] RECOGNIZED_PROPERTIES = new String[] {
NAMES_ELEMS,
NAMES_ATTRS,
NAMESPACES_URI,
};
/** Property defaults. */
private static final Object[] PROPERTY_DEFAULTS = {
null,
null,
XHTML_1_0_URI,
};
// modify HTML names
/** Don't modify HTML names. */
protected static final short NAMES_NO_CHANGE = 0;
/** Uppercase HTML names. */
protected static final short NAMES_UPPERCASE = 1;
/** Lowercase HTML names. */
protected static final short NAMES_LOWERCASE = 2;
//
// Data
//
// features
/** Namespaces. */
protected boolean fNamespaces;
/** Namespace prefixes. */
protected boolean fNamespacePrefixes;
/** Override namespaces. */
protected boolean fOverrideNamespaces;
/** Insert namespaces. */
protected boolean fInsertNamespaces;
// properties
/** Modify HTML element names. */
protected short fNamesElems;
/** Modify HTML attribute names. */
protected short fNamesAttrs;
/** Namespaces URI. */
protected String fNamespacesURI;
// state
/** Namespace context. */
protected final NamespaceSupport fNamespaceContext = new NamespaceSupport();
// temp vars
/** QName. */
private final QName fQName = new QName();
//
// HTMLComponent methods
//
/**
* Returns a list of feature identifiers that are recognized by
* this component. This method may return null if no features
* are recognized by this component.
*/
public String[] getRecognizedFeatures() {
return merge(super.getRecognizedFeatures(), RECOGNIZED_FEATURES);
} // getRecognizedFeatures():String[]
/**
* Returns the default state for a feature, or null if this
* component does not want to report a default value for this
* feature.
*/
public Boolean getFeatureDefault(String featureId) {
for (int i = 0; i < RECOGNIZED_FEATURES.length; i++) {
if (RECOGNIZED_FEATURES[i].equals(featureId)) {
return FEATURE_DEFAULTS[i];
}
}
return super.getFeatureDefault(featureId);
} // getFeatureDefault(String):Boolean
/**
* Returns a list of property identifiers that are recognized by
* this component. This method may return null if no properties
* are recognized by this component.
*/
public String[] getRecognizedProperties() {
return merge(super.getRecognizedProperties(), RECOGNIZED_PROPERTIES);
} // getRecognizedProperties():String[]
/**
* Returns the default value for a property, or null if this
* component does not want to report a default value for this
* property.
*/
public Object getPropertyDefault(String propertyId) {
for (int i = 0; i < RECOGNIZED_PROPERTIES.length; i++) {
if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) {
return PROPERTY_DEFAULTS[i];
}
}
return super.getPropertyDefault(propertyId);
} // getPropertyDefault(String):Object
/**
* Resets the component. The component can query the component manager
* about any features and properties that affect the operation of the
* component.
*
* @param manager The component manager.
*
* @throws XNIException Thrown by component on initialization error.
*/
public void reset(XMLComponentManager manager)
throws XMLConfigurationException {
super.reset(manager);
// features
fNamespaces = manager.getFeature(NAMESPACES);
fOverrideNamespaces = manager.getFeature(OVERRIDE_NAMESPACES);
fInsertNamespaces = manager.getFeature(INSERT_NAMESPACES);
// get properties
fNamesElems = getNamesValue(String.valueOf(manager.getProperty(NAMES_ELEMS)));
fNamesAttrs = getNamesValue(String.valueOf(manager.getProperty(NAMES_ATTRS)));
fNamespacesURI = String.valueOf(manager.getProperty(NAMESPACES_URI));
// initialize state
fNamespaceContext.reset();
} // reset(XMLComponentManager)
//
// XMLDocumentHandler methods
//
/** Start document. */
public void startDocument(XMLLocator locator, String encoding,
NamespaceContext nscontext, Augmentations augs)
throws XNIException {
// perform default handling
// NOTE: using own namespace context
super.startDocument(locator,encoding,fNamespaceContext,augs);
} // startDocument(XMLLocator,String,NamespaceContext,Augmentations)
/** Start element. */
public void startElement(QName element, XMLAttributes attrs,
Augmentations augs) throws XNIException {
// bind namespaces, if needed
if (fNamespaces) {
fNamespaceContext.pushContext();
bindNamespaces(element, attrs);
int dcount = fNamespaceContext.getDeclaredPrefixCount();
if (fDocumentHandler != null && dcount > 0) {
for (int i = 0; i < dcount; i++) {
String prefix = fNamespaceContext.getDeclaredPrefixAt(i);
String uri = fNamespaceContext.getURI(prefix);
XercesBridge.getInstance().XMLDocumentHandler_startPrefixMapping(fDocumentHandler, prefix, uri, augs);
}
}
}
// perform default handling
super.startElement(element, attrs, augs);
} // startElement(QName,XMLAttributes,Augmentations)
/** Empty element. */
public void emptyElement(QName element, XMLAttributes attrs,
Augmentations augs) throws XNIException {
// bind namespaces, if needed
if (fNamespaces) {
fNamespaceContext.pushContext();
bindNamespaces(element, attrs);
int dcount = fNamespaceContext.getDeclaredPrefixCount();
if (fDocumentHandler != null && dcount > 0) {
for (int i = 0; i < dcount; i++) {
String prefix = fNamespaceContext.getDeclaredPrefixAt(i);
String uri = fNamespaceContext.getURI(prefix);
XercesBridge.getInstance().XMLDocumentHandler_startPrefixMapping(fDocumentHandler, prefix, uri, augs);
}
}
}
// perform default handling
super.emptyElement(element, attrs, augs);
// pop context
if (fNamespaces) {
int dcount = fNamespaceContext.getDeclaredPrefixCount();
if (fDocumentHandler != null && dcount > 0) {
for (int i = dcount-1; i >= 0; i--) {
String prefix = fNamespaceContext.getDeclaredPrefixAt(i);
XercesBridge.getInstance().XMLDocumentHandler_endPrefixMapping(fDocumentHandler, prefix, augs);
}
}
fNamespaceContext.popContext();
}
} // startElement(QName,XMLAttributes,Augmentations)
/** End element. */
public void endElement(QName element, Augmentations augs)
throws XNIException {
// bind namespaces, if needed
if (fNamespaces) {
bindNamespaces(element, null);
}
// perform default handling
super.endElement(element, augs);
// pop context
if (fNamespaces) {
int dcount = fNamespaceContext.getDeclaredPrefixCount();
if (fDocumentHandler != null && dcount > 0) {
for (int i = dcount-1; i >= 0; i--) {
String prefix = fNamespaceContext.getDeclaredPrefixAt(i);
XercesBridge.getInstance().XMLDocumentHandler_endPrefixMapping(fDocumentHandler, prefix, augs);
}
}
fNamespaceContext.popContext();
}
} // endElement(QName,Augmentations)
//
// Protected static methods
//
/** Splits a qualified name. */
protected static void splitQName(QName qname) {
int index = qname.rawname.indexOf(':');
if (index != -1) {
qname.prefix = qname.rawname.substring(0,index);
qname.localpart = qname.rawname.substring(index+1);
}
} // splitQName(QName)
/**
* Converts HTML names string value to constant value.
*
* @see #NAMES_NO_CHANGE
* @see #NAMES_LOWERCASE
* @see #NAMES_UPPERCASE
*/
protected static final short getNamesValue(String value) {
if (value.equals("lower")) { return NAMES_LOWERCASE; }
if (value.equals("upper")) { return NAMES_UPPERCASE; }
return NAMES_NO_CHANGE;
} // getNamesValue(String):short
/** Modifies the given name based on the specified mode. */
protected static final String modifyName(String name, short mode) {
switch (mode) {
case NAMES_UPPERCASE: return name.toUpperCase();
case NAMES_LOWERCASE: return name.toLowerCase();
}
return name;
} // modifyName(String,short):String
//
// Protected methods
//
/** Binds namespaces. */
protected void bindNamespaces(QName element, XMLAttributes attrs) {
// split element qname
splitQName(element);
// declare namespace prefixes
int attrCount = attrs != null ? attrs.getLength() : 0;
for (int i = attrCount - 1; i >= 0; i--) {
attrs.getName(i, fQName);
String aname = fQName.rawname;
String ANAME = aname.toUpperCase();
if (ANAME.startsWith("XMLNS:") || ANAME.equals("XMLNS")) {
int anamelen = aname.length();
// get parts
String aprefix = anamelen > 5 ? aname.substring(0,5) : null;
String alocal = anamelen > 5 ? aname.substring(6) : aname;
String avalue = attrs.getValue(i);
// re-case parts and set them back into attributes
if (anamelen > 5) {
aprefix = modifyName(aprefix, NAMES_LOWERCASE);
alocal = modifyName(alocal, fNamesElems);
aname = aprefix + ':' + alocal;
}
else {
alocal = modifyName(alocal, NAMES_LOWERCASE);
aname = alocal;
}
fQName.setValues(aprefix, alocal, aname, null);
attrs.setName(i, fQName);
// declare prefix
String prefix = alocal != aname ? alocal : "";
String uri = avalue.length() > 0 ? avalue : null;
if (fOverrideNamespaces &&
prefix.equals(element.prefix) &&
HTMLElements.getElement(element.localpart, null) != null) {
uri = fNamespacesURI;
}
fNamespaceContext.declarePrefix(prefix, uri);
}
}
// bind element
String prefix = element.prefix != null ? element.prefix : "";
element.uri = fNamespaceContext.getURI(prefix);
// REVISIT: The prefix of a qualified element name that is
// bound to a namespace is passed (as recent as
// Xerces 2.4.0) as "" for start elements and null
// for end elements. Why? One of them is a bug,
// clearly. -Ac
if (element.uri != null && element.prefix == null) {
element.prefix = "";
}
// do we need to insert namespace bindings?
if (fInsertNamespaces && attrs != null &&
HTMLElements.getElement(element.localpart,null) != null) {
if (element.prefix == null ||
fNamespaceContext.getURI(element.prefix) == null) {
String xmlns = "xmlns" + ((element.prefix != null)
? ":"+element.prefix : "");
fQName.setValues(null, xmlns, xmlns, null);
attrs.addAttribute(fQName, "CDATA", fNamespacesURI);
bindNamespaces(element, attrs);
return;
}
}
// bind attributes
attrCount = attrs != null ? attrs.getLength() : 0;
for (int i = 0; i < attrCount; i++) {
attrs.getName(i, fQName);
splitQName(fQName);
prefix = !fQName.rawname.equals("xmlns")
? (fQName.prefix != null ? fQName.prefix : "") : "xmlns";
// PATCH: Joseph Walton
if (!prefix.equals("")) {
fQName.uri = prefix.equals("xml") ? XML_URI : fNamespaceContext.getURI(prefix);
}
// NOTE: You would think the xmlns namespace would be handled
// by NamespaceSupport but it's not. -Ac
if (prefix.equals("xmlns") && fQName.uri == null) {
fQName.uri = XMLNS_URI;
}
attrs.setName(i, fQName);
}
} // bindNamespaces(QName,XMLAttributes)
//
// Classes
//
/**
* This namespace context object implements the old and new XNI
* <code>NamespaceContext</code> interface methods so that it can
* be used across all versions of Xerces2.
*/
public static class NamespaceSupport
implements NamespaceContext {
//
// Data
//
/** Top of the levels list. */
protected int fTop = 0;
/** The levels of the entries. */
protected int[] fLevels = new int[10];
/** The entries. */
protected Entry[] fEntries = new Entry[10];
//
// Constructors
//
/** Default constructor. */
public NamespaceSupport() {
pushContext();
declarePrefix("xml", NamespaceContext.XML_URI);
declarePrefix("xmlns", NamespaceContext.XMLNS_URI);
} // <init>()
//
// NamespaceContext methods
//
// since Xerces 2.0.0-beta2 (old XNI namespaces)
/** Get URI. */
public String getURI(String prefix) {
for (int i = fLevels[fTop]-1; i >= 0; i--) {
Entry entry = (Entry)fEntries[i];
if (entry.prefix.equals(prefix)) {
return entry.uri;
}
}
return null;
} // getURI(String):String
/** Get declared prefix count. */
public int getDeclaredPrefixCount() {
return fLevels[fTop] - fLevels[fTop-1];
} // getDeclaredPrefixCount():int
/** Get declared prefix at. */
public String getDeclaredPrefixAt(int index) {
return fEntries[fLevels[fTop-1] + index].prefix;
} // getDeclaredPrefixAt(int):String
/** Get parent context. */
public NamespaceContext getParentContext() {
return this;
} // getParentContext():NamespaceContext
// since Xerces #.#.# (new XNI namespaces)
/** Reset. */
public void reset() {
fLevels[fTop = 1] = fLevels[fTop-1];
} // reset()
/** Push context. */
public void pushContext() {
if (++fTop == fLevels.length) {
int[] iarray = new int[fLevels.length + 10];
System.arraycopy(fLevels, 0, iarray, 0, fLevels.length);
fLevels = iarray;
}
fLevels[fTop] = fLevels[fTop-1];
} // pushContext()
/** Pop context. */
public void popContext() {
if (fTop > 1) {
fTop--;
}
} // popContext()
/** Declare prefix. */
public boolean declarePrefix(String prefix, String uri) {
int count = getDeclaredPrefixCount();
for (int i = 0; i < count; i++) {
String dprefix = getDeclaredPrefixAt(i);
if (dprefix.equals(prefix)) {
return false;
}
}
Entry entry = new Entry(prefix, uri);
if (fLevels[fTop] == fEntries.length) {
Entry[] earray = new Entry[fEntries.length + 10];
System.arraycopy(fEntries, 0, earray, 0, fEntries.length);
fEntries = earray;
}
fEntries[fLevels[fTop]++] = entry;
return true;
} // declarePrefix(String,String):boolean
/** Get prefix. */
public String getPrefix(String uri) {
for (int i = fLevels[fTop]-1; i >= 0; i--) {
Entry entry = (Entry)fEntries[i];
if (entry.uri.equals(uri)) {
return entry.prefix;
}
}
return null;
} // getPrefix(String):String
/** Get all prefixes. */
public Enumeration getAllPrefixes() {
Vector prefixes = new Vector();
for (int i = fLevels[1]; i < fLevels[fTop]; i++) {
String prefix = fEntries[i].prefix;
if (!prefixes.contains(prefix)) {
prefixes.addElement(prefix);
}
}
return prefixes.elements();
} // getAllPrefixes():Enumeration
//
// Classes
//
/** A namespace binding entry. */
static class Entry {
//
// Data
//
/** Prefix. */
public String prefix;
/** URI. */
public String uri;
//
// Constructors
//
/** Constructs an entry. */
public Entry(String prefix, String uri) {
this.prefix = prefix;
this.uri = uri;
} // <init>(String,String)
} // class Entry
} // class NamespaceSupport
} // class NamespaceBinder
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/filters/NamespaceBinder.java | Java | art | 21,326 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html.filters;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.apache.xerces.xni.parser.XMLParserConfiguration;
import org.cyberneko.html.HTMLConfiguration;
import org.cyberneko.html.HTMLElements;
import org.cyberneko.html.HTMLEntities;
/**
* An HTML writer written as a filter. Besides serializing the HTML
* event stream, the writer also passes the document events to the next
* stage in the pipeline. This allows applications to insert writer
* filters between other custom filters for debugging purposes.
* <p>
* Since an HTML document may have specified its encoding using the
* <META> tag and http-equiv/content attributes, the writer will
* automatically change any character set specified in this tag to
* match the encoding of the output stream. Therefore, the character
* encoding name used to construct the writer should be an official
* <a href='http://www.iana.org/assignments/character-sets'>IANA</a>
* encoding name and not a Java encoding name.
* <p>
* <strong>Note:</strong>
* The modified character set in the <META> tag is <em>not</em>
* propagated to the next stage in the pipeline. The changed value is
* only output to the stream; the original value is sent to the next
* stage in the pipeline.
*
* @author Andy Clark
*
* @version $Id: Writer.java,v 1.7 2005/02/14 04:01:33 andyc Exp $
*/
public class Writer
extends DefaultFilter {
//
// Constants
//
/** Notify character entity references. */
public static final String NOTIFY_CHAR_REFS = "http://apache.org/xml/features/scanner/notify-char-refs";
/** Notify built-in entity references. */
public static final String NOTIFY_HTML_BUILTIN_REFS = "http://cyberneko.org/html/features/scanner/notify-builtin-refs";
/** Augmentations feature identifier. */
protected static final String AUGMENTATIONS = "http://cyberneko.org/html/features/augmentations";
/** Filters property identifier. */
protected static final String FILTERS = "http://cyberneko.org/html/properties/filters";
//
// Data
//
/** The encoding. */
protected String fEncoding;
/**
* The print writer used for serializing the document with the
* appropriate character encoding.
*/
protected PrintWriter fPrinter;
// state
/** Seen root element. */
protected boolean fSeenRootElement;
/** Seen http-equiv directive. */
protected boolean fSeenHttpEquiv;
/** Element depth. */
protected int fElementDepth;
/** Normalize character content. */
protected boolean fNormalize;
/** Print characters. */
protected boolean fPrintChars;
//
// Constructors
//
/** Constructs a writer filter that prints to standard out. */
public Writer() {
// Note: UTF-8 should *always* be a supported encoding. Although,
// I've heard of the old M$ JVM not supporting it! Amazing. -Ac
try {
fEncoding = "UTF-8";
fPrinter = new PrintWriter(new OutputStreamWriter(System.out, fEncoding));
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage());
}
} // <init>()
/**
* Constructs a writer filter using the specified output stream and
* encoding.
*
* @param outputStream The output stream to write to.
* @param encoding The encoding to be used for the output. The encoding name
* should be an official IANA encoding name.
*/
public Writer(OutputStream outputStream, String encoding)
throws UnsupportedEncodingException {
this(new OutputStreamWriter(outputStream, encoding), encoding);
} // <init>(OutputStream,String)
/**
* Constructs a writer filter using the specified Java writer and
* encoding.
*
* @param writer The Java writer to write to.
* @param encoding The encoding to be used for the output. The encoding name
* should be an official IANA encoding name.
*/
public Writer(java.io.Writer writer, String encoding) {
fEncoding = encoding;
if (writer instanceof PrintWriter) {
fPrinter = (PrintWriter)writer;
}
else {
fPrinter = new PrintWriter(writer);
}
} // <init>(java.io.Writer,String)
//
// XMLDocumentHandler methods
//
// since Xerces-J 2.2.0
/** Start document. */
public void startDocument(XMLLocator locator, String encoding,
NamespaceContext nscontext, Augmentations augs)
throws XNIException {
fSeenRootElement = false;
fSeenHttpEquiv = false;
fElementDepth = 0;
fNormalize = true;
fPrintChars = true;
super.startDocument(locator, encoding, nscontext, augs);
} // startDocument(XMLLocator,String,NamespaceContext,Augmentations)
// old methods
/** Start document. */
public void startDocument(XMLLocator locator, String encoding, Augmentations augs)
throws XNIException {
startDocument(locator, encoding, null, augs);
} // startDocument(XMLLocator,String,Augmentations)
/** Comment. */
public void comment(XMLString text, Augmentations augs)
throws XNIException {
if (fSeenRootElement && fElementDepth <= 0) {
fPrinter.println();
}
fPrinter.print("<!--");
printCharacters(text, false);
fPrinter.print("-->");
if (!fSeenRootElement) {
fPrinter.println();
}
fPrinter.flush();
} // comment(XMLString,Augmentations)
/** Start element. */
public void startElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
fSeenRootElement = true;
fElementDepth++;
fNormalize = !HTMLElements.getElement(element.rawname).isSpecial();
printStartElement(element, attributes);
super.startElement(element, attributes, augs);
} // startElement(QName,XMLAttributes,Augmentations)
/** Empty element. */
public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs)
throws XNIException {
fSeenRootElement = true;
printStartElement(element, attributes);
super.emptyElement(element, attributes, augs);
} // emptyElement(QName,XMLAttributes,Augmentations)
/** Characters. */
public void characters(XMLString text, Augmentations augs)
throws XNIException {
if (fPrintChars) {
printCharacters(text, fNormalize);
}
super.characters(text, augs);
} // characters(XMLString,Augmentations)
/** End element. */
public void endElement(QName element, Augmentations augs)
throws XNIException {
fElementDepth--;
fNormalize = true;
/***
// NOTE: Not sure if this is what should be done in the case where
// the encoding is not explitly declared within the HEAD. So
// I'm leaving it commented out for now. -Ac
if (element.rawname.equalsIgnoreCase("head") && !fSeenHttpEquiv) {
boolean capitalize = Character.isUpperCase(element.rawname.charAt(0));
String ename = capitalize ? "META" : "meta";
QName qname = new QName(null, ename, ename, null);
XMLAttributes attrs = new XMLAttributesImpl();
QName aname = new QName(null, "http-equiv", "http-equiv", null);
attrs.addAttribute(aname, "CDATA", "Content-Type");
aname.setValues(null, "content", "content", null);
attrs.addAttribute(aname, "CDATA", "text/html; charset="+fEncoding);
super.emptyElement(qname, attrs, null);
}
/***/
printEndElement(element);
super.endElement(element, augs);
} // endElement(QName,Augmentations)
/** Start general entity. */
public void startGeneralEntity(String name, XMLResourceIdentifier id, String encoding, Augmentations augs)
throws XNIException {
fPrintChars = false;
if (name.startsWith("#")) {
try {
boolean hex = name.startsWith("#x");
int offset = hex ? 2 : 1;
int base = hex ? 16 : 10;
int value = Integer.parseInt(name.substring(offset), base);
String entity = HTMLEntities.get(value);
if (entity != null) {
name = entity;
}
}
catch (NumberFormatException e) {
// ignore
}
}
printEntity(name);
super.startGeneralEntity(name, id, encoding, augs);
} // startGeneralEntity(String,XMLResourceIdentifier,String,Augmentations)
/** End general entity. */
public void endGeneralEntity(String name, Augmentations augs)
throws XNIException {
fPrintChars = true;
super.endGeneralEntity(name, augs);
} // endGeneralEntity(String,Augmentations)
//
// Protected methods
//
/** Print attribute value. */
protected void printAttributeValue(String text) {
int length = text.length();
for (int j = 0; j < length; j++) {
char c = text.charAt(j);
if (c == '"') {
fPrinter.print(""");
}
else {
fPrinter.print(c);
}
}
fPrinter.flush();
} // printAttributeValue(String)
/** Print characters. */
protected void printCharacters(XMLString text, boolean normalize) {
if (normalize) {
for (int i = 0; i < text.length; i++) {
char c = text.ch[text.offset + i];
if (c != '\n') {
String entity = HTMLEntities.get(c);
if (entity != null) {
printEntity(entity);
}
else {
fPrinter.print(c);
}
}
else {
fPrinter.println();
}
}
}
else {
for (int i = 0; i < text.length; i++) {
char c = text.ch[text.offset + i];
fPrinter.print(c);
}
}
fPrinter.flush();
} // printCharacters(XMLString,boolean)
/** Print start element. */
protected void printStartElement(QName element, XMLAttributes attributes) {
// modify META[@http-equiv='content-type']/@content value
int contentIndex = -1;
String originalContent = null;
if (element.rawname.toLowerCase().equals("meta")) {
String httpEquiv = null;
int length = attributes.getLength();
for (int i = 0; i < length; i++) {
String aname = attributes.getQName(i).toLowerCase();
if (aname.equals("http-equiv")) {
httpEquiv = attributes.getValue(i);
}
else if (aname.equals("content")) {
contentIndex = i;
}
}
if (httpEquiv != null && httpEquiv.toLowerCase().equals("content-type")) {
fSeenHttpEquiv = true;
String content = null;
if (contentIndex != -1) {
originalContent = attributes.getValue(contentIndex);
content = originalContent.toLowerCase();
}
if (content != null) {
int charsetIndex = content.indexOf("charset=");
if (charsetIndex != -1) {
content = content.substring(0, charsetIndex + 8);
}
else {
content += ";charset=";
}
content += fEncoding;
attributes.setValue(contentIndex, content);
}
}
}
// print element
fPrinter.print('<');
fPrinter.print(element.rawname);
int attrCount = attributes != null ? attributes.getLength() : 0;
for (int i = 0; i < attrCount; i++) {
String aname = attributes.getQName(i);
String avalue = attributes.getValue(i);
fPrinter.print(' ');
fPrinter.print(aname);
fPrinter.print("=\"");
printAttributeValue(avalue);
fPrinter.print('"');
}
fPrinter.print('>');
fPrinter.flush();
// return original META[@http-equiv]/@content value
if (contentIndex != -1 && originalContent != null) {
attributes.setValue(contentIndex, originalContent);
}
} // printStartElement(QName,XMLAttributes)
/** Print end element. */
protected void printEndElement(QName element) {
fPrinter.print("</");
fPrinter.print(element.rawname);
fPrinter.print('>');
fPrinter.flush();
} // printEndElement(QName)
/** Print entity. */
protected void printEntity(String name) {
fPrinter.print('&');
fPrinter.print(name);
fPrinter.print(';');
fPrinter.flush();
} // printEntity(String)
//
// MAIN
//
/** Main. */
public static void main(String[] argv) throws Exception {
if (argv.length == 0) {
printUsage();
System.exit(1);
}
XMLParserConfiguration parser = new HTMLConfiguration();
parser.setFeature(NOTIFY_CHAR_REFS, true);
parser.setFeature(NOTIFY_HTML_BUILTIN_REFS, true);
String iencoding = null;
String oencoding = "Windows-1252";
boolean identity = false;
boolean purify = false;
for (int i = 0; i < argv.length; i++) {
String arg = argv[i];
if (arg.equals("-ie")) {
iencoding = argv[++i];
continue;
}
if (arg.equals("-e") || arg.equals("-oe")) {
oencoding = argv[++i];
continue;
}
if (arg.equals("-i")) {
identity = true;
continue;
}
if (arg.equals("-p")) {
purify = true;
continue;
}
if (arg.equals("-h")) {
printUsage();
System.exit(1);
}
java.util.Vector filtersVector = new java.util.Vector(2);
if (identity) {
filtersVector.addElement(new Identity());
}
else if (purify) {
filtersVector.addElement(new Purifier());
}
filtersVector.addElement(new Writer(System.out, oencoding));
XMLDocumentFilter[] filters =
new XMLDocumentFilter[filtersVector.size()];
filtersVector.copyInto(filters);
parser.setProperty(FILTERS, filters);
XMLInputSource source = new XMLInputSource(null, arg, null);
source.setEncoding(iencoding);
parser.parse(source);
}
} // main(String[])
/** Print usage. */
private static void printUsage() {
System.err.println("usage: java "+Writer.class.getName()+" (options) file ...");
System.err.println();
System.err.println("options:");
System.err.println(" -ie name Specify IANA name of input encoding.");
System.err.println(" -oe name Specify IANA name of output encoding.");
System.err.println(" -i Perform identity transform.");
System.err.println(" -p Purify output to ensure XML well-formedness.");
System.err.println(" -h Display help screen.");
System.err.println();
System.err.println("notes:");
System.err.println(" The -i and -p options are mutually exclusive.");
System.err.println(" The -e option has been replaced with -oe.");
} // printUsage()
} // class Writer
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/filters/Writer.java | Java | art | 17,260 |
/*
* Copyright 2004-2008 Andy Clark
*
* Licensed 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.
*/
package org.cyberneko.html.filters;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.util.XMLStringBuffer;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.cyberneko.html.HTMLAugmentations;
import org.cyberneko.html.HTMLEventInfo;
import org.cyberneko.html.xercesbridge.XercesBridge;
/**
* This filter purifies the HTML input to ensure XML well-formedness.
* The purification process includes:
* <ul>
* <li>fixing illegal characters in the document, including
* <ul>
* <li>element and attribute names,
* <li>processing instruction target and data,
* <li>document text;
* </ul>
* <li>ensuring the string "--" does not appear in the content of
* a comment;
* <li>ensuring the string "]]>" does not appear in the content of
* a CDATA section;
* <li>ensuring that the XML declaration has required pseudo-attributes
* and that the values are correct;
* and
* <li>synthesized missing namespace bindings.
* </ul>
* <p>
* Illegal characters in XML names are converted to the character
* sequence "_u####_" where "####" is the value of the Unicode
* character represented in hexadecimal. Whereas illegal characters
* appearing in document content is converted to the character
* sequence "\\u####".
* <p>
* In comments, the character '-' is replaced by the character
* sequence "- " to prevent "--" from ever appearing in the comment
* content. For CDATA sections, the character ']' is replaced by
* the character sequence "] " to prevent "]]" from appearing.
* <p>
* The URI used for synthesized namespace bindings is
* "http://cyberneko.org/html/ns/synthesized/<i>number</i>" where
* <i>number</i> is generated to ensure uniqueness.
*
* @author Andy Clark
*
* @version $Id: Purifier.java,v 1.5 2005/02/14 03:56:54 andyc Exp $
*/
public class Purifier
extends DefaultFilter {
//
// Constants
//
/** Synthesized namespace binding prefix. */
public static final String SYNTHESIZED_NAMESPACE_PREFX =
"http://cyberneko.org/html/ns/synthesized/";
/** Namespaces. */
protected static final String NAMESPACES = "http://xml.org/sax/features/namespaces";
/** Include infoset augmentations. */
protected static final String AUGMENTATIONS = "http://cyberneko.org/html/features/augmentations";
/** Recognized features. */
private static final String[] RECOGNIZED_FEATURES = {
NAMESPACES,
AUGMENTATIONS,
};
// static vars
/** Synthesized event info item. */
protected static final HTMLEventInfo SYNTHESIZED_ITEM =
new HTMLEventInfo.SynthesizedItem();
//
// Data
//
// features
/** Namespaces. */
protected boolean fNamespaces;
/** Augmentations. */
protected boolean fAugmentations;
// state
/** True if the doctype declaration was seen. */
protected boolean fSeenDoctype;
/** True if root element was seen. */
protected boolean fSeenRootElement;
/** True if inside a CDATA section. */
protected boolean fInCDATASection;
// doctype declaration info
/** Public identifier of doctype declaration. */
protected String fPublicId;
/** System identifier of doctype declaration. */
protected String fSystemId;
// namespace info
/** Namespace information. */
protected NamespaceContext fNamespaceContext;
/** Synthesized namespace binding count. */
protected int fSynthesizedNamespaceCount;
// temp vars
/** Qualified name. */
private QName fQName = new QName();
/** Augmentations. */
private final HTMLAugmentations fInfosetAugs = new HTMLAugmentations();
/** String buffer. */
private final XMLStringBuffer fStringBuffer = new XMLStringBuffer();
//
// XMLComponent methods
//
public void reset(XMLComponentManager manager)
throws XMLConfigurationException {
// state
fInCDATASection = false;
// features
fNamespaces = manager.getFeature(NAMESPACES);
fAugmentations = manager.getFeature(AUGMENTATIONS);
} // reset(XMLComponentManager)
//
// XMLDocumentHandler methods
//
/** Start document. */
public void startDocument(XMLLocator locator, String encoding,
Augmentations augs) throws XNIException {
fNamespaceContext = fNamespaces
? new NamespaceBinder.NamespaceSupport() : null;
fSynthesizedNamespaceCount = 0;
handleStartDocument();
super.startDocument(locator, encoding, augs);
} // startDocument(XMLLocator,String,Augmentations)
/** Start document. */
public void startDocument(XMLLocator locator, String encoding,
NamespaceContext nscontext, Augmentations augs)
throws XNIException {
fNamespaceContext = nscontext;
fSynthesizedNamespaceCount = 0;
handleStartDocument();
super.startDocument(locator, encoding, nscontext, augs);
} // startDocument(XMLLocator,NamespaceContext,String,Augmentations)
/** XML declaration. */
public void xmlDecl(String version, String encoding, String standalone,
Augmentations augs) throws XNIException {
if (version == null || !version.equals("1.0")) {
version = "1.0";
}
if (encoding != null && encoding.length() == 0) {
encoding = null;
}
if (standalone != null) {
if (!standalone.equalsIgnoreCase("true") &&
!standalone.equalsIgnoreCase("false")) {
standalone = null;
}
else {
standalone = standalone.toLowerCase();
}
}
super.xmlDecl(version,encoding,standalone,augs);
} // xmlDecl(String,String,String,Augmentations)
/** Comment. */
public void comment(XMLString text, Augmentations augs)
throws XNIException {
StringBuffer str = new StringBuffer(purifyText(text).toString());
int length = str.length();
for (int i = length-1; i >= 0; i--) {
char c = str.charAt(i);
if (c == '-') {
str.insert(i + 1, ' ');
}
}
fStringBuffer.length = 0;
fStringBuffer.append(str.toString());
text = fStringBuffer;
super.comment(text, augs);
} // comment(XMLString,Augmentations)
/** Processing instruction. */
public void processingInstruction(String target, XMLString data,
Augmentations augs)
throws XNIException {
target = purifyName(target, true);
data = purifyText(data);
super.processingInstruction(target, data, augs);
} // processingInstruction(String,XMLString,Augmentations)
/** Doctype declaration. */
public void doctypeDecl(String root, String pubid, String sysid,
Augmentations augs) throws XNIException {
fSeenDoctype = true;
// NOTE: It doesn't matter what the root element name is because
// it must match the root element. -Ac
fPublicId = pubid;
fSystemId = sysid;
// NOTE: If the public identifier is specified, then a system
// identifier must also be specified. -Ac
if (fPublicId != null && fSystemId == null) {
fSystemId = "";
}
// NOTE: Can't save the augmentations because the object state
// is transient. -Ac
} // doctypeDecl(String,String,String,Augmentations)
/** Start element. */
public void startElement(QName element, XMLAttributes attrs,
Augmentations augs) throws XNIException {
handleStartElement(element, attrs);
super.startElement(element, attrs, augs);
} // startElement(QName,XMLAttributes,Augmentations)
/** Empty element. */
public void emptyElement(QName element, XMLAttributes attrs,
Augmentations augs) throws XNIException {
handleStartElement(element, attrs);
super.emptyElement(element, attrs, augs);
} // emptyElement(QName,XMLAttributes,Augmentations)
/** Start CDATA section. */
public void startCDATA(Augmentations augs) throws XNIException {
fInCDATASection = true;
super.startCDATA(augs);
} // startCDATA(Augmentations)
/** End CDATA section. */
public void endCDATA(Augmentations augs) throws XNIException {
fInCDATASection = false;
super.endCDATA(augs);
} // endCDATA(Augmentations)
/** Characters. */
public void characters(XMLString text, Augmentations augs)
throws XNIException {
text = purifyText(text);
if (fInCDATASection) {
StringBuffer str = new StringBuffer(text.toString());
int length = str.length();
for (int i = length-1; i >= 0; i--) {
char c = str.charAt(i);
if (c == ']') {
str.insert(i + 1, ' ');
}
}
fStringBuffer.length = 0;
fStringBuffer.append(str.toString());
text = fStringBuffer;
}
super.characters(text,augs);
} // characters(XMLString,Augmentations)
/** End element. */
public void endElement(QName element, Augmentations augs)
throws XNIException {
element = purifyQName(element);
if (fNamespaces) {
if (element.prefix != null && element.uri == null) {
element.uri = fNamespaceContext.getURI(element.prefix);
}
}
super.endElement(element, augs);
} // endElement(QName,Augmentations)
//
// Protected methods
//
/** Handle start document. */
protected void handleStartDocument() {
fSeenDoctype = false;
fSeenRootElement = false;
} // handleStartDocument()
/** Handle start element. */
protected void handleStartElement(QName element, XMLAttributes attrs) {
// handle element and attributes
element = purifyQName(element);
int attrCount = attrs != null ? attrs.getLength() : 0;
for (int i = attrCount-1; i >= 0; i--) {
// purify attribute name
attrs.getName(i, fQName);
attrs.setName(i, purifyQName(fQName));
// synthesize namespace bindings
if (fNamespaces) {
if (!fQName.rawname.equals("xmlns") &&
!fQName.rawname.startsWith("xmlns:")) {
// NOTE: Must get attribute name again because the
// purifyQName method does not guarantee that
// the same QName object is returned. -Ac
attrs.getName(i, fQName);
if (fQName.prefix != null && fQName.uri == null) {
synthesizeBinding(attrs, fQName.prefix);
}
}
}
}
// synthesize namespace bindings
if (fNamespaces) {
if (element.prefix != null && element.uri == null) {
synthesizeBinding(attrs, element.prefix);
}
}
// synthesize doctype declaration
if (!fSeenRootElement && fSeenDoctype) {
Augmentations augs = synthesizedAugs();
super.doctypeDecl(element.rawname, fPublicId, fSystemId, augs);
}
// mark start element as seen
fSeenRootElement = true;
} // handleStartElement(QName,XMLAttributes)
/** Synthesize namespace binding. */
protected void synthesizeBinding(XMLAttributes attrs, String ns) {
String prefix = "xmlns";
String localpart = ns;
String qname = prefix+':'+localpart;
String uri = NamespaceBinder.NAMESPACES_URI;
String atype = "CDATA";
String avalue = SYNTHESIZED_NAMESPACE_PREFX+fSynthesizedNamespaceCount++;
// add attribute
fQName.setValues(prefix, localpart, qname, uri);
attrs.addAttribute(fQName, atype, avalue);
// bind namespace
XercesBridge.getInstance().NamespaceContext_declarePrefix(fNamespaceContext, ns, avalue);
} // synthesizeBinding(XMLAttributes,String)
/** Returns an augmentations object with a synthesized item added. */
protected final Augmentations synthesizedAugs() {
HTMLAugmentations augs = null;
if (fAugmentations) {
augs = fInfosetAugs;
augs.removeAllItems();
augs.putItem(AUGMENTATIONS, SYNTHESIZED_ITEM);
}
return augs;
} // synthesizedAugs():Augmentations
//
// Protected methods
//
/** Purify qualified name. */
protected QName purifyQName(QName qname) {
qname.prefix = purifyName(qname.prefix, true);
qname.localpart = purifyName(qname.localpart, true);
qname.rawname = purifyName(qname.rawname, false);
return qname;
} // purifyQName(QName):QName
/** Purify name. */
protected String purifyName(String name, boolean localpart) {
if (name == null) {
return name;
}
StringBuffer str = new StringBuffer();
int length = name.length();
boolean seenColon = localpart;
for (int i = 0; i < length; i++) {
char c = name.charAt(i);
if (i == 0) {
if (!XMLChar.isNameStart(c)) {
str.append("_u"+toHexString(c,4)+"_");
}
else {
str.append(c);
}
}
else {
if ((fNamespaces && c == ':' && seenColon) || !XMLChar.isName(c)) {
str.append("_u"+toHexString(c,4)+"_");
}
else {
str.append(c);
}
seenColon = seenColon || c == ':';
}
}
return str.toString();
} // purifyName(String):String
/** Purify content. */
protected XMLString purifyText(XMLString text) {
fStringBuffer.length = 0;
for (int i = 0; i < text.length; i++) {
char c = text.ch[text.offset+i];
if (XMLChar.isInvalid(c)) {
fStringBuffer.append("\\u"+toHexString(c,4));
}
else {
fStringBuffer.append(c);
}
}
return fStringBuffer;
} // purifyText(XMLString):XMLString
//
// Protected static methods
//
/** Returns a padded hexadecimal string for the given value. */
protected static String toHexString(int c, int padlen) {
StringBuffer str = new StringBuffer(padlen);
str.append(Integer.toHexString(c));
int len = padlen - str.length();
for (int i = 0; i < len; i++) {
str.insert(0, '0');
}
return str.toString().toUpperCase();
} // toHexString(int,int):String
} // class Purifier
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/filters/Purifier.java | Java | art | 15,987 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html;
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.BitSet;
import java.util.Stack;
import org.apache.xerces.util.EncodingMap;
import org.apache.xerces.util.NamespaceSupport;
import org.apache.xerces.util.URI;
import org.apache.xerces.util.XMLAttributesImpl;
import org.apache.xerces.util.XMLResourceIdentifierImpl;
import org.apache.xerces.util.XMLStringBuffer;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLDocumentScanner;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.cyberneko.html.xercesbridge.XercesBridge;
/**
* A simple HTML scanner. This scanner makes no attempt to balance tags
* or fix other problems in the source document — it just scans what
* it can and generates XNI document "events", ignoring errors of all
* kinds.
* <p>
* This component recognizes the following features:
* <ul>
* <li>http://cyberneko.org/html/features/augmentations
* <li>http://cyberneko.org/html/features/report-errors
* <li>http://apache.org/xml/features/scanner/notify-char-refs
* <li>http://apache.org/xml/features/scanner/notify-builtin-refs
* <li>http://cyberneko.org/html/features/scanner/notify-builtin-refs
* <li>http://cyberneko.org/html/features/scanner/fix-mswindows-refs
* <li>http://cyberneko.org/html/features/scanner/script/strip-cdata-delims
* <li>http://cyberneko.org/html/features/scanner/script/strip-comment-delims
* <li>http://cyberneko.org/html/features/scanner/style/strip-cdata-delims
* <li>http://cyberneko.org/html/features/scanner/style/strip-comment-delims
* <li>http://cyberneko.org/html/features/scanner/ignore-specified-charset
* <li>http://cyberneko.org/html/features/scanner/cdata-sections
* <li>http://cyberneko.org/html/features/override-doctype
* <li>http://cyberneko.org/html/features/insert-doctype
* <li>http://cyberneko.org/html/features/parse-noscript-content
* </ul>
* <p>
* This component recognizes the following properties:
* <ul>
* <li>http://cyberneko.org/html/properties/names/elems
* <li>http://cyberneko.org/html/properties/names/attrs
* <li>http://cyberneko.org/html/properties/default-encoding
* <li>http://cyberneko.org/html/properties/error-reporter
* <li>http://cyberneko.org/html/properties/doctype/pubid
* <li>http://cyberneko.org/html/properties/doctype/sysid
* </ul>
*
* @see HTMLElements
* @see HTMLEntities
*
* @author Andy Clark
* @author Marc Guillemot
* @author Ahmed Ashour
*
* @version $Id: HTMLScanner.java,v 1.19 2005/06/14 05:52:37 andyc Exp $
*/
public class HTMLScanner
implements XMLDocumentScanner, XMLLocator, HTMLComponent {
//
// Constants
//
// doctype info: HTML 4.01 strict
/** HTML 4.01 strict public identifier ("-//W3C//DTD HTML 4.01//EN"). */
public static final String HTML_4_01_STRICT_PUBID = "-//W3C//DTD HTML 4.01//EN";
/** HTML 4.01 strict system identifier ("http://www.w3.org/TR/html4/strict.dtd"). */
public static final String HTML_4_01_STRICT_SYSID = "http://www.w3.org/TR/html4/strict.dtd";
// doctype info: HTML 4.01 loose
/** HTML 4.01 transitional public identifier ("-//W3C//DTD HTML 4.01 Transitional//EN"). */
public static final String HTML_4_01_TRANSITIONAL_PUBID = "-//W3C//DTD HTML 4.01 Transitional//EN";
/** HTML 4.01 transitional system identifier ("http://www.w3.org/TR/html4/loose.dtd"). */
public static final String HTML_4_01_TRANSITIONAL_SYSID = "http://www.w3.org/TR/html4/loose.dtd";
// doctype info: HTML 4.01 frameset
/** HTML 4.01 frameset public identifier ("-//W3C//DTD HTML 4.01 Frameset//EN"). */
public static final String HTML_4_01_FRAMESET_PUBID = "-//W3C//DTD HTML 4.01 Frameset//EN";
/** HTML 4.01 frameset system identifier ("http://www.w3.org/TR/html4/frameset.dtd"). */
public static final String HTML_4_01_FRAMESET_SYSID = "http://www.w3.org/TR/html4/frameset.dtd";
// features
/** Include infoset augmentations. */
protected static final String AUGMENTATIONS = "http://cyberneko.org/html/features/augmentations";
/** Report errors. */
protected static final String REPORT_ERRORS = "http://cyberneko.org/html/features/report-errors";
/** Notify character entity references (e.g. &#32;, &#x20;, etc). */
public static final String NOTIFY_CHAR_REFS = "http://apache.org/xml/features/scanner/notify-char-refs";
/**
* Notify handler of built-in entity references (e.g. &amp;,
* &lt;, etc).
* <p>
* <strong>Note:</strong>
* This only applies to the five pre-defined XML general entities.
* Specifically, "amp", "lt", "gt", "quot", and "apos". This is done
* for compatibility with the Xerces feature.
* <p>
* To be notified of the built-in entity references in HTML, set the
* <code>http://cyberneko.org/html/features/scanner/notify-builtin-refs</code>
* feature to <code>true</code>.
*/
public static final String NOTIFY_XML_BUILTIN_REFS = "http://apache.org/xml/features/scanner/notify-builtin-refs";
/**
* Notify handler of built-in entity references (e.g. &nobr;,
* &copy;, etc).
* <p>
* <strong>Note:</strong>
* This <em>includes</em> the five pre-defined XML general entities.
*/
public static final String NOTIFY_HTML_BUILTIN_REFS = "http://cyberneko.org/html/features/scanner/notify-builtin-refs";
/** Fix Microsoft Windows® character entity references. */
public static final String FIX_MSWINDOWS_REFS = "http://cyberneko.org/html/features/scanner/fix-mswindows-refs";
/**
* Strip HTML comment delimiters ("<!−−" and
* "−−>") from SCRIPT tag contents.
*/
public static final String SCRIPT_STRIP_COMMENT_DELIMS = "http://cyberneko.org/html/features/scanner/script/strip-comment-delims";
/**
* Strip XHTML CDATA delimiters ("<![CDATA[" and "]]>") from
* SCRIPT tag contents.
*/
public static final String SCRIPT_STRIP_CDATA_DELIMS = "http://cyberneko.org/html/features/scanner/script/strip-cdata-delims";
/**
* Strip HTML comment delimiters ("<!−−" and
* "−−>") from STYLE tag contents.
*/
public static final String STYLE_STRIP_COMMENT_DELIMS = "http://cyberneko.org/html/features/scanner/style/strip-comment-delims";
/**
* Strip XHTML CDATA delimiters ("<![CDATA[" and "]]>") from
* STYLE tag contents.
*/
public static final String STYLE_STRIP_CDATA_DELIMS = "http://cyberneko.org/html/features/scanner/style/strip-cdata-delims";
/**
* Ignore specified charset found in the <meta equiv='Content-Type'
* content='text/html;charset=…'> tag or in the <?xml … encoding='…'> processing instruction
*/
public static final String IGNORE_SPECIFIED_CHARSET = "http://cyberneko.org/html/features/scanner/ignore-specified-charset";
/** Scan CDATA sections. */
public static final String CDATA_SECTIONS = "http://cyberneko.org/html/features/scanner/cdata-sections";
/** Override doctype declaration public and system identifiers. */
public static final String OVERRIDE_DOCTYPE = "http://cyberneko.org/html/features/override-doctype";
/** Insert document type declaration. */
public static final String INSERT_DOCTYPE = "http://cyberneko.org/html/features/insert-doctype";
/** Parse <noscript>...</noscript> content */
public static final String PARSE_NOSCRIPT_CONTENT = "http://cyberneko.org/html/features/parse-noscript-content";
/** Normalize attribute values. */
protected static final String NORMALIZE_ATTRIBUTES = "http://cyberneko.org/html/features/scanner/normalize-attrs";
/** Recognized features. */
private static final String[] RECOGNIZED_FEATURES = {
AUGMENTATIONS,
REPORT_ERRORS,
NOTIFY_CHAR_REFS,
NOTIFY_XML_BUILTIN_REFS,
NOTIFY_HTML_BUILTIN_REFS,
FIX_MSWINDOWS_REFS,
SCRIPT_STRIP_CDATA_DELIMS,
SCRIPT_STRIP_COMMENT_DELIMS,
STYLE_STRIP_CDATA_DELIMS,
STYLE_STRIP_COMMENT_DELIMS,
IGNORE_SPECIFIED_CHARSET,
CDATA_SECTIONS,
OVERRIDE_DOCTYPE,
INSERT_DOCTYPE,
NORMALIZE_ATTRIBUTES,
PARSE_NOSCRIPT_CONTENT,
};
/** Recognized features defaults. */
private static final Boolean[] RECOGNIZED_FEATURES_DEFAULTS = {
null,
null,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.TRUE,
};
// properties
/** Modify HTML element names: { "upper", "lower", "default" }. */
protected static final String NAMES_ELEMS = "http://cyberneko.org/html/properties/names/elems";
/** Modify HTML attribute names: { "upper", "lower", "default" }. */
protected static final String NAMES_ATTRS = "http://cyberneko.org/html/properties/names/attrs";
/** Default encoding. */
protected static final String DEFAULT_ENCODING = "http://cyberneko.org/html/properties/default-encoding";
/** Error reporter. */
protected static final String ERROR_REPORTER = "http://cyberneko.org/html/properties/error-reporter";
/** Doctype declaration public identifier. */
protected static final String DOCTYPE_PUBID = "http://cyberneko.org/html/properties/doctype/pubid";
/** Doctype declaration system identifier. */
protected static final String DOCTYPE_SYSID = "http://cyberneko.org/html/properties/doctype/sysid";
/** Recognized properties. */
private static final String[] RECOGNIZED_PROPERTIES = {
NAMES_ELEMS,
NAMES_ATTRS,
DEFAULT_ENCODING,
ERROR_REPORTER,
DOCTYPE_PUBID,
DOCTYPE_SYSID,
};
/** Recognized properties defaults. */
private static final Object[] RECOGNIZED_PROPERTIES_DEFAULTS = {
null,
null,
"Windows-1252",
null,
HTML_4_01_TRANSITIONAL_PUBID,
HTML_4_01_TRANSITIONAL_SYSID,
};
// states
/** State: content. */
protected static final short STATE_CONTENT = 0;
/** State: markup bracket. */
protected static final short STATE_MARKUP_BRACKET = 1;
/** State: start document. */
protected static final short STATE_START_DOCUMENT = 10;
/** State: end document. */
protected static final short STATE_END_DOCUMENT = 11;
// modify HTML names
/** Don't modify HTML names. */
protected static final short NAMES_NO_CHANGE = 0;
/** Uppercase HTML names. */
protected static final short NAMES_UPPERCASE = 1;
/** Lowercase HTML names. */
protected static final short NAMES_LOWERCASE = 2;
// defaults
/** Default buffer size. */
protected static final int DEFAULT_BUFFER_SIZE = 2048;
// debugging
/** Set to true to debug changes in the scanner. */
private static final boolean DEBUG_SCANNER = false;
/** Set to true to debug changes in the scanner state. */
private static final boolean DEBUG_SCANNER_STATE = false;
/** Set to true to debug the buffer. */
private static final boolean DEBUG_BUFFER = false;
/** Set to true to debug character encoding handling. */
private static final boolean DEBUG_CHARSET = false;
/** Set to true to debug callbacks. */
protected static final boolean DEBUG_CALLBACKS = false;
// static vars
/** Synthesized event info item. */
protected static final HTMLEventInfo SYNTHESIZED_ITEM =
new HTMLEventInfo.SynthesizedItem();
private final static BitSet ENTITY_CHARS = new BitSet();
static {
final String str = "-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
ENTITY_CHARS.set(c);
}
}
//
// Data
//
// features
/** Augmentations. */
protected boolean fAugmentations;
/** Report errors. */
protected boolean fReportErrors;
/** Notify character entity references. */
protected boolean fNotifyCharRefs;
/** Notify XML built-in general entity references. */
protected boolean fNotifyXmlBuiltinRefs;
/** Notify HTML built-in general entity references. */
protected boolean fNotifyHtmlBuiltinRefs;
/** Fix Microsoft Windows® character entity references. */
protected boolean fFixWindowsCharRefs;
/** Strip CDATA delimiters from SCRIPT tags. */
protected boolean fScriptStripCDATADelims;
/** Strip comment delimiters from SCRIPT tags. */
protected boolean fScriptStripCommentDelims;
/** Strip CDATA delimiters from STYLE tags. */
protected boolean fStyleStripCDATADelims;
/** Strip comment delimiters from STYLE tags. */
protected boolean fStyleStripCommentDelims;
/** Ignore specified character set. */
protected boolean fIgnoreSpecifiedCharset;
/** CDATA sections. */
protected boolean fCDATASections;
/** Override doctype declaration public and system identifiers. */
protected boolean fOverrideDoctype;
/** Insert document type declaration. */
protected boolean fInsertDoctype;
/** Normalize attribute values. */
protected boolean fNormalizeAttributes;
/** Parse noscript content. */
protected boolean fParseNoScriptContent;
/** Parse noframes content. */
protected boolean fParseNoFramesContent;
// properties
/** Modify HTML element names. */
protected short fNamesElems;
/** Modify HTML attribute names. */
protected short fNamesAttrs;
/** Default encoding. */
protected String fDefaultIANAEncoding;
/** Error reporter. */
protected HTMLErrorReporter fErrorReporter;
/** Doctype declaration public identifier. */
protected String fDoctypePubid;
/** Doctype declaration system identifier. */
protected String fDoctypeSysid;
// boundary locator information
/** Beginning line number. */
protected int fBeginLineNumber;
/** Beginning column number. */
protected int fBeginColumnNumber;
/** Beginning character offset in the file. */
protected int fBeginCharacterOffset;
/** Ending line number. */
protected int fEndLineNumber;
/** Ending column number. */
protected int fEndColumnNumber;
/** Ending character offset in the file. */
protected int fEndCharacterOffset;
// state
/** The playback byte stream. */
protected PlaybackInputStream fByteStream;
/** Current entity. */
protected CurrentEntity fCurrentEntity;
/** The current entity stack. */
protected final Stack fCurrentEntityStack = new Stack();
/** The current scanner. */
protected Scanner fScanner;
/** The current scanner state. */
protected short fScannerState;
/** The document handler. */
protected XMLDocumentHandler fDocumentHandler;
/** Auto-detected IANA encoding. */
protected String fIANAEncoding;
/** Auto-detected Java encoding. */
protected String fJavaEncoding;
/** True if the encoding matches "ISO-8859-*". */
protected boolean fIso8859Encoding;
/** Element count. */
protected int fElementCount;
/** Element depth. */
protected int fElementDepth;
// scanners
/** Content scanner. */
protected Scanner fContentScanner = new ContentScanner();
/**
* Special scanner used for elements whose content needs to be scanned
* as plain text, ignoring markup such as elements and entity references.
* For example: <SCRIPT> and <COMMENT>.
*/
protected SpecialScanner fSpecialScanner = new SpecialScanner();
// temp vars
/** String buffer. */
protected final XMLStringBuffer fStringBuffer = new XMLStringBuffer(1024);
/** String buffer. */
private final XMLStringBuffer fStringBuffer2 = new XMLStringBuffer(1024);
/** Non-normalized attribute string buffer. */
private final XMLStringBuffer fNonNormAttr = new XMLStringBuffer(128);
/** Augmentations. */
private final HTMLAugmentations fInfosetAugs = new HTMLAugmentations();
/** Location infoset item. */
private final LocationItem fLocationItem = new LocationItem();
/** Single boolean array. */
private final boolean[] fSingleBoolean = { false };
/** Resource identifier. */
private final XMLResourceIdentifierImpl fResourceId = new XMLResourceIdentifierImpl();
//
// Public methods
//
/**
* Pushes an input source onto the current entity stack. This
* enables the scanner to transparently scan new content (e.g.
* the output written by an embedded script). At the end of the
* current entity, the scanner returns where it left off at the
* time this entity source was pushed.
* <p>
* <strong>Note:</strong>
* This functionality is experimental at this time and is
* subject to change in future releases of NekoHTML.
*
* @param inputSource The new input source to start scanning.
* @see #evaluateInputSource(XMLInputSource)
*/
public void pushInputSource(XMLInputSource inputSource) {
final Reader reader = getReader(inputSource);
fCurrentEntityStack.push(fCurrentEntity);
String encoding = inputSource.getEncoding();
String publicId = inputSource.getPublicId();
String baseSystemId = inputSource.getBaseSystemId();
String literalSystemId = inputSource.getSystemId();
String expandedSystemId = expandSystemId(literalSystemId, baseSystemId);
fCurrentEntity = new CurrentEntity(reader, encoding,
publicId, baseSystemId,
literalSystemId, expandedSystemId);
} // pushInputSource(XMLInputSource)
private Reader getReader(final XMLInputSource inputSource) {
Reader reader = inputSource.getCharacterStream();
if (reader == null) {
try {
return new InputStreamReader(inputSource.getByteStream(), fJavaEncoding);
}
catch (final UnsupportedEncodingException e) {
// should not happen as this encoding is already used to parse the "main" source
}
}
return reader;
}
/**
* Immediately evaluates an input source and add the new content (e.g.
* the output written by an embedded script).
*
* @param inputSource The new input source to start evaluating.
* @see #pushInputSource(XMLInputSource)
*/
public void evaluateInputSource(XMLInputSource inputSource) {
final Scanner previousScanner = fScanner;
final short previousScannerState = fScannerState;
final CurrentEntity previousEntity = fCurrentEntity;
final Reader reader = getReader(inputSource);
String encoding = inputSource.getEncoding();
String publicId = inputSource.getPublicId();
String baseSystemId = inputSource.getBaseSystemId();
String literalSystemId = inputSource.getSystemId();
String expandedSystemId = expandSystemId(literalSystemId, baseSystemId);
fCurrentEntity = new CurrentEntity(reader, encoding,
publicId, baseSystemId,
literalSystemId, expandedSystemId);
setScanner(fContentScanner);
setScannerState(STATE_CONTENT);
try {
do {
fScanner.scan(false);
} while (fScannerState != STATE_END_DOCUMENT);
}
catch (final IOException e) {
// ignore
}
setScanner(previousScanner);
setScannerState(previousScannerState);
fCurrentEntity = previousEntity;
} // evaluateInputSource(XMLInputSource)
/**
* Cleans up used resources. For example, if scanning is terminated
* early, then this method ensures all remaining open streams are
* closed.
*
* @param closeall Close all streams, including the original.
* This is used in cases when the application has
* opened the original document stream and should
* be responsible for closing it.
*/
public void cleanup(boolean closeall) {
int size = fCurrentEntityStack.size();
if (size > 0) {
// current entity is not the original, so close it
if (fCurrentEntity != null) {
fCurrentEntity.closeQuietly();
}
// close remaining streams
for (int i = closeall ? 0 : 1; i < size; i++) {
fCurrentEntity = (CurrentEntity) fCurrentEntityStack.pop();
fCurrentEntity.closeQuietly();
}
}
else if (closeall && fCurrentEntity != null) {
fCurrentEntity.closeQuietly();
}
} // cleanup(boolean)
//
// XMLLocator methods
//
/** Returns the encoding. */
public String getEncoding() {
return fCurrentEntity != null ? fCurrentEntity.encoding : null;
} // getEncoding():String
/** Returns the public identifier. */
public String getPublicId() {
return fCurrentEntity != null ? fCurrentEntity.publicId : null;
} // getPublicId():String
/** Returns the base system identifier. */
public String getBaseSystemId() {
return fCurrentEntity != null ? fCurrentEntity.baseSystemId : null;
} // getBaseSystemId():String
/** Returns the literal system identifier. */
public String getLiteralSystemId() {
return fCurrentEntity != null ? fCurrentEntity.literalSystemId : null;
} // getLiteralSystemId():String
/** Returns the expanded system identifier. */
public String getExpandedSystemId() {
return fCurrentEntity != null ? fCurrentEntity.expandedSystemId : null;
} // getExpandedSystemId():String
/** Returns the current line number. */
public int getLineNumber() {
return fCurrentEntity != null ? fCurrentEntity.getLineNumber() : -1;
} // getLineNumber():int
/** Returns the current column number. */
public int getColumnNumber() {
return fCurrentEntity != null ? fCurrentEntity.getColumnNumber() : -1;
} // getColumnNumber():int
/** Returns the XML version. */
public String getXMLVersion() {
return fCurrentEntity != null ? fCurrentEntity.version : null;
} // getXMLVersion():String
/** Returns the character offset. */
public int getCharacterOffset() {
return fCurrentEntity != null ? fCurrentEntity.getCharacterOffset() : -1;
} // getCharacterOffset():int
//
// HTMLComponent methods
//
/** Returns the default state for a feature. */
public Boolean getFeatureDefault(String featureId) {
int length = RECOGNIZED_FEATURES != null ? RECOGNIZED_FEATURES.length : 0;
for (int i = 0; i < length; i++) {
if (RECOGNIZED_FEATURES[i].equals(featureId)) {
return RECOGNIZED_FEATURES_DEFAULTS[i];
}
}
return null;
} // getFeatureDefault(String):Boolean
/** Returns the default state for a property. */
public Object getPropertyDefault(String propertyId) {
int length = RECOGNIZED_PROPERTIES != null ? RECOGNIZED_PROPERTIES.length : 0;
for (int i = 0; i < length; i++) {
if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) {
return RECOGNIZED_PROPERTIES_DEFAULTS[i];
}
}
return null;
} // getPropertyDefault(String):Object
//
// XMLComponent methods
//
/** Returns recognized features. */
public String[] getRecognizedFeatures() {
return RECOGNIZED_FEATURES;
} // getRecognizedFeatures():String[]
/** Returns recognized properties. */
public String[] getRecognizedProperties() {
return RECOGNIZED_PROPERTIES;
} // getRecognizedProperties():String[]
/** Resets the component. */
public void reset(XMLComponentManager manager)
throws XMLConfigurationException {
// get features
fAugmentations = manager.getFeature(AUGMENTATIONS);
fReportErrors = manager.getFeature(REPORT_ERRORS);
fNotifyCharRefs = manager.getFeature(NOTIFY_CHAR_REFS);
fNotifyXmlBuiltinRefs = manager.getFeature(NOTIFY_XML_BUILTIN_REFS);
fNotifyHtmlBuiltinRefs = manager.getFeature(NOTIFY_HTML_BUILTIN_REFS);
fFixWindowsCharRefs = manager.getFeature(FIX_MSWINDOWS_REFS);
fScriptStripCDATADelims = manager.getFeature(SCRIPT_STRIP_CDATA_DELIMS);
fScriptStripCommentDelims = manager.getFeature(SCRIPT_STRIP_COMMENT_DELIMS);
fStyleStripCDATADelims = manager.getFeature(STYLE_STRIP_CDATA_DELIMS);
fStyleStripCommentDelims = manager.getFeature(STYLE_STRIP_COMMENT_DELIMS);
fIgnoreSpecifiedCharset = manager.getFeature(IGNORE_SPECIFIED_CHARSET);
fCDATASections = manager.getFeature(CDATA_SECTIONS);
fOverrideDoctype = manager.getFeature(OVERRIDE_DOCTYPE);
fInsertDoctype = manager.getFeature(INSERT_DOCTYPE);
fNormalizeAttributes = manager.getFeature(NORMALIZE_ATTRIBUTES);
fParseNoScriptContent = manager.getFeature(PARSE_NOSCRIPT_CONTENT);
// get properties
fNamesElems = getNamesValue(String.valueOf(manager.getProperty(NAMES_ELEMS)));
fNamesAttrs = getNamesValue(String.valueOf(manager.getProperty(NAMES_ATTRS)));
fDefaultIANAEncoding = String.valueOf(manager.getProperty(DEFAULT_ENCODING));
fErrorReporter = (HTMLErrorReporter)manager.getProperty(ERROR_REPORTER);
fDoctypePubid = String.valueOf(manager.getProperty(DOCTYPE_PUBID));
fDoctypeSysid = String.valueOf(manager.getProperty(DOCTYPE_SYSID));
} // reset(XMLComponentManager)
/** Sets a feature. */
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
if (featureId.equals(AUGMENTATIONS)) {
fAugmentations = state;
}
else if (featureId.equals(IGNORE_SPECIFIED_CHARSET)) {
fIgnoreSpecifiedCharset = state;
}
else if (featureId.equals(NOTIFY_CHAR_REFS)) {
fNotifyCharRefs = state;
}
else if (featureId.equals(NOTIFY_XML_BUILTIN_REFS)) {
fNotifyXmlBuiltinRefs = state;
}
else if (featureId.equals(NOTIFY_HTML_BUILTIN_REFS)) {
fNotifyHtmlBuiltinRefs = state;
}
else if (featureId.equals(FIX_MSWINDOWS_REFS)) {
fFixWindowsCharRefs = state;
}
else if (featureId.equals(SCRIPT_STRIP_CDATA_DELIMS)) {
fScriptStripCDATADelims = state;
}
else if (featureId.equals(SCRIPT_STRIP_COMMENT_DELIMS)) {
fScriptStripCommentDelims = state;
}
else if (featureId.equals(STYLE_STRIP_CDATA_DELIMS)) {
fStyleStripCDATADelims = state;
}
else if (featureId.equals(STYLE_STRIP_COMMENT_DELIMS)) {
fStyleStripCommentDelims = state;
}
else if (featureId.equals(IGNORE_SPECIFIED_CHARSET)) {
fIgnoreSpecifiedCharset = state;
}
else if (featureId.equals(PARSE_NOSCRIPT_CONTENT)) {
fParseNoScriptContent = state;
}
} // setFeature(String,boolean)
/** Sets a property. */
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
if (propertyId.equals(NAMES_ELEMS)) {
fNamesElems = getNamesValue(String.valueOf(value));
return;
}
if (propertyId.equals(NAMES_ATTRS)) {
fNamesAttrs = getNamesValue(String.valueOf(value));
return;
}
if (propertyId.equals(DEFAULT_ENCODING)) {
fDefaultIANAEncoding = String.valueOf(value);
return;
}
} // setProperty(String,Object)
//
// XMLDocumentScanner methods
//
/** Sets the input source. */
public void setInputSource(XMLInputSource source) throws IOException {
// reset state
fElementCount = 0;
fElementDepth = -1;
fByteStream = null;
fCurrentEntityStack.removeAllElements();
fBeginLineNumber = 1;
fBeginColumnNumber = 1;
fBeginCharacterOffset = 0;
fEndLineNumber = fBeginLineNumber;
fEndColumnNumber = fBeginColumnNumber;
fEndCharacterOffset = fBeginCharacterOffset;
// reset encoding information
fIANAEncoding = fDefaultIANAEncoding;
fJavaEncoding = fIANAEncoding;
// get location information
String encoding = source.getEncoding();
String publicId = source.getPublicId();
String baseSystemId = source.getBaseSystemId();
String literalSystemId = source.getSystemId();
String expandedSystemId = expandSystemId(literalSystemId, baseSystemId);
// open stream
Reader reader = source.getCharacterStream();
if (reader == null) {
InputStream inputStream = source.getByteStream();
if (inputStream == null) {
URL url = new URL(expandedSystemId);
inputStream = url.openStream();
}
fByteStream = new PlaybackInputStream(inputStream);
String[] encodings = new String[2];
if (encoding == null) {
fByteStream.detectEncoding(encodings);
}
else {
encodings[0] = encoding;
}
if (encodings[0] == null) {
encodings[0] = fDefaultIANAEncoding;
if (fReportErrors) {
fErrorReporter.reportWarning("HTML1000", null);
}
}
if (encodings[1] == null) {
encodings[1] = EncodingMap.getIANA2JavaMapping(encodings[0].toUpperCase());
if (encodings[1] == null) {
encodings[1] = encodings[0];
if (fReportErrors) {
fErrorReporter.reportWarning("HTML1001", new Object[]{encodings[0]});
}
}
}
fIANAEncoding = encodings[0];
fJavaEncoding = encodings[1];
/* PATCH: Asgeir Asgeirsson */
fIso8859Encoding = fIANAEncoding == null
|| fIANAEncoding.toUpperCase().startsWith("ISO-8859")
|| fIANAEncoding.equalsIgnoreCase(fDefaultIANAEncoding);
encoding = fIANAEncoding;
reader = new InputStreamReader(fByteStream, fJavaEncoding);
}
fCurrentEntity = new CurrentEntity(reader, encoding,
publicId, baseSystemId,
literalSystemId, expandedSystemId);
// set scanner and state
setScanner(fContentScanner);
setScannerState(STATE_START_DOCUMENT);
} // setInputSource(XMLInputSource)
/** Scans the document. */
public boolean scanDocument(boolean complete) throws XNIException, IOException {
do {
if (!fScanner.scan(complete)) {
return false;
}
} while (complete);
return true;
} // scanDocument(boolean):boolean
/** Sets the document handler. */
public void setDocumentHandler(XMLDocumentHandler handler) {
fDocumentHandler = handler;
} // setDocumentHandler(XMLDocumentHandler)
// @since Xerces 2.1.0
/** Returns the document handler. */
public XMLDocumentHandler getDocumentHandler() {
return fDocumentHandler;
} // getDocumentHandler():XMLDocumentHandler
//
// Protected static methods
//
/** Returns the value of the specified attribute, ignoring case. */
protected static String getValue(XMLAttributes attrs, String aname) {
int length = attrs != null ? attrs.getLength() : 0;
for (int i = 0; i < length; i++) {
if (attrs.getQName(i).equalsIgnoreCase(aname)) {
return attrs.getValue(i);
}
}
return null;
} // getValue(XMLAttributes,String):String
/**
* Expands a system id and returns the system id as a URI, if
* it can be expanded. A return value of null means that the
* identifier is already expanded. An exception thrown
* indicates a failure to expand the id.
*
* @param systemId The systemId to be expanded.
*
* @return Returns the URI string representing the expanded system
* identifier. A null value indicates that the given
* system identifier is already expanded.
*
*/
public static String expandSystemId(String systemId, String baseSystemId) {
// check for bad parameters id
if (systemId == null || systemId.length() == 0) {
return systemId;
}
// if id already expanded, return
try {
URI uri = new URI(systemId);
if (uri != null) {
return systemId;
}
}
catch (URI.MalformedURIException e) {
// continue on...
}
// normalize id
String id = fixURI(systemId);
// normalize base
URI base = null;
URI uri = null;
try {
if (baseSystemId == null || baseSystemId.length() == 0 ||
baseSystemId.equals(systemId)) {
String dir;
try {
dir = fixURI(System.getProperty("user.dir"));
}
catch (SecurityException se) {
dir = "";
}
if (!dir.endsWith("/")) {
dir = dir + "/";
}
base = new URI("file", "", dir, null, null);
}
else {
try {
base = new URI(fixURI(baseSystemId));
}
catch (URI.MalformedURIException e) {
String dir;
try {
dir = fixURI(System.getProperty("user.dir"));
}
catch (SecurityException se) {
dir = "";
}
if (baseSystemId.indexOf(':') != -1) {
// for xml schemas we might have baseURI with
// a specified drive
base = new URI("file", "", fixURI(baseSystemId), null, null);
}
else {
if (!dir.endsWith("/")) {
dir = dir + "/";
}
dir = dir + fixURI(baseSystemId);
base = new URI("file", "", dir, null, null);
}
}
}
// expand id
uri = new URI(base, id);
}
catch (URI.MalformedURIException e) {
// let it go through
}
if (uri == null) {
return systemId;
}
return uri.toString();
} // expandSystemId(String,String):String
/**
* Fixes a platform dependent filename to standard URI form.
*
* @param str The string to fix.
*
* @return Returns the fixed URI string.
*/
protected static String fixURI(String str) {
// handle platform dependent strings
str = str.replace(java.io.File.separatorChar, '/');
// Windows fix
if (str.length() >= 2) {
char ch1 = str.charAt(1);
// change "C:blah" to "/C:blah"
if (ch1 == ':') {
char ch0 = Character.toUpperCase(str.charAt(0));
if (ch0 >= 'A' && ch0 <= 'Z') {
str = "/" + str;
}
}
// change "//blah" to "file://blah"
else if (ch1 == '/' && str.charAt(0) == '/') {
str = "file:" + str;
}
}
// done
return str;
} // fixURI(String):String
/** Modifies the given name based on the specified mode. */
protected static final String modifyName(String name, short mode) {
switch (mode) {
case NAMES_UPPERCASE: return name.toUpperCase();
case NAMES_LOWERCASE: return name.toLowerCase();
}
return name;
} // modifyName(String,short):String
/**
* Converts HTML names string value to constant value.
*
* @see #NAMES_NO_CHANGE
* @see #NAMES_LOWERCASE
* @see #NAMES_UPPERCASE
*/
protected static final short getNamesValue(String value) {
if (value.equals("lower")) {
return NAMES_LOWERCASE;
}
if (value.equals("upper")) {
return NAMES_UPPERCASE;
}
return NAMES_NO_CHANGE;
} // getNamesValue(String):short
/**
* Fixes Microsoft Windows® specific characters.
* <p>
* Details about this common problem can be found at
* <a href='http://www.cs.tut.fi/~jkorpela/www/windows-chars.html'>http://www.cs.tut.fi/~jkorpela/www/windows-chars.html</a>
*/
protected int fixWindowsCharacter(int origChar) {
/* PATCH: Asgeir Asgeirsson */
switch(origChar) {
case 130: return 8218;
case 131: return 402;
case 132: return 8222;
case 133: return 8230;
case 134: return 8224;
case 135: return 8225;
case 136: return 710;
case 137: return 8240;
case 138: return 352;
case 139: return 8249;
case 140: return 338;
case 145: return 8216;
case 146: return 8217;
case 147: return 8220;
case 148: return 8221;
case 149: return 8226;
case 150: return 8211;
case 151: return 8212;
case 152: return 732;
case 153: return 8482;
case 154: return 353;
case 155: return 8250;
case 156: return 339;
case 159: return 376;
}
return origChar;
} // fixWindowsCharacter(int):int
//
// Protected methods
//
// i/o
/** Reads a single character. */
protected int read() throws IOException {
return fCurrentEntity.read();
}
// debugging
/** Sets the scanner. */
protected void setScanner(Scanner scanner) {
fScanner = scanner;
if (DEBUG_SCANNER) {
System.out.print("$$$ setScanner(");
System.out.print(scanner!=null?scanner.getClass().getName():"null");
System.out.println(");");
}
} // setScanner(Scanner)
/** Sets the scanner state. */
protected void setScannerState(short state) {
fScannerState = state;
if (DEBUG_SCANNER_STATE) {
System.out.print("$$$ setScannerState(");
switch (fScannerState) {
case STATE_CONTENT: { System.out.print("STATE_CONTENT"); break; }
case STATE_MARKUP_BRACKET: { System.out.print("STATE_MARKUP_BRACKET"); break; }
case STATE_START_DOCUMENT: { System.out.print("STATE_START_DOCUMENT"); break; }
case STATE_END_DOCUMENT: { System.out.print("STATE_END_DOCUMENT"); break; }
}
System.out.println(");");
}
} // setScannerState(short)
// scanning
/** Scans a DOCTYPE line. */
protected void scanDoctype() throws IOException {
String root = null;
String pubid = null;
String sysid = null;
if (skipSpaces()) {
root = scanName();
if (root == null) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1014", null);
}
}
else {
root = modifyName(root, fNamesElems);
}
if (skipSpaces()) {
if (skip("PUBLIC", false)) {
skipSpaces();
pubid = scanLiteral();
if (skipSpaces()) {
sysid = scanLiteral();
}
}
else if (skip("SYSTEM", false)) {
skipSpaces();
sysid = scanLiteral();
}
}
}
int c;
while ((c = fCurrentEntity.read()) != -1) {
if (c == '<') {
fCurrentEntity.rewind();
break;
}
if (c == '>') {
break;
}
if (c == '[') {
skipMarkup(true);
break;
}
}
if (fDocumentHandler != null) {
if (fOverrideDoctype) {
pubid = fDoctypePubid;
sysid = fDoctypeSysid;
}
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fDocumentHandler.doctypeDecl(root, pubid, sysid, locationAugs());
}
} // scanDoctype()
/** Scans a quoted literal. */
protected String scanLiteral() throws IOException {
int quote = fCurrentEntity.read();
if (quote == '\'' || quote == '"') {
StringBuffer str = new StringBuffer();
int c;
while ((c = fCurrentEntity.read()) != -1) {
if (c == quote) {
break;
}
if (c == '\r' || c == '\n') {
fCurrentEntity.rewind();
// NOTE: This collapses newlines to a single space.
// [Q] Is this the right thing to do here? -Ac
skipNewlines();
str.append(' ');
}
else if (c == '<') {
fCurrentEntity.rewind();
break;
}
else {
str.append((char)c);
}
}
if (c == -1) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1007", null);
}
throw new EOFException();
}
return str.toString();
}
else {
fCurrentEntity.rewind();
}
return null;
} // scanLiteral():String
/** Scans a name. */
protected String scanName() throws IOException {
fCurrentEntity.debugBufferIfNeeded("(scanName: ");
if (fCurrentEntity.offset == fCurrentEntity.length) {
if (fCurrentEntity.load(0) == -1) {
fCurrentEntity.debugBufferIfNeeded(")scanName: ");
return null;
}
}
int offset = fCurrentEntity.offset;
while (true) {
while (fCurrentEntity.hasNext()) {
char c = fCurrentEntity.getNextChar();
if (!Character.isLetterOrDigit(c) &&
!(c == '-' || c == '.' || c == ':' || c == '_')) {
fCurrentEntity.rewind();
break;
}
}
if (fCurrentEntity.offset == fCurrentEntity.length) {
int length = fCurrentEntity.length - offset;
System.arraycopy(fCurrentEntity.buffer, offset, fCurrentEntity.buffer, 0, length);
int count = fCurrentEntity.load(length);
offset = 0;
if (count == -1) {
break;
}
}
else {
break;
}
}
int length = fCurrentEntity.offset - offset;
String name = length > 0 ? new String(fCurrentEntity.buffer, offset, length) : null;
fCurrentEntity.debugBufferIfNeeded(")scanName: ", " -> \"" + name + '"');
return name;
} // scanName():String
/** Scans an entity reference. */
protected int scanEntityRef(final XMLStringBuffer str, final boolean content)
throws IOException {
str.clear();
str.append('&');
boolean endsWithSemicolon = false;
while (true) {
int c = fCurrentEntity.read();
if (c == ';') {
str.append(';');
endsWithSemicolon = true;
break;
}
else if (c == -1) {
break;
}
else if (!ENTITY_CHARS.get(c) && c != '#') {
fCurrentEntity.rewind();
break;
}
str.append((char)c);
}
if (!endsWithSemicolon) {
if (fReportErrors) {
fErrorReporter.reportWarning("HTML1004", null);
}
}
if (str.length == 1) {
if (content && fDocumentHandler != null && fElementCount >= fElementDepth) {
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fDocumentHandler.characters(str, locationAugs());
}
return -1;
}
final String name;
if (endsWithSemicolon)
name = str.toString().substring(1, str.length -1);
else
name = str.toString().substring(1);
if (name.startsWith("#")) {
int value = -1;
try {
if (name.startsWith("#x") || name.startsWith("#X")) {
value = Integer.parseInt(name.substring(2), 16);
}
else {
value = Integer.parseInt(name.substring(1));
}
/* PATCH: Asgeir Asgeirsson */
if (fFixWindowsCharRefs && fIso8859Encoding) {
value = fixWindowsCharacter(value);
}
if (content && fDocumentHandler != null && fElementCount >= fElementDepth) {
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
if (fNotifyCharRefs) {
XMLResourceIdentifier id = resourceId();
String encoding = null;
fDocumentHandler.startGeneralEntity(name, id, encoding, locationAugs());
}
str.clear();
str.append((char)value);
fDocumentHandler.characters(str, locationAugs());
if (fNotifyCharRefs) {
fDocumentHandler.endGeneralEntity(name, locationAugs());
}
}
}
catch (NumberFormatException e) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1005", new Object[]{name});
}
if (content && fDocumentHandler != null && fElementCount >= fElementDepth) {
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fDocumentHandler.characters(str, locationAugs());
}
}
return value;
}
int c = HTMLEntities.get(name);
// in attributes, some incomplete entities should be recognized, not all
// TODO: investigate to find which ones (there are differences between browsers)
// in a first time, consider only those that behave the same in FF and IE
final boolean invalidEntityInAttribute = !content && !endsWithSemicolon && c > 256;
if (c == -1 || invalidEntityInAttribute) {
if (fReportErrors) {
fErrorReporter.reportWarning("HTML1006", new Object[]{name});
}
if (content && fDocumentHandler != null && fElementCount >= fElementDepth) {
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fDocumentHandler.characters(str, locationAugs());
}
return -1;
}
if (content && fDocumentHandler != null && fElementCount >= fElementDepth) {
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
boolean notify = fNotifyHtmlBuiltinRefs || (fNotifyXmlBuiltinRefs && builtinXmlRef(name));
if (notify) {
XMLResourceIdentifier id = resourceId();
String encoding = null;
fDocumentHandler.startGeneralEntity(name, id, encoding, locationAugs());
}
str.clear();
str.append((char)c);
fDocumentHandler.characters(str, locationAugs());
if (notify) {
fDocumentHandler.endGeneralEntity(name, locationAugs());
}
}
return c;
} // scanEntityRef(XMLStringBuffer,boolean):int
/** Returns true if the specified text is present and is skipped. */
protected boolean skip(String s, boolean caseSensitive) throws IOException {
int length = s != null ? s.length() : 0;
for (int i = 0; i < length; i++) {
if (fCurrentEntity.offset == fCurrentEntity.length) {
System.arraycopy(fCurrentEntity.buffer, fCurrentEntity.offset - i, fCurrentEntity.buffer, 0, i);
if (fCurrentEntity.load(i) == -1) {
fCurrentEntity.offset = 0;
return false;
}
}
char c0 = s.charAt(i);
char c1 = fCurrentEntity.getNextChar();
if (!caseSensitive) {
c0 = Character.toUpperCase(c0);
c1 = Character.toUpperCase(c1);
}
if (c0 != c1) {
fCurrentEntity.rewind(i + 1);
return false;
}
}
return true;
} // skip(String):boolean
/** Skips markup. */
protected boolean skipMarkup(boolean balance) throws IOException {
fCurrentEntity.debugBufferIfNeeded("(skipMarkup: ");
int depth = 1;
boolean slashgt = false;
OUTER: while (true) {
if (fCurrentEntity.offset == fCurrentEntity.length) {
if (fCurrentEntity.load(0) == -1) {
break OUTER;
}
}
while (fCurrentEntity.hasNext()) {
char c = fCurrentEntity.getNextChar();
if (balance && c == '<') {
depth++;
}
else if (c == '>') {
depth--;
if (depth == 0) {
break OUTER;
}
}
else if (c == '/') {
if (fCurrentEntity.offset == fCurrentEntity.length) {
if (fCurrentEntity.load(0) == -1) {
break OUTER;
}
}
c = fCurrentEntity.getNextChar();
if (c == '>') {
slashgt = true;
depth--;
if (depth == 0) {
break OUTER;
}
}
else {
fCurrentEntity.rewind();
}
}
else if (c == '\r' || c == '\n') {
fCurrentEntity.rewind();
skipNewlines();
}
}
}
fCurrentEntity.debugBufferIfNeeded(")skipMarkup: ", " -> "+slashgt);
return slashgt;
} // skipMarkup():boolean
/** Skips whitespace. */
protected boolean skipSpaces() throws IOException {
fCurrentEntity.debugBufferIfNeeded("(skipSpaces: ");
boolean spaces = false;
while (true) {
if (fCurrentEntity.offset == fCurrentEntity.length) {
if (fCurrentEntity.load(0) == -1) {
break;
}
}
char c = fCurrentEntity.getNextChar();
if (!Character.isWhitespace(c)) {
fCurrentEntity.rewind();
break;
}
spaces = true;
if (c == '\r' || c == '\n') {
fCurrentEntity.rewind();
skipNewlines();
continue;
}
}
fCurrentEntity.debugBufferIfNeeded(")skipSpaces: ", " -> " + spaces);
return spaces;
} // skipSpaces()
/** Skips newlines and returns the number of newlines skipped. */
protected int skipNewlines() throws IOException {
fCurrentEntity.debugBufferIfNeeded("(skipNewlines: ");
if (!fCurrentEntity.hasNext()) {
if (fCurrentEntity.load(0) == -1) {
fCurrentEntity.debugBufferIfNeeded(")skipNewlines: ");
return 0;
}
}
char c = fCurrentEntity.getCurrentChar();
int newlines = 0;
int offset = fCurrentEntity.offset;
if (c == '\n' || c == '\r') {
do {
c = fCurrentEntity.getNextChar();
if (c == '\r') {
newlines++;
if (fCurrentEntity.offset == fCurrentEntity.length) {
offset = 0;
fCurrentEntity.offset = newlines;
if (fCurrentEntity.load(newlines) == -1) {
break;
}
}
if (fCurrentEntity.getCurrentChar() == '\n') {
fCurrentEntity.offset++;
fCurrentEntity.characterOffset_++;
offset++;
}
}
else if (c == '\n') {
newlines++;
if (fCurrentEntity.offset == fCurrentEntity.length) {
offset = 0;
fCurrentEntity.offset = newlines;
if (fCurrentEntity.load(newlines) == -1) {
break;
}
}
}
else {
fCurrentEntity.rewind();
break;
}
} while (fCurrentEntity.offset < fCurrentEntity.length - 1);
fCurrentEntity.incLine(newlines);
}
fCurrentEntity.debugBufferIfNeeded(")skipNewlines: ", " -> " + newlines);
return newlines;
} // skipNewlines(int):int
// infoset utility methods
/** Returns an augmentations object with a location item added. */
protected final Augmentations locationAugs() {
HTMLAugmentations augs = null;
if (fAugmentations) {
fLocationItem.setValues(fBeginLineNumber, fBeginColumnNumber,
fBeginCharacterOffset, fEndLineNumber,
fEndColumnNumber, fEndCharacterOffset);
augs = fInfosetAugs;
augs.removeAllItems();
augs.putItem(AUGMENTATIONS, fLocationItem);
}
return augs;
} // locationAugs():Augmentations
/** Returns an augmentations object with a synthesized item added. */
protected final Augmentations synthesizedAugs() {
HTMLAugmentations augs = null;
if (fAugmentations) {
augs = fInfosetAugs;
augs.removeAllItems();
augs.putItem(AUGMENTATIONS, SYNTHESIZED_ITEM);
}
return augs;
} // synthesizedAugs():Augmentations
/** Returns an empty resource identifier. */
protected final XMLResourceIdentifier resourceId() {
/***/
fResourceId.clear();
return fResourceId;
/***
// NOTE: Unfortunately, the Xerces DOM parser classes expect a
// non-null resource identifier object to be passed to
// startGeneralEntity. -Ac
return null;
/***/
} // resourceId():XMLResourceIdentifier
//
// Protected static methods
//
/** Returns true if the name is a built-in XML general entity reference. */
protected static boolean builtinXmlRef(String name) {
return name.equals("amp") || name.equals("lt") || name.equals("gt") ||
name.equals("quot") || name.equals("apos");
} // builtinXmlRef(String):boolean
//
// Private methods
//
//
// Interfaces
//
/**
* Basic scanner interface.
*
* @author Andy Clark
*/
public interface Scanner {
//
// Scanner methods
//
/**
* Scans part of the document. This interface allows scanning to
* be performed in a pulling manner.
*
* @param complete True if the scanner should not return until
* scanning is complete.
*
* @return True if additional scanning is required.
*
* @throws IOException Thrown if I/O error occurs.
*/
public boolean scan(boolean complete) throws IOException;
} // interface Scanner
//
// Classes
//
/**
* Current entity.
*
* @author Andy Clark
*/
public static class CurrentEntity {
//
// Data
//
/** Character stream. */
private Reader stream_;
/** Encoding. */
public final String encoding;
/** Public identifier. */
public final String publicId;
/** Base system identifier. */
public final String baseSystemId;
/** Literal system identifier. */
public final String literalSystemId;
/** Expanded system identifier. */
public final String expandedSystemId;
/** XML version. */
public final String version = "1.0";
/** Line number. */
private int lineNumber_ = 1;
/** Column number. */
private int columnNumber_ = 1;
/** Character offset in the file. */
public int characterOffset_ = 0;
// buffer
/** Character buffer. */
public char[] buffer = new char[DEFAULT_BUFFER_SIZE];
/** Offset into character buffer. */
public int offset = 0;
/** Length of characters read into character buffer. */
public int length = 0;
private boolean endReached_ = false;
//
// Constructors
//
/** Constructs an entity from the specified stream. */
public CurrentEntity(Reader stream, String encoding,
String publicId, String baseSystemId,
String literalSystemId, String expandedSystemId) {
stream_ = stream;
this.encoding = encoding;
this.publicId = publicId;
this.baseSystemId = baseSystemId;
this.literalSystemId = literalSystemId;
this.expandedSystemId = expandedSystemId;
} // <init>(Reader,String,String,String,String)
private char getCurrentChar() {
return buffer[offset];
}
/**
* Gets the current character and moves to next one.
* @return
*/
private char getNextChar() {
characterOffset_++;
columnNumber_++;
return buffer[offset++];
}
private void closeQuietly() {
try {
stream_.close();
}
catch (IOException e) {
// ignore
}
}
/**
* Indicates if there are characters left.
*/
boolean hasNext() {
return offset < length;
}
/**
* Loads a new chunk of data into the buffer and returns the number of
* characters loaded or -1 if no additional characters were loaded.
*
* @param offset The offset at which new characters should be loaded.
*/
protected int load(int offset) throws IOException {
debugBufferIfNeeded("(load: ");
// resize buffer, if needed
if (offset == buffer.length) {
int adjust = buffer.length / 4;
char[] array = new char[buffer.length + adjust];
System.arraycopy(buffer, 0, array, 0, length);
buffer = array;
}
// read a block of characters
int count = stream_.read(buffer, offset, buffer.length - offset);
if (count == -1) {
endReached_ = true;
}
length = count != -1 ? count + offset : offset;
this.offset = offset;
debugBufferIfNeeded(")load: ", " -> " + count);
return count;
} // load():int
/** Reads a single character. */
protected int read() throws IOException {
debugBufferIfNeeded("(read: ");
if (offset == length) {
if (endReached_) {
return -1;
}
if (load(0) == -1) {
if (DEBUG_BUFFER) {
System.out.println(")read: -> -1");
}
return -1;
}
}
final char c = buffer[offset++];
characterOffset_++;
columnNumber_++;
debugBufferIfNeeded(")read: ", " -> " + c);
return c;
} // read():int
/** Prints the contents of the character buffer to standard out. */
private void debugBufferIfNeeded(final String prefix) {
debugBufferIfNeeded(prefix, "");
}
/** Prints the contents of the character buffer to standard out. */
private void debugBufferIfNeeded(final String prefix, final String suffix) {
if (DEBUG_BUFFER) {
System.out.print(prefix);
System.out.print('[');
System.out.print(length);
System.out.print(' ');
System.out.print(offset);
if (length > 0) {
System.out.print(" \"");
for (int i = 0; i < length; i++) {
if (i == offset) {
System.out.print('^');
}
char c = buffer[i];
switch (c) {
case '\r': {
System.out.print("\\r");
break;
}
case '\n': {
System.out.print("\\n");
break;
}
case '\t': {
System.out.print("\\t");
break;
}
case '"': {
System.out.print("\\\"");
break;
}
default: {
System.out.print(c);
}
}
}
if (offset == length) {
System.out.print('^');
}
System.out.print('"');
}
System.out.print(']');
System.out.print(suffix);
System.out.println();
}
} // printBuffer()
private void setStream(final InputStreamReader inputStreamReader) {
stream_ = inputStreamReader;
offset = length = characterOffset_ = 0;
lineNumber_ = columnNumber_ = 1;
}
/**
* Goes back, cancelling the effect of the previous read() call.
*/
private void rewind() {
offset--;
characterOffset_--;
columnNumber_--;
}
private void rewind(int i) {
offset -= i;
characterOffset_ -= i;
columnNumber_ -= i;
}
private void incLine() {
lineNumber_++;
columnNumber_ = 1;
}
private void incLine(int nbLines) {
lineNumber_ += nbLines;
columnNumber_ = 1;
}
public int getLineNumber() {
return lineNumber_;
}
private void resetBuffer(final XMLStringBuffer buffer, final int lineNumber,
final int columnNumber, final int characterOffset) {
lineNumber_ = lineNumber;
columnNumber_ = columnNumber;
this.characterOffset_ = characterOffset;
this.buffer = buffer.ch;
this.offset = buffer.offset;
this.length = buffer.length;
}
private int getColumnNumber() {
return columnNumber_;
}
private void restorePosition(int originalOffset,
int originalColumnNumber, int originalCharacterOffset) {
this.offset = originalOffset;
this.columnNumber_ = originalColumnNumber;
this.characterOffset_ = originalCharacterOffset;
}
private int getCharacterOffset() {
return characterOffset_;
}
} // class CurrentEntity
/**
* The primary HTML document scanner.
*
* @author Andy Clark
*/
public class ContentScanner
implements Scanner {
//
// Data
//
// temp vars
/** A qualified name. */
private final QName fQName = new QName();
/** Attributes. */
private final XMLAttributesImpl fAttributes = new XMLAttributesImpl();
//
// Scanner methods
//
/** Scan. */
public boolean scan(boolean complete) throws IOException {
boolean next;
do {
try {
next = false;
switch (fScannerState) {
case STATE_CONTENT: {
fBeginLineNumber = fCurrentEntity.getLineNumber();
fBeginColumnNumber = fCurrentEntity.getColumnNumber();
fBeginCharacterOffset = fCurrentEntity.getCharacterOffset();
int c = fCurrentEntity.read();
if (c == '<') {
setScannerState(STATE_MARKUP_BRACKET);
next = true;
}
else if (c == '&') {
scanEntityRef(fStringBuffer, true);
}
else if (c == -1) {
throw new EOFException();
}
else {
fCurrentEntity.rewind();
scanCharacters();
}
break;
}
case STATE_MARKUP_BRACKET: {
int c = fCurrentEntity.read();
if (c == '!') {
if (skip("--", false)) {
scanComment();
}
else if (skip("[CDATA[", false)) {
scanCDATA();
}
else if (skip("DOCTYPE", false)) {
scanDoctype();
}
else {
if (fReportErrors) {
fErrorReporter.reportError("HTML1002", null);
}
skipMarkup(true);
}
}
else if (c == '?') {
scanPI();
}
else if (c == '/') {
scanEndElement();
}
else if (c == -1) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1003", null);
}
if (fDocumentHandler != null && fElementCount >= fElementDepth) {
fStringBuffer.clear();
fStringBuffer.append('<');
fDocumentHandler.characters(fStringBuffer, null);
}
throw new EOFException();
}
else {
fCurrentEntity.rewind();
fElementCount++;
fSingleBoolean[0] = false;
final String ename = scanStartElement(fSingleBoolean);
fBeginLineNumber = fCurrentEntity.getLineNumber();
fBeginColumnNumber = fCurrentEntity.getColumnNumber();
fBeginCharacterOffset = fCurrentEntity.getCharacterOffset();
if ("script".equalsIgnoreCase(ename)) {
scanScriptContent();
}
else if (!fParseNoScriptContent && "noscript".equalsIgnoreCase(ename)) {
scanNoXxxContent("noscript");
}
else if (!fParseNoFramesContent && "noframes".equalsIgnoreCase(ename)) {
scanNoXxxContent("noframes");
}
else if (ename != null && !fSingleBoolean[0]
&& HTMLElements.getElement(ename).isSpecial()
&& (!ename.equalsIgnoreCase("TITLE") || isEnded(ename))) {
setScanner(fSpecialScanner.setElementName(ename));
setScannerState(STATE_CONTENT);
return true;
}
}
setScannerState(STATE_CONTENT);
break;
}
case STATE_START_DOCUMENT: {
if (fDocumentHandler != null && fElementCount >= fElementDepth) {
if (DEBUG_CALLBACKS) {
System.out.println("startDocument()");
}
XMLLocator locator = HTMLScanner.this;
String encoding = fIANAEncoding;
Augmentations augs = locationAugs();
NamespaceContext nscontext = new NamespaceSupport();
XercesBridge.getInstance().XMLDocumentHandler_startDocument(fDocumentHandler, locator, encoding, nscontext, augs);
}
if (fInsertDoctype && fDocumentHandler != null) {
String root = HTMLElements.getElement(HTMLElements.HTML).name;
root = modifyName(root, fNamesElems);
String pubid = fDoctypePubid;
String sysid = fDoctypeSysid;
fDocumentHandler.doctypeDecl(root, pubid, sysid,
synthesizedAugs());
}
setScannerState(STATE_CONTENT);
break;
}
case STATE_END_DOCUMENT: {
if (fDocumentHandler != null && fElementCount >= fElementDepth && complete) {
if (DEBUG_CALLBACKS) {
System.out.println("endDocument()");
}
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fDocumentHandler.endDocument(locationAugs());
}
return false;
}
default: {
throw new RuntimeException("unknown scanner state: "+fScannerState);
}
}
}
catch (EOFException e) {
if (fCurrentEntityStack.empty()) {
setScannerState(STATE_END_DOCUMENT);
}
else {
fCurrentEntity = (CurrentEntity)fCurrentEntityStack.pop();
}
next = true;
}
} while (next || complete);
return true;
} // scan(boolean):boolean
/**
* Scans the content of <noscript>: it doesn't get parsed but is considered as plain text
* when feature {@link HTMLScanner#PARSE_NOSCRIPT_CONTENT} is set to false.
* @param the tag for which content is scanned (one of "noscript" or "noframes")
* @throws IOException
*/
private void scanNoXxxContent(final String tagName) throws IOException {
final XMLStringBuffer buffer = new XMLStringBuffer();
final String end = "/" + tagName;
while (true) {
int c = fCurrentEntity.read();
if (c == -1) {
break;
}
if (c == '<') {
final String next = nextContent(10) + " ";
if (next.length() >= 10 && end.equalsIgnoreCase(next.substring(0, end.length()))
&& ('>' == next.charAt(9) || Character.isWhitespace(next.charAt(9)))) {
fCurrentEntity.rewind();
break;
}
}
if (c == '\r' || c == '\n') {
fCurrentEntity.rewind();
int newlines = skipNewlines();
for (int i = 0; i < newlines; i++) {
buffer.append('\n');
}
}
else {
buffer.append((char)c);
}
}
if (buffer.length > 0 && fDocumentHandler != null) {
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fDocumentHandler.characters(buffer, locationAugs());
}
}
private void scanScriptContent() throws IOException {
final XMLStringBuffer buffer = new XMLStringBuffer();
boolean waitForEndComment = false;
while (true) {
int c = fCurrentEntity.read();
if (c == -1) {
break;
}
else if (c == '-' && endsWith(buffer, "<!-"))
{
waitForEndComment = endCommentAvailable();
}
else if (!waitForEndComment && c == '<') {
final String next = nextContent(8) + " ";
if (next.length() >= 8 && "/script".equalsIgnoreCase(next.substring(0, 7))
&& ('>' == next.charAt(7) || Character.isWhitespace(next.charAt(7)))) {
fCurrentEntity.rewind();
break;
}
}
else if (c == '>' && endsWith(buffer, "--")) {
waitForEndComment = false;
}
if (c == '\r' || c == '\n') {
fCurrentEntity.rewind();
int newlines = skipNewlines();
for (int i = 0; i < newlines; i++) {
buffer.append('\n');
}
}
else {
buffer.append((char)c);
}
}
if (fScriptStripCommentDelims) {
reduceToContent(buffer, "<!--", "-->");
}
if (fScriptStripCDATADelims) {
reduceToContent(buffer, "<![CDATA[", "]]>");
}
if (buffer.length > 0 && fDocumentHandler != null && fElementCount >= fElementDepth) {
if (DEBUG_CALLBACKS) {
System.out.println("characters("+buffer+")");
}
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fDocumentHandler.characters(buffer, locationAugs());
}
}
/**
* Reads the next characters WITHOUT impacting the buffer content
* up to current offset.
* @param len the number of characters to read
* @return the read string (length may be smaller if EOF is encountered)
*/
protected String nextContent(int len) throws IOException {
final int originalOffset = fCurrentEntity.offset;
final int originalColumnNumber = fCurrentEntity.getColumnNumber();
final int originalCharacterOffset = fCurrentEntity.getCharacterOffset();
char[] buff = new char[len];
int nbRead = 0;
for (nbRead=0; nbRead<len; ++nbRead) {
// read() should not clear the buffer
if (fCurrentEntity.offset == fCurrentEntity.length) {
if (fCurrentEntity.length == fCurrentEntity.buffer.length) {
fCurrentEntity.load(fCurrentEntity.buffer.length);
}
else { // everything was already loaded
break;
}
}
int c = fCurrentEntity.read();
if (c == -1) {
break;
}
else {
buff[nbRead] = (char) c;
}
}
fCurrentEntity.restorePosition(originalOffset, originalColumnNumber, originalCharacterOffset);
return new String(buff, 0, nbRead);
}
//
// Protected methods
//
/** Scans characters. */
protected void scanCharacters() throws IOException {
fCurrentEntity.debugBufferIfNeeded("(scanCharacters: ");
fStringBuffer.clear();
while(true) {
int newlines = skipNewlines();
if (newlines == 0 && fCurrentEntity.offset == fCurrentEntity.length) {
fCurrentEntity.debugBufferIfNeeded(")scanCharacters: ");
break;
}
char c;
int offset = fCurrentEntity.offset - newlines;
for (int i = offset; i < fCurrentEntity.offset; i++) {
fCurrentEntity.buffer[i] = '\n';
}
while (fCurrentEntity.hasNext()) {
c = fCurrentEntity.getNextChar();
if (c == '<' || c == '&' || c == '\n' || c == '\r') {
fCurrentEntity.rewind();
break;
}
}
if (fCurrentEntity.offset > offset &&
fDocumentHandler != null && fElementCount >= fElementDepth) {
if (DEBUG_CALLBACKS) {
final XMLString xmlString = new XMLString(fCurrentEntity.buffer, offset, fCurrentEntity.offset - offset);
System.out.println("characters(" + xmlString + ")");
}
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fStringBuffer.append(fCurrentEntity.buffer, offset, fCurrentEntity.offset - offset);
}
fCurrentEntity.debugBufferIfNeeded(")scanCharacters: ");
boolean hasNext = fCurrentEntity.offset < fCurrentEntity.buffer.length;
int next = hasNext ? fCurrentEntity.getCurrentChar() : -1;
if(next == '&' || next == '<' || next == -1) {
break;
}
} //end while
if(fStringBuffer.length != 0) {
fDocumentHandler.characters(fStringBuffer, locationAugs());
}
} // scanCharacters()
/** Scans a CDATA section. */
protected void scanCDATA() throws IOException {
fCurrentEntity.debugBufferIfNeeded("(scanCDATA: ");
fStringBuffer.clear();
if (fCDATASections) {
if (fDocumentHandler != null && fElementCount >= fElementDepth) {
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
if (DEBUG_CALLBACKS) {
System.out.println("startCDATA()");
}
fDocumentHandler.startCDATA(locationAugs());
}
}
else {
fStringBuffer.append("[CDATA[");
}
boolean eof = scanMarkupContent(fStringBuffer, ']');
if (!fCDATASections) {
fStringBuffer.append("]]");
}
if (fDocumentHandler != null && fElementCount >= fElementDepth) {
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
if (fCDATASections) {
if (DEBUG_CALLBACKS) {
System.out.println("characters("+fStringBuffer+")");
}
fDocumentHandler.characters(fStringBuffer, locationAugs());
if (DEBUG_CALLBACKS) {
System.out.println("endCDATA()");
}
fDocumentHandler.endCDATA(locationAugs());
}
else {
if (DEBUG_CALLBACKS) {
System.out.println("comment("+fStringBuffer+")");
}
fDocumentHandler.comment(fStringBuffer, locationAugs());
}
}
fCurrentEntity.debugBufferIfNeeded(")scanCDATA: ");
if (eof) {
throw new EOFException();
}
} // scanCDATA()
/** Scans a comment. */
protected void scanComment() throws IOException {
fCurrentEntity.debugBufferIfNeeded("(scanComment: ");
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
XMLStringBuffer buffer = new XMLStringBuffer();
boolean eof = scanMarkupContent(buffer, '-');
// no --> found, comment with end only with >
if (eof) {
fCurrentEntity.resetBuffer(buffer, fEndLineNumber, fEndColumnNumber, fEndCharacterOffset);
buffer = new XMLStringBuffer(); // take a new one to avoid interactions
while (true) {
int c = fCurrentEntity.read();
if (c == -1) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1007", null);
}
eof = true;
break;
}
else if (c != '>') {
buffer.append((char)c);
continue;
}
else if (c == '\n' || c == '\r') {
fCurrentEntity.rewind();
int newlines = skipNewlines();
for (int i = 0; i < newlines; i++) {
buffer.append('\n');
}
continue;
}
eof = false;
break;
}
}
if (fDocumentHandler != null && fElementCount >= fElementDepth) {
if (DEBUG_CALLBACKS) {
System.out.println("comment(" + buffer + ")");
}
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fDocumentHandler.comment(buffer, locationAugs());
}
fCurrentEntity.debugBufferIfNeeded(")scanComment: ");
if (eof) {
throw new EOFException();
}
} // scanComment()
/** Scans markup content. */
protected boolean scanMarkupContent(XMLStringBuffer buffer,
char cend) throws IOException {
int c = -1;
OUTER: while (true) {
c = fCurrentEntity.read();
if (c == cend) {
int count = 1;
while (true) {
c = fCurrentEntity.read();
if (c == cend) {
count++;
continue;
}
break;
}
if (c == -1) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1007", null);
}
break OUTER;
}
if (count < 2) {
buffer.append(cend);
//if (c != -1) {
fCurrentEntity.rewind();
//}
continue;
}
if (c != '>') {
for (int i = 0; i < count; i++) {
buffer.append(cend);
}
fCurrentEntity.rewind();
continue;
}
for (int i = 0; i < count - 2; i++) {
buffer.append(cend);
}
break;
}
else if (c == '\n' || c == '\r') {
fCurrentEntity.rewind();
int newlines = skipNewlines();
for (int i = 0; i < newlines; i++) {
buffer.append('\n');
}
continue;
}
else if (c == -1) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1007", null);
}
break;
}
buffer.append((char)c);
}
return c == -1;
} // scanMarkupContent(XMLStringBuffer,char):boolean
/** Scans a processing instruction. */
protected void scanPI() throws IOException {
fCurrentEntity.debugBufferIfNeeded("(scanPI: ");
if (fReportErrors) {
fErrorReporter.reportWarning("HTML1008", null);
}
// scan processing instruction
String target = scanName();
if (target != null && !target.equalsIgnoreCase("xml")) {
while (true) {
int c = fCurrentEntity.read();
if (c == '\r' || c == '\n') {
if (c == '\r') {
c = fCurrentEntity.read();
if (c != '\n') {
fCurrentEntity.offset--;
fCurrentEntity.characterOffset_--;
}
}
fCurrentEntity.incLine();
continue;
}
if (c == -1) {
break;
}
if (c != ' ' && c != '\t') {
fCurrentEntity.rewind();
break;
}
}
fStringBuffer.clear();
while (true) {
int c = fCurrentEntity.read();
if (c == '?' || c == '/') {
char c0 = (char)c;
c = fCurrentEntity.read();
if (c == '>') {
break;
}
else {
fStringBuffer.append(c0);
fCurrentEntity.rewind();
continue;
}
}
else if (c == '\r' || c == '\n') {
fStringBuffer.append('\n');
if (c == '\r') {
c = fCurrentEntity.read();
if (c != '\n') {
fCurrentEntity.offset--;
fCurrentEntity.characterOffset_--;
}
}
fCurrentEntity.incLine();
continue;
}
else if (c == -1) {
break;
}
else {
fStringBuffer.append((char)c);
}
}
XMLString data = fStringBuffer;
if (fDocumentHandler != null) {
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fDocumentHandler.processingInstruction(target, data, locationAugs());
}
}
// scan xml/text declaration
else {
int beginLineNumber = fBeginLineNumber;
int beginColumnNumber = fBeginColumnNumber;
int beginCharacterOffset = fBeginCharacterOffset;
fAttributes.removeAllAttributes();
int aindex = 0;
while (scanPseudoAttribute(fAttributes)) {
// if we haven't scanned a value, remove the entry as values have special signification
if (fAttributes.getValue(aindex).length() == 0) {
fAttributes.removeAttributeAt(aindex);
}
else {
fAttributes.getName(aindex,fQName);
fQName.rawname = fQName.rawname.toLowerCase();
fAttributes.setName(aindex,fQName);
aindex++;
}
}
if (fDocumentHandler != null) {
String version = fAttributes.getValue("version");
String encoding = fAttributes.getValue("encoding");
String standalone = fAttributes.getValue("standalone");
// if the encoding is successfully changed, the stream will be processed again
// with the right encoding an we will come here again but without need to change the encoding
final boolean xmlDeclNow = fIgnoreSpecifiedCharset || !changeEncoding(encoding);
if (xmlDeclNow) {
fBeginLineNumber = beginLineNumber;
fBeginColumnNumber = beginColumnNumber;
fBeginCharacterOffset = beginCharacterOffset;
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fDocumentHandler.xmlDecl(version, encoding, standalone,
locationAugs());
}
}
}
fCurrentEntity.debugBufferIfNeeded(")scanPI: ");
} // scanPI()
/**
* Scans a start element.
*
* @param empty Is used for a second return value to indicate whether
* the start element tag is empty (e.g. "/>").
*/
protected String scanStartElement(boolean[] empty) throws IOException {
String ename = scanName();
int length = ename != null ? ename.length() : 0;
int c = length > 0 ? ename.charAt(0) : -1;
if (length == 0 || !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1009", null);
}
if (fDocumentHandler != null && fElementCount >= fElementDepth) {
fStringBuffer.clear();
fStringBuffer.append('<');
if (length > 0) {
fStringBuffer.append(ename);
}
fDocumentHandler.characters(fStringBuffer, null);
}
return null;
}
ename = modifyName(ename, fNamesElems);
fAttributes.removeAllAttributes();
int beginLineNumber = fBeginLineNumber;
int beginColumnNumber = fBeginColumnNumber;
int beginCharacterOffset = fBeginCharacterOffset;
while (scanAttribute(fAttributes, empty)) {
// do nothing
}
fBeginLineNumber = beginLineNumber;
fBeginColumnNumber = beginColumnNumber;
fBeginCharacterOffset = beginCharacterOffset;
if (fByteStream != null && fElementDepth == -1) {
if (ename.equalsIgnoreCase("META")) {
if (DEBUG_CHARSET) {
System.out.println("+++ <META>");
}
String httpEquiv = getValue(fAttributes, "http-equiv");
if (httpEquiv != null && httpEquiv.equalsIgnoreCase("content-type")) {
if (DEBUG_CHARSET) {
System.out.println("+++ @content-type: \""+httpEquiv+'"');
}
String content = getValue(fAttributes, "content");
if (content != null) {
content = removeSpaces(content);
int index1 = content.toLowerCase().indexOf("charset=");
if (index1 != -1 && !fIgnoreSpecifiedCharset) {
final int index2 = content.indexOf(';', index1);
final String charset = index2 != -1 ? content.substring(index1+8, index2) : content.substring(index1+8);
changeEncoding(charset);
}
}
}
}
else if (ename.equalsIgnoreCase("BODY")) {
fByteStream.clear();
fByteStream = null;
}
else {
HTMLElements.Element element = HTMLElements.getElement(ename);
if (element.parent != null && element.parent.length > 0) {
if (element.parent[0].code == HTMLElements.BODY) {
fByteStream.clear();
fByteStream = null;
}
}
}
}
if (fDocumentHandler != null && fElementCount >= fElementDepth) {
fQName.setValues(null, ename, ename, null);
if (DEBUG_CALLBACKS) {
System.out.println("startElement("+fQName+','+fAttributes+")");
}
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
if (empty[0]) {
fDocumentHandler.emptyElement(fQName, fAttributes, locationAugs());
}
else {
fDocumentHandler.startElement(fQName, fAttributes, locationAugs());
}
}
return ename;
} // scanStartElement():ename
/**
* Removes all spaces for the string (remember: JDK 1.3!)
*/
private String removeSpaces(final String content) {
StringBuffer sb = null;
for (int i=content.length()-1; i>=0; --i) {
if (Character.isWhitespace(content.charAt(i))) {
if (sb == null) {
sb = new StringBuffer(content);
}
sb.deleteCharAt(i);
}
}
return (sb == null) ? content : sb.toString();
}
/**
* Tries to change the encoding used to read the input stream to the specified one
* @param charset the charset that should be used
* @return <code>true</code> when the encoding has been changed
*/
private boolean changeEncoding(String charset) {
if (charset == null || fByteStream == null) {
return false;
}
charset = charset.trim();
boolean encodingChanged = false;
try {
String ianaEncoding = charset;
String javaEncoding = EncodingMap.getIANA2JavaMapping(ianaEncoding.toUpperCase());
if (DEBUG_CHARSET) {
System.out.println("+++ ianaEncoding: "+ianaEncoding);
System.out.println("+++ javaEncoding: "+javaEncoding);
}
if (javaEncoding == null) {
javaEncoding = ianaEncoding;
if (fReportErrors) {
fErrorReporter.reportError("HTML1001", new Object[]{ianaEncoding});
}
}
// patch: Marc Guillemot
if (!javaEncoding.equals(fJavaEncoding)) {
if (!isEncodingCompatible(javaEncoding, fJavaEncoding)) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1015", new Object[]{javaEncoding,fJavaEncoding});
}
}
// change the charset
else {
fIso8859Encoding = ianaEncoding == null
|| ianaEncoding.toUpperCase().startsWith("ISO-8859")
|| ianaEncoding.equalsIgnoreCase(fDefaultIANAEncoding);
fJavaEncoding = javaEncoding;
fCurrentEntity.setStream(new InputStreamReader(fByteStream, javaEncoding));
fByteStream.playback();
fElementDepth = fElementCount;
fElementCount = 0;
encodingChanged = true;
}
}
}
catch (UnsupportedEncodingException e) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1010", new Object[]{charset});
}
// NOTE: If the encoding change doesn't work,
// then there's no point in continuing to
// buffer the input stream.
fByteStream.clear();
fByteStream = null;
}
return encodingChanged;
}
/**
* Scans a real attribute.
*
* @param attributes The list of attributes.
* @param empty Is used for a second return value to indicate
* whether the start element tag is empty
* (e.g. "/>").
*/
protected boolean scanAttribute(XMLAttributesImpl attributes,
boolean[] empty)
throws IOException {
return scanAttribute(attributes,empty,'/');
} // scanAttribute(XMLAttributesImpl,boolean[]):boolean
/**
* Scans a pseudo attribute.
*
* @param attributes The list of attributes.
*/
protected boolean scanPseudoAttribute(XMLAttributesImpl attributes)
throws IOException {
return scanAttribute(attributes,fSingleBoolean,'?');
} // scanPseudoAttribute(XMLAttributesImpl):boolean
/**
* Scans an attribute, pseudo or real.
*
* @param attributes The list of attributes.
* @param empty Is used for a second return value to indicate
* whether the start element tag is empty
* (e.g. "/>").
* @param endc The end character that appears before the
* closing angle bracket ('>').
*/
protected boolean scanAttribute(XMLAttributesImpl attributes,
boolean[] empty, char endc)
throws IOException {
boolean skippedSpaces = skipSpaces();
fBeginLineNumber = fCurrentEntity.getLineNumber();
fBeginColumnNumber = fCurrentEntity.getColumnNumber();
fBeginCharacterOffset = fCurrentEntity.getCharacterOffset();
int c = fCurrentEntity.read();
if (c == -1) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1007", null);
}
return false;
}
else if (c == '>') {
return false;
}
else if (c == '<') {
fCurrentEntity.rewind();
return false;
}
fCurrentEntity.rewind();
String aname = scanName();
if (aname == null) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1011", null);
}
empty[0] = skipMarkup(false);
return false;
}
if (!skippedSpaces && fReportErrors) {
fErrorReporter.reportError("HTML1013", new Object[] { aname });
}
aname = modifyName(aname, fNamesAttrs);
skipSpaces();
c = fCurrentEntity.read();
if (c == -1) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1007", null);
}
throw new EOFException();
}
if (c == '/' || c == '>') {
fQName.setValues(null, aname, aname, null);
attributes.addAttribute(fQName, "CDATA", "");
attributes.setSpecified(attributes.getLength()-1, true);
if (fAugmentations) {
addLocationItem(attributes, attributes.getLength() - 1);
}
if (c == '/') {
fCurrentEntity.rewind();
empty[0] = skipMarkup(false);
}
return false;
}
/***
// REVISIT: [Q] Why is this still here? -Ac
if (c == '/' || c == '>') {
if (c == '/') {
fCurrentEntity.offset--;
fCurrentEntity.columnNumber--;
empty[0] = skipMarkup(false);
}
fQName.setValues(null, aname, aname, null);
attributes.addAttribute(fQName, "CDATA", "");
attributes.setSpecified(attributes.getLength()-1, true);
if (fAugmentations) {
addLocationItem(attributes, attributes.getLength() - 1);
}
return false;
}
/***/
if (c == '=') {
skipSpaces();
c = fCurrentEntity.read();
if (c == -1) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1007", null);
}
throw new EOFException();
}
// Xiaowei/Ac: Fix for <a href=/cgi-bin/myscript>...</a>
if (c == '>') {
fQName.setValues(null, aname, aname, null);
attributes.addAttribute(fQName, "CDATA", "");
attributes.setSpecified(attributes.getLength()-1, true);
if (fAugmentations) {
addLocationItem(attributes, attributes.getLength() - 1);
}
return false;
}
fStringBuffer.clear();
fNonNormAttr.clear();
if (c != '\'' && c != '"') {
fCurrentEntity.rewind();
while (true) {
c = fCurrentEntity.read();
// Xiaowei/Ac: Fix for <a href=/broken/>...</a>
if (Character.isWhitespace((char)c) || c == '>') {
//fCharOffset--;
fCurrentEntity.rewind();
break;
}
if (c == -1) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1007", null);
}
throw new EOFException();
}
if (c == '&') {
int ce = scanEntityRef(fStringBuffer2, false);
if (ce != -1) {
fStringBuffer.append((char)ce);
}
else {
fStringBuffer.append(fStringBuffer2);
}
fNonNormAttr.append(fStringBuffer2);
}
else {
fStringBuffer.append((char)c);
fNonNormAttr.append((char)c);
}
}
fQName.setValues(null, aname, aname, null);
String avalue = fStringBuffer.toString();
attributes.addAttribute(fQName, "CDATA", avalue);
int lastattr = attributes.getLength()-1;
attributes.setSpecified(lastattr, true);
attributes.setNonNormalizedValue(lastattr, fNonNormAttr.toString());
if (fAugmentations) {
addLocationItem(attributes, attributes.getLength() - 1);
}
return true;
}
char quote = (char)c;
boolean isStart = true;
boolean prevSpace = false;
do {
boolean acceptSpace = !fNormalizeAttributes || (!isStart && !prevSpace);
c = fCurrentEntity.read();
if (c == -1) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1007", null);
}
break;
// throw new EOFException();
}
if (c == '&') {
isStart = false;
int ce = scanEntityRef(fStringBuffer2, false);
if (ce != -1) {
fStringBuffer.append((char)ce);
}
else {
fStringBuffer.append(fStringBuffer2);
}
fNonNormAttr.append(fStringBuffer2);
}
else if (c == ' ' || c == '\t') {
if (acceptSpace) {
fStringBuffer.append(fNormalizeAttributes ? ' ' : (char)c);
}
fNonNormAttr.append((char)c);
}
else if (c == '\r' || c == '\n') {
if (c == '\r') {
int c2 = fCurrentEntity.read();
if (c2 != '\n') {
fCurrentEntity.rewind();
}
else {
fNonNormAttr.append('\r');
c = c2;
}
}
if (acceptSpace) {
fStringBuffer.append(fNormalizeAttributes ? ' ' : '\n');
}
fCurrentEntity.incLine();
fNonNormAttr.append((char)c);
}
else if (c != quote) {
isStart = false;
fStringBuffer.append((char)c);
fNonNormAttr.append((char)c);
}
prevSpace = c == ' ' || c == '\t' || c == '\r' || c == '\n';
isStart = isStart && prevSpace;
} while (c != quote);
if (fNormalizeAttributes && fStringBuffer.length > 0) {
// trailing whitespace already normalized to single space
if (fStringBuffer.ch[fStringBuffer.length - 1] == ' ') {
fStringBuffer.length--;
}
}
fQName.setValues(null, aname, aname, null);
String avalue = fStringBuffer.toString();
attributes.addAttribute(fQName, "CDATA", avalue);
int lastattr = attributes.getLength()-1;
attributes.setSpecified(lastattr, true);
attributes.setNonNormalizedValue(lastattr, fNonNormAttr.toString());
if (fAugmentations) {
addLocationItem(attributes, attributes.getLength() - 1);
}
}
else {
fQName.setValues(null, aname, aname, null);
attributes.addAttribute(fQName, "CDATA", "");
attributes.setSpecified(attributes.getLength()-1, true);
fCurrentEntity.rewind();
if (fAugmentations) {
addLocationItem(attributes, attributes.getLength() - 1);
}
}
return true;
} // scanAttribute(XMLAttributesImpl):boolean
/** Adds location augmentations to the specified attribute. */
protected void addLocationItem(XMLAttributes attributes, int index) {
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
LocationItem locationItem = new LocationItem();
locationItem.setValues(fBeginLineNumber, fBeginColumnNumber,
fBeginCharacterOffset, fEndLineNumber,
fEndColumnNumber, fEndCharacterOffset);
Augmentations augs = attributes.getAugmentations(index);
augs.putItem(AUGMENTATIONS, locationItem);
} // addLocationItem(XMLAttributes,int)
/** Scans an end element. */
protected void scanEndElement() throws IOException {
String ename = scanName();
if (fReportErrors && ename == null) {
fErrorReporter.reportError("HTML1012", null);
}
skipMarkup(false);
if (ename != null) {
ename = modifyName(ename, fNamesElems);
if (fDocumentHandler != null && fElementCount >= fElementDepth) {
fQName.setValues(null, ename, ename, null);
if (DEBUG_CALLBACKS) {
System.out.println("endElement("+fQName+")");
}
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fDocumentHandler.endElement(fQName, locationAugs());
}
}
} // scanEndElement()
//
// Private methods
//
/**
* Returns true if the given element has an end-tag.
*/
private boolean isEnded(String ename) {
String content = new String(fCurrentEntity.buffer, fCurrentEntity.offset,
fCurrentEntity.length - fCurrentEntity.offset);
return content.toLowerCase().indexOf("</" + ename.toLowerCase() + ">") != -1;
}
} // class ContentScanner
/**
* Special scanner used for elements whose content needs to be scanned
* as plain text, ignoring markup such as elements and entity references.
* For example: <SCRIPT> and <COMMENT>.
*
* @author Andy Clark
*/
public class SpecialScanner
implements Scanner {
//
// Data
//
/** Name of element whose content needs to be scanned as text. */
protected String fElementName;
/** True if <style> element. */
protected boolean fStyle;
/** True if <textarea> element. */
protected boolean fTextarea;
/** True if <title> element. */
protected boolean fTitle;
// temp vars
/** A qualified name. */
private final QName fQName = new QName();
/** A string buffer. */
private final XMLStringBuffer fStringBuffer = new XMLStringBuffer();
//
// Public methods
//
/** Sets the element name. */
public Scanner setElementName(String ename) {
fElementName = ename;
fStyle = fElementName.equalsIgnoreCase("STYLE");
fTextarea = fElementName.equalsIgnoreCase("TEXTAREA");
fTitle = fElementName.equalsIgnoreCase("TITLE");
return this;
} // setElementName(String):Scanner
//
// Scanner methods
//
/** Scan. */
public boolean scan(boolean complete) throws IOException {
boolean next;
do {
try {
next = false;
switch (fScannerState) {
case STATE_CONTENT: {
fBeginLineNumber = fCurrentEntity.getLineNumber();
fBeginColumnNumber = fCurrentEntity.getColumnNumber();
fBeginCharacterOffset = fCurrentEntity.getCharacterOffset();
int c = fCurrentEntity.read();
if (c == '<') {
setScannerState(STATE_MARKUP_BRACKET);
continue;
}
if (c == '&') {
if (fTextarea || fTitle) {
scanEntityRef(fStringBuffer, true);
continue;
}
fStringBuffer.clear();
fStringBuffer.append('&');
}
else if (c == -1) {
if (fReportErrors) {
fErrorReporter.reportError("HTML1007", null);
}
throw new EOFException();
}
else {
fCurrentEntity.rewind();
fStringBuffer.clear();
}
scanCharacters(fStringBuffer, -1);
break;
} // case STATE_CONTENT
case STATE_MARKUP_BRACKET: {
int delimiter = -1;
int c = fCurrentEntity.read();
if (c == '/') {
String ename = scanName();
if (ename != null) {
if (ename.equalsIgnoreCase(fElementName)) {
if (fCurrentEntity.read() == '>') {
ename = modifyName(ename, fNamesElems);
if (fDocumentHandler != null && fElementCount >= fElementDepth) {
fQName.setValues(null, ename, ename, null);
if (DEBUG_CALLBACKS) {
System.out.println("endElement("+fQName+")");
}
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fDocumentHandler.endElement(fQName, locationAugs());
}
setScanner(fContentScanner);
setScannerState(STATE_CONTENT);
return true;
}
else {
fCurrentEntity.rewind();
}
}
fStringBuffer.clear();
fStringBuffer.append("</");
fStringBuffer.append(ename);
}
else {
fStringBuffer.clear();
fStringBuffer.append("</");
}
}
else {
fStringBuffer.clear();
fStringBuffer.append('<');
fStringBuffer.append((char)c);
}
scanCharacters(fStringBuffer, delimiter);
setScannerState(STATE_CONTENT);
break;
} // case STATE_MARKUP_BRACKET
} // switch
} // try
catch (EOFException e) {
setScanner(fContentScanner);
if (fCurrentEntityStack.empty()) {
setScannerState(STATE_END_DOCUMENT);
}
else {
fCurrentEntity = (CurrentEntity)fCurrentEntityStack.pop();
setScannerState(STATE_CONTENT);
}
return true;
}
} // do
while (next || complete);
return true;
} // scan(boolean):boolean
//
// Protected methods
//
/** Scan characters. */
protected void scanCharacters(XMLStringBuffer buffer,
int delimiter) throws IOException {
fCurrentEntity.debugBufferIfNeeded("(scanCharacters, delimiter="+delimiter+": ");
while (true) {
int c = fCurrentEntity.read();
if (c == -1 || (c == '<' || c == '&')) {
if (c != -1) {
fCurrentEntity.rewind();
}
break;
}
// Patch supplied by Jonathan Baxter
else if (c == '\r' || c == '\n') {
fCurrentEntity.rewind();
int newlines = skipNewlines();
for (int i = 0; i < newlines; i++) {
buffer.append('\n');
}
}
else {
buffer.append((char)c);
if (c == '\n') {
fCurrentEntity.incLine();
}
}
}
if (fStyle) {
if (fStyleStripCommentDelims) {
reduceToContent(buffer, "<!--", "-->");
}
if (fStyleStripCDATADelims) {
reduceToContent(buffer, "<![CDATA[", "]]>");
}
}
if (buffer.length > 0 && fDocumentHandler != null && fElementCount >= fElementDepth) {
if (DEBUG_CALLBACKS) {
System.out.println("characters("+buffer+")");
}
fEndLineNumber = fCurrentEntity.getLineNumber();
fEndColumnNumber = fCurrentEntity.getColumnNumber();
fEndCharacterOffset = fCurrentEntity.getCharacterOffset();
fDocumentHandler.characters(buffer, locationAugs());
}
fCurrentEntity.debugBufferIfNeeded(")scanCharacters: ");
} // scanCharacters(StringBuffer)
} // class SpecialScanner
/**
* A playback input stream. This class has the ability to save the bytes
* read from the underlying input stream and play the bytes back later.
* This class is used by the HTML scanner to switch encodings when a
* <meta> tag is detected that specifies a different encoding.
* <p>
* If the encoding is changed, then the scanner calls the
* <code>playback</code> method and re-scans the beginning of the HTML
* document again. This should not be too much of a performance problem
* because the <meta> tag appears at the beginning of the document.
* <p>
* If the <body> tag is reached without playing back the bytes,
* then the buffer can be cleared by calling the <code>clear</code>
* method. This stops the buffering of bytes and allows the memory used
* by the buffer to be reclaimed.
* <p>
* <strong>Note:</strong>
* If the buffer is never played back or cleared, this input stream
* will continue to buffer the entire stream. Therefore, it is very
* important to use this stream correctly.
*
* @author Andy Clark
*/
public static class PlaybackInputStream
extends FilterInputStream {
//
// Constants
//
/** Set to true to debug playback. */
private static final boolean DEBUG_PLAYBACK = false;
//
// Data
//
// state
/** Playback mode. */
protected boolean fPlayback = false;
/** Buffer cleared. */
protected boolean fCleared = false;
/** Encoding detected. */
protected boolean fDetected = false;
// buffer info
/** Byte buffer. */
protected byte[] fByteBuffer = new byte[1024];
/** Offset into byte buffer during playback. */
protected int fByteOffset = 0;
/** Length of bytes read into byte buffer. */
protected int fByteLength = 0;
/** Pushback offset. */
public int fPushbackOffset = 0;
/** Pushback length. */
public int fPushbackLength = 0;
//
// Constructors
//
/** Constructor. */
public PlaybackInputStream(InputStream in) {
super(in);
} // <init>(InputStream)
//
// Public methods
//
/** Detect encoding. */
public void detectEncoding(String[] encodings) throws IOException {
if (fDetected) {
throw new IOException("Should not detect encoding twice.");
}
fDetected = true;
int b1 = read();
if (b1 == -1) {
return;
}
int b2 = read();
if (b2 == -1) {
fPushbackLength = 1;
return;
}
// UTF-8 BOM: 0xEFBBBF
if (b1 == 0xEF && b2 == 0xBB) {
int b3 = read();
if (b3 == 0xBF) {
fPushbackOffset = 3;
encodings[0] = "UTF-8";
encodings[1] = "UTF8";
return;
}
fPushbackLength = 3;
}
// UTF-16 LE BOM: 0xFFFE
if (b1 == 0xFF && b2 == 0xFE) {
encodings[0] = "UTF-16";
encodings[1] = "UnicodeLittleUnmarked";
return;
}
// UTF-16 BE BOM: 0xFEFF
else if (b1 == 0xFE && b2 == 0xFF) {
encodings[0] = "UTF-16";
encodings[1] = "UnicodeBigUnmarked";
return;
}
// unknown
fPushbackLength = 2;
} // detectEncoding()
/** Playback buffer contents. */
public void playback() {
fPlayback = true;
} // playback()
/**
* Clears the buffer.
* <p>
* <strong>Note:</strong>
* The buffer cannot be cleared during playback. Therefore, calling
* this method during playback will not do anything. However, the
* buffer will be cleared automatically at the end of playback.
*/
public void clear() {
if (!fPlayback) {
fCleared = true;
fByteBuffer = null;
}
} // clear()
//
// InputStream methods
//
/** Read a byte. */
public int read() throws IOException {
if (DEBUG_PLAYBACK) {
System.out.println("(read");
}
if (fPushbackOffset < fPushbackLength) {
return fByteBuffer[fPushbackOffset++];
}
if (fCleared) {
return in.read();
}
if (fPlayback) {
int c = fByteBuffer[fByteOffset++];
if (fByteOffset == fByteLength) {
fCleared = true;
fByteBuffer = null;
}
if (DEBUG_PLAYBACK) {
System.out.println(")read -> "+(char)c);
}
return c;
}
int c = in.read();
if (c != -1) {
if (fByteLength == fByteBuffer.length) {
byte[] newarray = new byte[fByteLength + 1024];
System.arraycopy(fByteBuffer, 0, newarray, 0, fByteLength);
fByteBuffer = newarray;
}
fByteBuffer[fByteLength++] = (byte)c;
}
if (DEBUG_PLAYBACK) {
System.out.println(")read -> "+(char)c);
}
return c;
} // read():int
/** Read an array of bytes. */
public int read(byte[] array) throws IOException {
return read(array, 0, array.length);
} // read(byte[]):int
/** Read an array of bytes. */
public int read(byte[] array, int offset, int length) throws IOException {
if (DEBUG_PLAYBACK) {
System.out.println(")read("+offset+','+length+')');
}
if (fPushbackOffset < fPushbackLength) {
int count = fPushbackLength - fPushbackOffset;
if (count > length) {
count = length;
}
System.arraycopy(fByteBuffer, fPushbackOffset, array, offset, count);
fPushbackOffset += count;
return count;
}
if (fCleared) {
return in.read(array, offset, length);
}
if (fPlayback) {
if (fByteOffset + length > fByteLength) {
length = fByteLength - fByteOffset;
}
System.arraycopy(fByteBuffer, fByteOffset, array, offset, length);
fByteOffset += length;
if (fByteOffset == fByteLength) {
fCleared = true;
fByteBuffer = null;
}
return length;
}
int count = in.read(array, offset, length);
if (count != -1) {
if (fByteLength + count > fByteBuffer.length) {
byte[] newarray = new byte[fByteLength + count + 512];
System.arraycopy(fByteBuffer, 0, newarray, 0, fByteLength);
fByteBuffer = newarray;
}
System.arraycopy(array, offset, fByteBuffer, fByteLength, count);
fByteLength += count;
}
if (DEBUG_PLAYBACK) {
System.out.println(")read("+offset+','+length+") -> "+count);
}
return count;
} // read(byte[]):int
} // class PlaybackInputStream
/**
* Location infoset item.
*
* @author Andy Clark
*/
protected static class LocationItem implements HTMLEventInfo, Cloneable {
//
// Data
//
/** Beginning line number. */
protected int fBeginLineNumber;
/** Beginning column number. */
protected int fBeginColumnNumber;
/** Beginning character offset. */
protected int fBeginCharacterOffset;
/** Ending line number. */
protected int fEndLineNumber;
/** Ending column number. */
protected int fEndColumnNumber;
/** Ending character offset. */
protected int fEndCharacterOffset;
//
// Public methods
//
public LocationItem() {
// nothing
}
LocationItem(final LocationItem other) {
setValues(other.fBeginLineNumber, other.fBeginColumnNumber, other.fBeginCharacterOffset,
other.fEndLineNumber, other.fEndColumnNumber, other.fEndCharacterOffset);
}
/** Sets the values of this item. */
public void setValues(int beginLine, int beginColumn, int beginOffset,
int endLine, int endColumn, int endOffset) {
fBeginLineNumber = beginLine;
fBeginColumnNumber = beginColumn;
fBeginCharacterOffset = beginOffset;
fEndLineNumber = endLine;
fEndColumnNumber = endColumn;
fEndCharacterOffset = endOffset;
} // setValues(int,int,int,int)
//
// HTMLEventInfo methods
//
// location information
/** Returns the line number of the beginning of this event.*/
public int getBeginLineNumber() {
return fBeginLineNumber;
} // getBeginLineNumber():int
/** Returns the column number of the beginning of this event.*/
public int getBeginColumnNumber() {
return fBeginColumnNumber;
} // getBeginColumnNumber():int
/** Returns the character offset of the beginning of this event.*/
public int getBeginCharacterOffset() {
return fBeginCharacterOffset;
} // getBeginCharacterOffset():int
/** Returns the line number of the end of this event.*/
public int getEndLineNumber() {
return fEndLineNumber;
} // getEndLineNumber():int
/** Returns the column number of the end of this event.*/
public int getEndColumnNumber() {
return fEndColumnNumber;
} // getEndColumnNumber():int
/** Returns the character offset of the end of this event.*/
public int getEndCharacterOffset() {
return fEndCharacterOffset;
} // getEndCharacterOffset():int
// other information
/** Returns true if this corresponding event was synthesized. */
public boolean isSynthesized() {
return false;
} // isSynthesize():boolean
//
// Object methods
//
/** Returns a string representation of this object. */
public String toString() {
StringBuffer str = new StringBuffer();
str.append(fBeginLineNumber);
str.append(':');
str.append(fBeginColumnNumber);
str.append(':');
str.append(fBeginCharacterOffset);
str.append(':');
str.append(fEndLineNumber);
str.append(':');
str.append(fEndColumnNumber);
str.append(':');
str.append(fEndCharacterOffset);
return str.toString();
} // toString():String
} // class LocationItem
/**
* To detect if 2 encoding are compatible, both must be able to read the meta tag specifying
* the new encoding. This means that the byte representation of some minimal html markup must
* be the same in both encodings
*/
boolean isEncodingCompatible(final String encoding1, final String encoding2) {
final String reference = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=";
try {
final byte[] bytesEncoding1 = reference.getBytes(encoding1);
final String referenceWithEncoding2 = new String(bytesEncoding1, encoding2);
return reference.equals(referenceWithEncoding2);
}
catch (final UnsupportedEncodingException e) {
return false;
}
}
private boolean endsWith(final XMLStringBuffer buffer, final String string) {
final int l = string.length();
if (buffer.length < l) {
return false;
}
else {
final String s = new String(buffer.ch, buffer.length-l, l);
return string.equals(s);
}
}
/** Reads a single character, preserving the old buffer content */
protected int readPreservingBufferContent() throws IOException {
fCurrentEntity.debugBufferIfNeeded("(read: ");
if (fCurrentEntity.offset == fCurrentEntity.length) {
if (fCurrentEntity.load(fCurrentEntity.length) < 1) {
if (DEBUG_BUFFER) {
System.out.println(")read: -> -1");
}
return -1;
}
}
final char c = fCurrentEntity.getNextChar();
fCurrentEntity.debugBufferIfNeeded(")read: ", " -> " + c);
return c;
} // readPreservingBufferContent():int
/**
* Indicates if the end comment --> is available, loading further data if needed, without to reset the buffer
*/
private boolean endCommentAvailable() throws IOException {
int nbCaret = 0;
final int originalOffset = fCurrentEntity.offset;
final int originalColumnNumber = fCurrentEntity.getColumnNumber();
final int originalCharacterOffset = fCurrentEntity.getCharacterOffset();
while (true) {
int c = readPreservingBufferContent();
if (c == -1) {
fCurrentEntity.restorePosition(originalOffset, originalColumnNumber, originalCharacterOffset);
return false;
}
else if (c == '>' && nbCaret >= 2) {
fCurrentEntity.restorePosition(originalOffset, originalColumnNumber, originalCharacterOffset);
return true;
}
else if (c == '-') {
nbCaret++;
}
else {
nbCaret = 0;
}
}
}
/**
* Reduces the buffer to the content between start and end marker when
* only whitespaces are found before the startMarker as well as after the end marker
*/
static void reduceToContent(final XMLStringBuffer buffer, final String startMarker, final String endMarker) {
int i = 0;
int startContent = -1;
final int l1 = startMarker.length();
final int l2 = endMarker.length();
while (i < buffer.length - l1 - l2) {
final char c = buffer.ch[buffer.offset+i];
if (Character.isWhitespace(c)) {
++i;
}
else if (c == startMarker.charAt(0)
&& startMarker.equals(new String(buffer.ch, buffer.offset+i, l1))) {
startContent = buffer.offset + i + l1;
break;
}
else {
return; // start marker not found
}
}
if (startContent == -1) { // start marker not found
return;
}
i = buffer.length - 1;
while (i > startContent + l2) {
final char c = buffer.ch[buffer.offset+i];
if (Character.isWhitespace(c)) {
--i;
}
else if (c == endMarker.charAt(l2-1)
&& endMarker.equals(new String(buffer.ch, buffer.offset+i-l2+1, l2))) {
buffer.length = buffer.offset + i - startContent - 2;
buffer.offset = startContent;
return;
}
else {
return; // start marker not found
}
}
}
} // class HTMLScanner
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/HTMLScanner.java | Java | art | 139,835 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.Vector;
import org.apache.xerces.util.DefaultErrorHandler;
import org.apache.xerces.util.ParserConfigurationSettings;
import org.apache.xerces.xni.XMLDTDContentModelHandler;
import org.apache.xerces.xni.XMLDTDHandler;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import org.apache.xerces.xni.parser.XMLDocumentSource;
import org.apache.xerces.xni.parser.XMLEntityResolver;
import org.apache.xerces.xni.parser.XMLErrorHandler;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.apache.xerces.xni.parser.XMLParseException;
import org.apache.xerces.xni.parser.XMLPullParserConfiguration;
import org.cyberneko.html.filters.NamespaceBinder;
import org.cyberneko.html.xercesbridge.XercesBridge;
/**
* An XNI-based parser configuration that can be used to parse HTML
* documents. This configuration can be used directly in order to
* parse HTML documents or can be used in conjunction with any XNI
* based tools, such as the Xerces2 implementation.
* <p>
* This configuration recognizes the following features:
* <ul>
* <li>http://cyberneko.org/html/features/augmentations
* <li>http://cyberneko.org/html/features/report-errors
* <li>http://cyberneko.org/html/features/report-errors/simple
* <li>http://cyberneko.org/html/features/balance-tags
* <li><i>and</i>
* <li>the features supported by the scanner and tag balancer components.
* </ul>
* <p>
* This configuration recognizes the following properties:
* <ul>
* <li>http://cyberneko.org/html/properties/names/elems
* <li>http://cyberneko.org/html/properties/names/attrs
* <li>http://cyberneko.org/html/properties/filters
* <li>http://cyberneko.org/html/properties/error-reporter
* <li><i>and</i>
* <li>the properties supported by the scanner and tag balancer.
* </ul>
* <p>
* For complete usage information, refer to the documentation.
*
* @see HTMLScanner
* @see HTMLTagBalancer
* @see HTMLErrorReporter
*
* @author Andy Clark
*
* @version $Id: HTMLConfiguration.java,v 1.9 2005/02/14 03:56:54 andyc Exp $
*/
public class HTMLConfiguration
extends ParserConfigurationSettings
implements XMLPullParserConfiguration {
//
// Constants
//
// features
/** Namespaces. */
protected static final String NAMESPACES = "http://xml.org/sax/features/namespaces";
/** Include infoset augmentations. */
protected static final String AUGMENTATIONS = "http://cyberneko.org/html/features/augmentations";
/** Report errors. */
protected static final String REPORT_ERRORS = "http://cyberneko.org/html/features/report-errors";
/** Simple report format. */
protected static final String SIMPLE_ERROR_FORMAT = "http://cyberneko.org/html/features/report-errors/simple";
/** Balance tags. */
protected static final String BALANCE_TAGS = "http://cyberneko.org/html/features/balance-tags";
// properties
/** Modify HTML element names: { "upper", "lower", "default" }. */
protected static final String NAMES_ELEMS = "http://cyberneko.org/html/properties/names/elems";
/** Modify HTML attribute names: { "upper", "lower", "default" }. */
protected static final String NAMES_ATTRS = "http://cyberneko.org/html/properties/names/attrs";
/** Pipeline filters. */
protected static final String FILTERS = "http://cyberneko.org/html/properties/filters";
/** Error reporter. */
protected static final String ERROR_REPORTER = "http://cyberneko.org/html/properties/error-reporter";
// other
/** Error domain. */
protected static final String ERROR_DOMAIN = "http://cyberneko.org/html";
// private
/** Document source class array. */
private static final Class[] DOCSOURCE = { XMLDocumentSource.class };
//
// Data
//
// handlers
/** Document handler. */
protected XMLDocumentHandler fDocumentHandler;
/** DTD handler. */
protected XMLDTDHandler fDTDHandler;
/** DTD content model handler. */
protected XMLDTDContentModelHandler fDTDContentModelHandler;
/** Error handler. */
protected XMLErrorHandler fErrorHandler = new DefaultErrorHandler();
// other settings
/** Entity resolver. */
protected XMLEntityResolver fEntityResolver;
/** Locale. */
protected Locale fLocale = Locale.getDefault();
// state
/**
* Stream opened by parser. Therefore, must close stream manually upon
* termination of parsing.
*/
protected boolean fCloseStream;
// components
/** Components. */
protected final Vector fHTMLComponents = new Vector(2);
// pipeline
/** Document scanner. */
protected final HTMLScanner fDocumentScanner = createDocumentScanner();
/** HTML tag balancer. */
protected final HTMLTagBalancer fTagBalancer = new HTMLTagBalancer();
/** Namespace binder. */
protected final NamespaceBinder fNamespaceBinder = new NamespaceBinder();
// other components
/** Error reporter. */
protected final HTMLErrorReporter fErrorReporter = new ErrorReporter();
// HACK: workarounds Xerces 2.0.x problems
/** Parser version is Xerces 2.0.0. */
protected static boolean XERCES_2_0_0 = false;
/** Parser version is Xerces 2.0.1. */
protected static boolean XERCES_2_0_1 = false;
/** Parser version is XML4J 4.0.x. */
protected static boolean XML4J_4_0_x = false;
//
// Static initializer
//
static {
try {
String VERSION = "org.apache.xerces.impl.Version";
Object version = ObjectFactory.createObject(VERSION, VERSION);
java.lang.reflect.Field field = version.getClass().getField("fVersion");
String versionStr = String.valueOf(field.get(version));
XERCES_2_0_0 = versionStr.equals("Xerces-J 2.0.0");
XERCES_2_0_1 = versionStr.equals("Xerces-J 2.0.1");
XML4J_4_0_x = versionStr.startsWith("XML4J 4.0.");
}
catch (Throwable e) {
// ignore
}
} // <clinit>()
//
// Constructors
//
/** Default constructor. */
public HTMLConfiguration() {
// add components
addComponent(fDocumentScanner);
addComponent(fTagBalancer);
addComponent(fNamespaceBinder);
//
// features
//
// recognized features
String VALIDATION = "http://xml.org/sax/features/validation";
String[] recognizedFeatures = {
AUGMENTATIONS,
NAMESPACES,
VALIDATION,
REPORT_ERRORS,
SIMPLE_ERROR_FORMAT,
BALANCE_TAGS,
};
addRecognizedFeatures(recognizedFeatures);
setFeature(AUGMENTATIONS, false);
setFeature(NAMESPACES, true);
setFeature(VALIDATION, false);
setFeature(REPORT_ERRORS, false);
setFeature(SIMPLE_ERROR_FORMAT, false);
setFeature(BALANCE_TAGS, true);
// HACK: Xerces 2.0.0
if (XERCES_2_0_0) {
// NOTE: These features should not be required but it causes a
// problem if they're not there. This will be fixed in
// subsequent releases of Xerces.
recognizedFeatures = new String[] {
"http://apache.org/xml/features/scanner/notify-builtin-refs",
};
addRecognizedFeatures(recognizedFeatures);
}
// HACK: Xerces 2.0.1
if (XERCES_2_0_0 || XERCES_2_0_1 || XML4J_4_0_x) {
// NOTE: These features should not be required but it causes a
// problem if they're not there. This should be fixed in
// subsequent releases of Xerces.
recognizedFeatures = new String[] {
"http://apache.org/xml/features/validation/schema/normalized-value",
"http://apache.org/xml/features/scanner/notify-char-refs",
};
addRecognizedFeatures(recognizedFeatures);
}
//
// properties
//
// recognized properties
String[] recognizedProperties = {
NAMES_ELEMS,
NAMES_ATTRS,
FILTERS,
ERROR_REPORTER,
};
addRecognizedProperties(recognizedProperties);
setProperty(NAMES_ELEMS, "upper");
setProperty(NAMES_ATTRS, "lower");
setProperty(ERROR_REPORTER, fErrorReporter);
// HACK: Xerces 2.0.0
if (XERCES_2_0_0) {
// NOTE: This is a hack to get around a problem in the Xerces 2.0.0
// AbstractSAXParser. If it uses a parser configuration that
// does not have a SymbolTable, then it will remove *all*
// attributes. This will be fixed in subsequent releases of
// Xerces.
String SYMBOL_TABLE = "http://apache.org/xml/properties/internal/symbol-table";
recognizedProperties = new String[] {
SYMBOL_TABLE,
};
addRecognizedProperties(recognizedProperties);
Object symbolTable = ObjectFactory.createObject("org.apache.xerces.util.SymbolTable",
"org.apache.xerces.util.SymbolTable");
setProperty(SYMBOL_TABLE, symbolTable);
}
} // <init>()
protected HTMLScanner createDocumentScanner() {
return new HTMLScanner();
}
//
// Public methods
//
/**
* Pushes an input source onto the current entity stack. This
* enables the scanner to transparently scan new content (e.g.
* the output written by an embedded script). At the end of the
* current entity, the scanner returns where it left off at the
* time this entity source was pushed.
* <p>
* <strong>Hint:</strong>
* To use this feature to insert the output of <SCRIPT>
* tags, remember to buffer the <em>entire</em> output of the
* processed instructions before pushing a new input source.
* Otherwise, events may appear out of sequence.
*
* @param inputSource The new input source to start scanning.
* @see #evaluateInputSource(XMLInputSource)
*/
public void pushInputSource(XMLInputSource inputSource) {
fDocumentScanner.pushInputSource(inputSource);
} // pushInputSource(XMLInputSource)
/**
* <font color="red">EXPERIMENTAL: may change in next release</font><br/>
* Immediately evaluates an input source and add the new content (e.g.
* the output written by an embedded script).
*
* @param inputSource The new input source to start scanning.
* @see #pushInputSource(XMLInputSource)
*/
public void evaluateInputSource(XMLInputSource inputSource) {
fDocumentScanner.evaluateInputSource(inputSource);
} // evaluateInputSource(XMLInputSource)
// XMLParserConfiguration methods
//
/** Sets a feature. */
public void setFeature(String featureId, boolean state)
throws XMLConfigurationException {
super.setFeature(featureId, state);
int size = fHTMLComponents.size();
for (int i = 0; i < size; i++) {
HTMLComponent component = (HTMLComponent)fHTMLComponents.elementAt(i);
component.setFeature(featureId, state);
}
} // setFeature(String,boolean)
/** Sets a property. */
public void setProperty(String propertyId, Object value)
throws XMLConfigurationException {
super.setProperty(propertyId, value);
if (propertyId.equals(FILTERS)) {
XMLDocumentFilter[] filters = (XMLDocumentFilter[])getProperty(FILTERS);
if (filters != null) {
for (int i = 0; i < filters.length; i++) {
XMLDocumentFilter filter = filters[i];
if (filter instanceof HTMLComponent) {
addComponent((HTMLComponent)filter);
}
}
}
}
int size = fHTMLComponents.size();
for (int i = 0; i < size; i++) {
HTMLComponent component = (HTMLComponent)fHTMLComponents.elementAt(i);
component.setProperty(propertyId, value);
}
} // setProperty(String,Object)
/** Sets the document handler. */
public void setDocumentHandler(XMLDocumentHandler handler) {
fDocumentHandler = handler;
if (handler instanceof HTMLTagBalancingListener) {
fTagBalancer.setTagBalancingListener((HTMLTagBalancingListener) handler);
}
} // setDocumentHandler(XMLDocumentHandler)
/** Returns the document handler. */
public XMLDocumentHandler getDocumentHandler() {
return fDocumentHandler;
} // getDocumentHandler():XMLDocumentHandler
/** Sets the DTD handler. */
public void setDTDHandler(XMLDTDHandler handler) {
fDTDHandler = handler;
} // setDTDHandler(XMLDTDHandler)
/** Returns the DTD handler. */
public XMLDTDHandler getDTDHandler() {
return fDTDHandler;
} // getDTDHandler():XMLDTDHandler
/** Sets the DTD content model handler. */
public void setDTDContentModelHandler(XMLDTDContentModelHandler handler) {
fDTDContentModelHandler = handler;
} // setDTDContentModelHandler(XMLDTDContentModelHandler)
/** Returns the DTD content model handler. */
public XMLDTDContentModelHandler getDTDContentModelHandler() {
return fDTDContentModelHandler;
} // getDTDContentModelHandler():XMLDTDContentModelHandler
/** Sets the error handler. */
public void setErrorHandler(XMLErrorHandler handler) {
fErrorHandler = handler;
} // setErrorHandler(XMLErrorHandler)
/** Returns the error handler. */
public XMLErrorHandler getErrorHandler() {
return fErrorHandler;
} // getErrorHandler():XMLErrorHandler
/** Sets the entity resolver. */
public void setEntityResolver(XMLEntityResolver resolver) {
fEntityResolver = resolver;
} // setEntityResolver(XMLEntityResolver)
/** Returns the entity resolver. */
public XMLEntityResolver getEntityResolver() {
return fEntityResolver;
} // getEntityResolver():XMLEntityResolver
/** Sets the locale. */
public void setLocale(Locale locale) {
if (locale == null) {
locale = Locale.getDefault();
}
fLocale = locale;
} // setLocale(Locale)
/** Returns the locale. */
public Locale getLocale() {
return fLocale;
} // getLocale():Locale
/** Parses a document. */
public void parse(XMLInputSource source) throws XNIException, IOException {
setInputSource(source);
parse(true);
} // parse(XMLInputSource)
//
// XMLPullParserConfiguration methods
//
// parsing
/**
* Sets the input source for the document to parse.
*
* @param inputSource The document's input source.
*
* @exception XMLConfigurationException Thrown if there is a
* configuration error when initializing the
* parser.
* @exception IOException Thrown on I/O error.
*
* @see #parse(boolean)
*/
public void setInputSource(XMLInputSource inputSource)
throws XMLConfigurationException, IOException {
reset();
fCloseStream = inputSource.getByteStream() == null &&
inputSource.getCharacterStream() == null;
fDocumentScanner.setInputSource(inputSource);
} // setInputSource(XMLInputSource)
/**
* Parses the document in a pull parsing fashion.
*
* @param complete True if the pull parser should parse the
* remaining document completely.
*
* @return True if there is more document to parse.
*
* @exception XNIException Any XNI exception, possibly wrapping
* another exception.
* @exception IOException An IO exception from the parser, possibly
* from a byte stream or character stream
* supplied by the parser.
*
* @see #setInputSource
*/
public boolean parse(boolean complete) throws XNIException, IOException {
try {
boolean more = fDocumentScanner.scanDocument(complete);
if (!more) {
cleanup();
}
return more;
}
catch (XNIException e) {
cleanup();
throw e;
}
catch (IOException e) {
cleanup();
throw e;
}
} // parse(boolean):boolean
/**
* If the application decides to terminate parsing before the xml document
* is fully parsed, the application should call this method to free any
* resource allocated during parsing. For example, close all opened streams.
*/
public void cleanup() {
fDocumentScanner.cleanup(fCloseStream);
} // cleanup()
//
// Protected methods
//
/** Adds a component. */
protected void addComponent(HTMLComponent component) {
// add component to list
fHTMLComponents.addElement(component);
// add recognized features and set default states
String[] features = component.getRecognizedFeatures();
addRecognizedFeatures(features);
int featureCount = features != null ? features.length : 0;
for (int i = 0; i < featureCount; i++) {
Boolean state = component.getFeatureDefault(features[i]);
if (state != null) {
setFeature(features[i], state.booleanValue());
}
}
// add recognized properties and set default values
String[] properties = component.getRecognizedProperties();
addRecognizedProperties(properties);
int propertyCount = properties != null ? properties.length : 0;
for (int i = 0; i < propertyCount; i++) {
Object value = component.getPropertyDefault(properties[i]);
if (value != null) {
setProperty(properties[i], value);
}
}
} // addComponent(HTMLComponent)
/** Resets the parser configuration. */
protected void reset() throws XMLConfigurationException {
// reset components
int size = fHTMLComponents.size();
for (int i = 0; i < size; i++) {
HTMLComponent component = (HTMLComponent)fHTMLComponents.elementAt(i);
component.reset(this);
}
// configure pipeline
XMLDocumentSource lastSource = fDocumentScanner;
if (getFeature(NAMESPACES)) {
lastSource.setDocumentHandler(fNamespaceBinder);
fNamespaceBinder.setDocumentSource(fTagBalancer);
lastSource = fNamespaceBinder;
}
if (getFeature(BALANCE_TAGS)) {
lastSource.setDocumentHandler(fTagBalancer);
fTagBalancer.setDocumentSource(fDocumentScanner);
lastSource = fTagBalancer;
}
XMLDocumentFilter[] filters = (XMLDocumentFilter[])getProperty(FILTERS);
if (filters != null) {
for (int i = 0; i < filters.length; i++) {
XMLDocumentFilter filter = filters[i];
XercesBridge.getInstance().XMLDocumentFilter_setDocumentSource(filter, lastSource);
lastSource.setDocumentHandler(filter);
lastSource = filter;
}
}
lastSource.setDocumentHandler(fDocumentHandler);
} // reset()
//
// Interfaces
//
/**
* Defines an error reporter for reporting HTML errors. There is no such
* thing as a fatal error in parsing HTML. I/O errors are fatal but should
* throw an <code>IOException</code> directly instead of reporting an error.
* <p>
* When used in a configuration, the error reporter instance should be
* set as a property with the following property identifier:
* <pre>
* "http://cyberneko.org/html/internal/error-reporter" in the
* </pre>
* Components in the configuration can query the error reporter using this
* property identifier.
* <p>
* <strong>Note:</strong>
* All reported errors are within the domain "http://cyberneko.org/html".
*
* @author Andy Clark
*/
protected class ErrorReporter
implements HTMLErrorReporter {
//
// Data
//
/** Last locale. */
protected Locale fLastLocale;
/** Error messages. */
protected ResourceBundle fErrorMessages;
//
// HTMLErrorReporter methods
//
/** Format message without reporting error. */
public String formatMessage(String key, Object[] args) {
if (!getFeature(SIMPLE_ERROR_FORMAT)) {
if (!fLocale.equals(fLastLocale)) {
fErrorMessages = null;
fLastLocale = fLocale;
}
if (fErrorMessages == null) {
fErrorMessages =
ResourceBundle.getBundle("org/cyberneko/html/res/ErrorMessages",
fLocale);
}
try {
String value = fErrorMessages.getString(key);
String message = MessageFormat.format(value, args);
return message;
}
catch (MissingResourceException e) {
// ignore and return a simple format
}
}
return formatSimpleMessage(key, args);
} // formatMessage(String,Object[]):String
/** Reports a warning. */
public void reportWarning(String key, Object[] args)
throws XMLParseException {
if (fErrorHandler != null) {
fErrorHandler.warning(ERROR_DOMAIN, key, createException(key, args));
}
} // reportWarning(String,Object[])
/** Reports an error. */
public void reportError(String key, Object[] args)
throws XMLParseException {
if (fErrorHandler != null) {
fErrorHandler.error(ERROR_DOMAIN, key, createException(key, args));
}
} // reportError(String,Object[])
//
// Protected methods
//
/** Creates parse exception. */
protected XMLParseException createException(String key, Object[] args) {
String message = formatMessage(key, args);
return new XMLParseException(fDocumentScanner, message);
} // createException(String,Object[]):XMLParseException
/** Format simple message. */
protected String formatSimpleMessage(String key, Object[] args) {
StringBuffer str = new StringBuffer();
str.append(ERROR_DOMAIN);
str.append('#');
str.append(key);
if (args != null && args.length > 0) {
str.append('\t');
for (int i = 0; i < args.length; i++) {
if (i > 0) {
str.append('\t');
}
str.append(String.valueOf(args[i]));
}
}
return str.toString();
} // formatSimpleMessage(String,
} // class ErrorReporter
} // class HTMLConfiguration
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/HTMLConfiguration.java | Java | art | 24,441 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
/**
* <font color="red">EXPERIMENTAL: may change in next release</font><br/>
* {@link XMLDocumentHandler} implementing this interface will get notified of elements discarded
* by the tag balancer when they:
* <ul>
* <li>are configured using {@link HTMLConfiguration}</li>
* <li>activate the tag balancing feature</li>
* </ul>
* @author Marc Guillemot
* @version $Id: HTMLTagBalancingListener.java 260 2009-09-02 08:26:01Z mguillem $
*/
public interface HTMLTagBalancingListener
{
/**
* Notifies that the start element has been ignored.
*/
void ignoredStartElement(QName elem, XMLAttributes attrs, Augmentations augs);
/**
* Notifies that the end element has been ignored.
*/
void ignoredEndElement(QName element, Augmentations augs);
}
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/HTMLTagBalancingListener.java | Java | art | 1,534 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html;
import org.apache.xerces.xni.parser.XMLParseException;
/**
* Defines an error reporter for reporting HTML errors. There is no such
* thing as a fatal error in parsing HTML. I/O errors are fatal but should
* throw an <code>IOException</code> directly instead of reporting an error.
* <p>
* When used in a configuration, the error reporter instance should be
* set as a property with the following property identifier:
* <pre>
* "http://cyberneko.org/html/internal/error-reporter" in the
* </pre>
* Components in the configuration can query the error reporter using this
* property identifier.
* <p>
* <strong>Note:</strong>
* All reported errors are within the domain "http://cyberneko.org/html".
*
* @author Andy Clark
*
* @version $Id: HTMLErrorReporter.java,v 1.4 2005/02/14 03:56:54 andyc Exp $
*/
public interface HTMLErrorReporter {
//
// HTMLErrorReporter methods
//
/** Format message without reporting error. */
public String formatMessage(String key, Object[] args);
/** Reports a warning. */
public void reportWarning(String key, Object[] args) throws XMLParseException;
/** Reports an error. */
public void reportError(String key, Object[] args) throws XMLParseException;
} // interface HTMLErrorReporter
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/HTMLErrorReporter.java | Java | art | 1,931 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html.parsers;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.XNIException;
import org.cyberneko.html.HTMLConfiguration;
import org.cyberneko.html.xercesbridge.XercesBridge;
/**
* A DOM parser for HTML documents.
*
* @author Andy Clark
*
* @version $Id: DOMParser.java,v 1.5 2005/02/14 03:56:54 andyc Exp $
*/
public class DOMParser
/***/
extends org.apache.xerces.parsers.DOMParser {
/***
// NOTE: It would be better to extend from AbstractDOMParser but
// most users will find it easier if the API is just like the
// Xerces DOM parser. By extending directly from DOMParser,
// users can register SAX error handlers, entity resolvers,
// and the like. -Ac
extends org.apache.xerces.parsers.AbstractDOMParser {
/***/
//
// Constructors
//
/** Default constructor. */
public DOMParser() {
super(new HTMLConfiguration());
/*** extending DOMParser ***/
try {
setProperty("http://apache.org/xml/properties/dom/document-class-name",
"org.apache.html.dom.HTMLDocumentImpl");
}
catch (org.xml.sax.SAXNotRecognizedException e) {
throw new RuntimeException("http://apache.org/xml/properties/dom/document-class-name property not recognized");
}
catch (org.xml.sax.SAXNotSupportedException e) {
throw new RuntimeException("http://apache.org/xml/properties/dom/document-class-name property not supported");
}
/*** extending AbstractDOMParser ***
fConfiguration.setProperty("http://apache.org/xml/properties/dom/document-class-name",
"org.apache.html.dom.HTMLDocumentImpl");
/***/
} // <init>()
//
// XMLDocumentHandler methods
//
/** Doctype declaration. */
public void doctypeDecl(String root, String pubid, String sysid,
Augmentations augs) throws XNIException {
// NOTE: Xerces HTML DOM implementation (up to and including
// 2.5.0) throws a heirarchy request error exception
// when a doctype node is appended to the tree. So,
// don't insert this node into the tree for those
// versions... -Ac
String VERSION = XercesBridge.getInstance().getVersion();
boolean okay = true;
if (VERSION.startsWith("Xerces-J 2.")) {
okay = getParserSubVersion() > 5;
}
// REVISIT: As soon as XML4J is updated with the latest code
// from Xerces, then this needs to be updated to
// check XML4J's version. -Ac
else if (VERSION.startsWith("XML4J")) {
okay = false;
}
// if okay, insert doctype; otherwise, don't risk it
if (okay) {
super.doctypeDecl(root, pubid, sysid, augs);
}
} // doctypeDecl(String,String,String,Augmentations)
//
// Private static methods
//
/** Returns the parser's sub-version number. */
private static int getParserSubVersion() {
try {
String VERSION = XercesBridge.getInstance().getVersion();
int index1 = VERSION.indexOf('.') + 1;
int index2 = VERSION.indexOf('.', index1);
if (index2 == -1) { index2 = VERSION.length(); }
return Integer.parseInt(VERSION.substring(index1, index2));
}
catch (Exception e) {
return -1;
}
} // getParserSubVersion():int
} // class DOMParser
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/parsers/DOMParser.java | Java | art | 4,248 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html.parsers;
import org.apache.xerces.parsers.AbstractSAXParser;
import org.cyberneko.html.HTMLConfiguration;
/**
* A SAX parser for HTML documents.
*
* @author Andy Clark
*
* @version $Id: SAXParser.java,v 1.4 2005/02/14 03:56:54 andyc Exp $
*/
public class SAXParser
extends AbstractSAXParser {
//
// Constructors
//
/** Default constructor. */
public SAXParser() {
super(new HTMLConfiguration());
} // <init>()
} // class SAXParser
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/parsers/SAXParser.java | Java | art | 1,123 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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 file contains some code from Apache Xerces-J which is
* used in accordance with the Apache license.
*/
package org.cyberneko.html.parsers;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import org.apache.xerces.impl.Constants;
import org.apache.xerces.util.ErrorHandlerWrapper;
import org.apache.xerces.util.XMLChar;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLDocumentHandler;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLResourceIdentifier;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLConfigurationException;
import org.apache.xerces.xni.parser.XMLDocumentSource;
import org.apache.xerces.xni.parser.XMLErrorHandler;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.apache.xerces.xni.parser.XMLParseException;
import org.apache.xerces.xni.parser.XMLParserConfiguration;
import org.cyberneko.html.HTMLConfiguration;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.EntityReference;
import org.w3c.dom.Node;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.Text;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
/**
* A DOM parser for HTML fragments.
*
* @author Andy Clark
*
* @version $Id: DOMFragmentParser.java,v 1.8 2005/02/14 03:56:54 andyc Exp $
*/
public class DOMFragmentParser
implements XMLDocumentHandler {
//
// Constants
//
// features
/** Document fragment balancing only. */
protected static final String DOCUMENT_FRAGMENT =
"http://cyberneko.org/html/features/document-fragment";
/** Recognized features. */
protected static final String[] RECOGNIZED_FEATURES = {
DOCUMENT_FRAGMENT,
};
// properties
/** Property identifier: error handler. */
protected static final String ERROR_HANDLER =
Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY;
/** Current element node. */
protected static final String CURRENT_ELEMENT_NODE =
Constants.XERCES_PROPERTY_PREFIX + Constants.CURRENT_ELEMENT_NODE_PROPERTY;
/** Recognized properties. */
protected static final String[] RECOGNIZED_PROPERTIES = {
ERROR_HANDLER,
CURRENT_ELEMENT_NODE,
};
//
// Data
//
/** Parser configuration. */
protected XMLParserConfiguration fParserConfiguration;
/** Document source. */
protected XMLDocumentSource fDocumentSource;
/** DOM document fragment. */
protected DocumentFragment fDocumentFragment;
/** Document. */
protected Document fDocument;
/** Current node. */
protected Node fCurrentNode;
/** True if within a CDATA section. */
protected boolean fInCDATASection;
//
// Constructors
//
/** Default constructor. */
public DOMFragmentParser() {
fParserConfiguration = new HTMLConfiguration();
fParserConfiguration.addRecognizedFeatures(RECOGNIZED_FEATURES);
fParserConfiguration.addRecognizedProperties(RECOGNIZED_PROPERTIES);
fParserConfiguration.setFeature(DOCUMENT_FRAGMENT, true);
fParserConfiguration.setDocumentHandler(this);
} // <init>()
//
// Public methods
//
/** Parses a document fragment. */
public void parse(String systemId, DocumentFragment fragment)
throws SAXException, IOException {
parse(new InputSource(systemId), fragment);
} // parse(String,DocumentFragment)
/** Parses a document fragment. */
public void parse(InputSource source, DocumentFragment fragment)
throws SAXException, IOException {
fCurrentNode = fDocumentFragment = fragment;
fDocument = fDocumentFragment.getOwnerDocument();
try {
String pubid = source.getPublicId();
String sysid = source.getSystemId();
String encoding = source.getEncoding();
InputStream stream = source.getByteStream();
Reader reader = source.getCharacterStream();
XMLInputSource inputSource =
new XMLInputSource(pubid, sysid, sysid);
inputSource.setEncoding(encoding);
inputSource.setByteStream(stream);
inputSource.setCharacterStream(reader);
fParserConfiguration.parse(inputSource);
}
catch (XMLParseException e) {
Exception ex = e.getException();
if (ex != null) {
throw new SAXParseException(e.getMessage(), null, ex);
}
throw new SAXParseException(e.getMessage(), null);
}
} // parse(InputSource,DocumentFragment)
/**
* Allow an application to register an error event handler.
*
* <p>If the application does not register an error handler, all
* error events reported by the SAX parser will be silently
* ignored; however, normal processing may not continue. It is
* highly recommended that all SAX applications implement an
* error handler to avoid unexpected bugs.</p>
*
* <p>Applications may register a new or different handler in the
* middle of a parse, and the SAX parser must begin using the new
* handler immediately.</p>
*
* @param errorHandler The error handler.
* @exception java.lang.NullPointerException If the handler
* argument is null.
* @see #getErrorHandler
*/
public void setErrorHandler(ErrorHandler errorHandler) {
fParserConfiguration.setErrorHandler(new ErrorHandlerWrapper(errorHandler));
} // setErrorHandler(ErrorHandler)
/**
* Return the current error handler.
*
* @return The current error handler, or null if none
* has been registered.
* @see #setErrorHandler
*/
public ErrorHandler getErrorHandler() {
ErrorHandler errorHandler = null;
try {
XMLErrorHandler xmlErrorHandler =
(XMLErrorHandler)fParserConfiguration.getProperty(ERROR_HANDLER);
if (xmlErrorHandler != null &&
xmlErrorHandler instanceof ErrorHandlerWrapper) {
errorHandler = ((ErrorHandlerWrapper)xmlErrorHandler).getErrorHandler();
}
}
catch (XMLConfigurationException e) {
// do nothing
}
return errorHandler;
} // getErrorHandler():ErrorHandler
/**
* Set the state of any feature in a SAX2 parser. The parser
* might not recognize the feature, and if it does recognize
* it, it might not be able to fulfill the request.
*
* @param featureId The unique identifier (URI) of the feature.
* @param state The requested state of the feature (true or false).
*
* @exception SAXNotRecognizedException If the
* requested feature is not known.
* @exception SAXNotSupportedException If the
* requested feature is known, but the requested
* state is not supported.
*/
public void setFeature(String featureId, boolean state)
throws SAXNotRecognizedException, SAXNotSupportedException {
try {
fParserConfiguration.setFeature(featureId, state);
}
catch (XMLConfigurationException e) {
String message = e.getMessage();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(message);
}
else {
throw new SAXNotSupportedException(message);
}
}
} // setFeature(String,boolean)
/**
* Query the state of a feature.
*
* Query the current state of any feature in a SAX2 parser. The
* parser might not recognize the feature.
*
* @param featureId The unique identifier (URI) of the feature
* being set.
* @return The current state of the feature.
* @exception org.xml.sax.SAXNotRecognizedException If the
* requested feature is not known.
* @exception SAXNotSupportedException If the
* requested feature is known but not supported.
*/
public boolean getFeature(String featureId)
throws SAXNotRecognizedException, SAXNotSupportedException {
try {
return fParserConfiguration.getFeature(featureId);
}
catch (XMLConfigurationException e) {
String message = e.getMessage();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(message);
}
else {
throw new SAXNotSupportedException(message);
}
}
} // getFeature(String):boolean
/**
* Set the value of any property in a SAX2 parser. The parser
* might not recognize the property, and if it does recognize
* it, it might not support the requested value.
*
* @param propertyId The unique identifier (URI) of the property
* being set.
* @param value The value to which the property is being set.
*
* @exception SAXNotRecognizedException If the
* requested property is not known.
* @exception SAXNotSupportedException If the
* requested property is known, but the requested
* value is not supported.
*/
public void setProperty(String propertyId, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException {
try {
fParserConfiguration.setProperty(propertyId, value);
}
catch (XMLConfigurationException e) {
String message = e.getMessage();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(message);
}
else {
throw new SAXNotSupportedException(message);
}
}
} // setProperty(String,Object)
/**
* Query the value of a property.
*
* Return the current value of a property in a SAX2 parser.
* The parser might not recognize the property.
*
* @param propertyId The unique identifier (URI) of the property
* being set.
* @return The current value of the property.
* @exception org.xml.sax.SAXNotRecognizedException If the
* requested property is not known.
* @exception SAXNotSupportedException If the
* requested property is known but not supported.
*/
public Object getProperty(String propertyId)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (propertyId.equals(CURRENT_ELEMENT_NODE)) {
return (fCurrentNode!=null &&
fCurrentNode.getNodeType() == Node.ELEMENT_NODE)? fCurrentNode:null;
}
try {
return fParserConfiguration.getProperty(propertyId);
}
catch (XMLConfigurationException e) {
String message = e.getMessage();
if (e.getType() == XMLConfigurationException.NOT_RECOGNIZED) {
throw new SAXNotRecognizedException(message);
}
else {
throw new SAXNotSupportedException(message);
}
}
} // getProperty(String):Object
//
// XMLDocumentHandler methods
//
/** Sets the document source. */
public void setDocumentSource(XMLDocumentSource source) {
fDocumentSource = source;
} // setDocumentSource(XMLDocumentSource)
/** Returns the document source. */
public XMLDocumentSource getDocumentSource() {
return fDocumentSource;
} // getDocumentSource():XMLDocumentSource
/** Start document. */
public void startDocument(XMLLocator locator, String encoding,
Augmentations augs) throws XNIException {
startDocument(locator, encoding, null, augs);
} // startDocument(XMLLocator,String,Augmentations)
// since Xerces 2.2.0
/** Start document. */
public void startDocument(XMLLocator locator, String encoding,
NamespaceContext nscontext,
Augmentations augs) throws XNIException {
fInCDATASection = false;
} // startDocument(XMLLocator,String,NamespaceContext,Augmentations)
/** XML declaration. */
public void xmlDecl(String version, String encoding,
String standalone, Augmentations augs)
throws XNIException {
} // xmlDecl(String,String,String,Augmentations)
/** Document type declaration. */
public void doctypeDecl(String root, String pubid, String sysid,
Augmentations augs) throws XNIException {
} // doctypeDecl(String,String,String,Augmentations)
/** Processing instruction. */
public void processingInstruction(final String target, final XMLString data,
final Augmentations augs)
throws XNIException {
final String s = data.toString();
if (XMLChar.isValidName(s)) {
final ProcessingInstruction pi = fDocument.createProcessingInstruction(target, s);
fCurrentNode.appendChild(pi);
}
} // processingInstruction(String,XMLString,Augmentations)
/** Comment. */
public void comment(XMLString text, Augmentations augs)
throws XNIException {
Comment comment = fDocument.createComment(text.toString());
fCurrentNode.appendChild(comment);
} // comment(XMLString,Augmentations)
/** Start prefix mapping. @deprecated Since Xerces 2.2.0. */
public void startPrefixMapping(String prefix, String uri,
Augmentations augs) throws XNIException {
} // startPrefixMapping(String,String,Augmentations)
/** End prefix mapping. @deprecated Since Xerces 2.2.0. */
public void endPrefixMapping(String prefix, Augmentations augs)
throws XNIException {
} // endPrefixMapping(String,Augmentations)
/** Start element. */
public void startElement(QName element, XMLAttributes attrs,
Augmentations augs) throws XNIException {
Element elementNode = fDocument.createElement(element.rawname);
int count = attrs != null ? attrs.getLength() : 0;
for (int i = 0; i < count; i++) {
String aname = attrs.getQName(i);
String avalue = attrs.getValue(i);
if (XMLChar.isValidName(aname)) {
elementNode.setAttribute(aname, avalue);
}
}
fCurrentNode.appendChild(elementNode);
fCurrentNode = elementNode;
} // startElement(QName,XMLAttributes,Augmentations)
/** Empty element. */
public void emptyElement(QName element, XMLAttributes attrs,
Augmentations augs) throws XNIException {
startElement(element, attrs, augs);
endElement(element, augs);
} // emptyElement(QName,XMLAttributes,Augmentations)
/** Characters. */
public void characters(XMLString text, Augmentations augs)
throws XNIException {
if (fInCDATASection) {
Node node = fCurrentNode.getLastChild();
if (node != null && node.getNodeType() == Node.CDATA_SECTION_NODE) {
CDATASection cdata = (CDATASection)node;
cdata.appendData(text.toString());
}
else {
CDATASection cdata = fDocument.createCDATASection(text.toString());
fCurrentNode.appendChild(cdata);
}
}
else {
Node node = fCurrentNode.getLastChild();
if (node != null && node.getNodeType() == Node.TEXT_NODE) {
Text textNode = (Text)node;
textNode.appendData(text.toString());
}
else {
Text textNode = fDocument.createTextNode(text.toString());
fCurrentNode.appendChild(textNode);
}
}
} // characters(XMLString,Augmentations)
/** Ignorable whitespace. */
public void ignorableWhitespace(XMLString text, Augmentations augs)
throws XNIException {
characters(text, augs);
} // ignorableWhitespace(XMLString,Augmentations)
/** Start general entity. */
public void startGeneralEntity(String name, XMLResourceIdentifier id,
String encoding, Augmentations augs)
throws XNIException {
EntityReference entityRef = fDocument.createEntityReference(name);
fCurrentNode.appendChild(entityRef);
fCurrentNode = entityRef;
} // startGeneralEntity(String,XMLResourceIdentifier,String,Augmentations)
/** Text declaration. */
public void textDecl(String version, String encoding,
Augmentations augs) throws XNIException {
} // textDecl(String,String,Augmentations)
/** End general entity. */
public void endGeneralEntity(String name, Augmentations augs)
throws XNIException {
fCurrentNode = fCurrentNode.getParentNode();
} // endGeneralEntity(String,Augmentations)
/** Start CDATA section. */
public void startCDATA(Augmentations augs) throws XNIException {
fInCDATASection = true;
} // startCDATA(Augmentations)
/** End CDATA section. */
public void endCDATA(Augmentations augs) throws XNIException {
fInCDATASection = false;
} // endCDATA(Augmentations)
/** End element. */
public void endElement(QName element, Augmentations augs)
throws XNIException {
fCurrentNode = fCurrentNode.getParentNode();
} // endElement(QName,Augmentations)
/** End document. */
public void endDocument(Augmentations augs) throws XNIException {
} // endDocument(Augmentations)
//
// DEBUG
//
/***
public static void print(Node node) {
short type = node.getNodeType();
switch (type) {
case Node.ELEMENT_NODE: {
System.out.print('<');
System.out.print(node.getNodeName());
org.w3c.dom.NamedNodeMap attrs = node.getAttributes();
int attrCount = attrs != null ? attrs.getLength() : 0;
for (int i = 0; i < attrCount; i++) {
Node attr = attrs.item(i);
System.out.print(' ');
System.out.print(attr.getNodeName());
System.out.print("='");
System.out.print(attr.getNodeValue());
System.out.print('\'');
}
System.out.print('>');
break;
}
case Node.TEXT_NODE: {
System.out.print(node.getNodeValue());
break;
}
}
Node child = node.getFirstChild();
while (child != null) {
print(child);
child = child.getNextSibling();
}
if (type == Node.ELEMENT_NODE) {
System.out.print("</");
System.out.print(node.getNodeName());
System.out.print('>');
}
else if (type == Node.DOCUMENT_NODE || type == Node.DOCUMENT_FRAGMENT_NODE) {
System.out.println();
}
System.out.flush();
}
public static void main(String[] argv) throws Exception {
DOMFragmentParser parser = new DOMFragmentParser();
HTMLDocument document = new org.apache.html.dom.HTMLDocumentImpl();
for (int i = 0; i < argv.length; i++) {
String sysid = argv[i];
System.err.println("# "+sysid);
DocumentFragment fragment = document.createDocumentFragment();
parser.parse(sysid, fragment);
print(fragment);
}
}
/***/
} // class DOMFragmentParser
| zzh-simple-hr | Znekohtml/src/org/cyberneko/html/parsers/DOMFragmentParser.java | Java | art | 21,076 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package sample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.cyberneko.html.HTMLConfiguration;
import org.cyberneko.html.filters.DefaultFilter;
import org.cyberneko.html.filters.Identity;
import org.cyberneko.html.filters.Writer;
/**
* This sample demonstrates how to use of the <code>pushInputSource</code>
* method of the HTMLConfiguration in order to dynamically insert content
* into the HTML stream. The typical use for this functionality is to
* insert the result of an embedded script into the HTML document in place
* of the script.
* <p>
* This particular example defines a new script language called "NekoHTML"
* script that is a tiny subset of the NSGMLS format. The following table
* enumerates the NSGMLS features supported by this script language:
* <table border='1' cellspacing='0', cellpadding='3'>
* <tr><th>(<i>name</i><td>A start element with the specified <i>name</i>.
* <tr><th>"<i>text</i><td>Character content with the specified <i>text</i>.
* <tr><th>)<i>name</i><td>An end element with the specified <i>name</i>.
* </table>
* <p>
* In this format, every <i>command</i> is specified on a line by itself.
* For example, the following document:
* <pre>
* <script type='NekoHTML'>
* (h1
* "Header
* )h1
* </script>
* </pre>
* is equivalent to the following HTML document:
* <pre>
* <H1>Header</H1>
* </pre>
* as seen by document handler registered with the parser, when processed
* by this filter.
*
* @author Andy Clark
*
* @version $Id: Script.java,v 1.3 2004/02/19 20:00:17 andyc Exp $
*/
public class Script
extends DefaultFilter {
//
// Constants
//
/** Augmentations feature identifier. */
protected static final String AUGMENTATIONS = "http://cyberneko.org/html/features/augmentations";
/** Filters property identifier. */
protected static final String FILTERS = "http://cyberneko.org/html/properties/filters";
/** Script type ("text/x-nekoscript"). */
protected static final String SCRIPT_TYPE = "text/x-nekoscript";
//
// Data
//
/** The NekoHTML configuration. */
protected HTMLConfiguration fConfiguration;
/** A string buffer to collect the "script". */
protected StringBuffer fBuffer;
/** The system identifier of the source document. */
protected String fSystemId;
/** The script count. */
protected int fScriptCount;
//
// Constructors
//
/** Constructs a script object with the specified configuration. */
public Script(HTMLConfiguration config) {
fConfiguration = config;
} // <init>(HTMLConfiguration)
//
// XMLDocumentHandler methods
//
/** Start document. */
public void startDocument(XMLLocator locator, String encoding, Augmentations augs)
throws XNIException {
fBuffer = null;
fSystemId = locator != null ? locator.getLiteralSystemId() : null;
fScriptCount = 0;
super.startDocument(locator, encoding, augs);
} // startDocument(XMLLocator,String,Augmentations)
/** Start element. */
public void startElement(QName element, XMLAttributes attrs, Augmentations augs)
throws XNIException {
if (element.rawname.equalsIgnoreCase("script") && attrs != null) {
String value = attrs.getValue("type");
if (value != null && value.equalsIgnoreCase(SCRIPT_TYPE)) {
fBuffer = new StringBuffer();
return;
}
}
super.startElement(element, attrs, augs);
} // startElement(QName,XMLAttributes,Augmentations)
/** Empty element. */
public void emptyElement(QName element, XMLAttributes attrs, Augmentations augs)
throws XNIException {
if (element.rawname.equalsIgnoreCase("script") && attrs != null) {
String value = attrs.getValue("type");
if (value != null && value.equalsIgnoreCase(SCRIPT_TYPE)) {
return;
}
}
super.emptyElement(element, attrs, augs);
} // emptyElement(QName,XMLAttributes,Augmentations)
/** Characters. */
public void characters(XMLString text, Augmentations augs)
throws XNIException {
if (fBuffer != null) {
fBuffer.append(text.ch, text.offset, text.length);
}
else {
super.characters(text, augs);
}
} // characters(XMLString,Augmentations)
/** End element. */
public void endElement(QName element, Augmentations augs) throws XNIException {
if (fBuffer != null) {
try {
// run "script" and generate HTML output
BufferedReader in = new BufferedReader(new StringReader(fBuffer.toString()));
StringWriter sout = new StringWriter();
PrintWriter out = new PrintWriter(sout);
String line;
while ((line = in.readLine()) != null) {
line.trim();
if (line.length() == 0) {
continue;
}
switch (line.charAt(0)) {
case '(': {
out.print('<');
out.print(line.substring(1));
out.print('>');
break;
}
case '"': {
out.print(line.substring(1));
break;
}
case ')': {
out.print("</");
out.print(line.substring(1));
out.print('>');
break;
}
}
}
// push new input source
String systemId = fSystemId != null ? fSystemId+'_' : "";
fScriptCount++;
systemId += "script"+fScriptCount;
XMLInputSource source = new XMLInputSource(null, systemId, null,
new StringReader(sout.toString()),
"UTF-8");
fConfiguration.pushInputSource(source);
}
catch (IOException e) {
// ignore
}
finally {
fBuffer = null;
}
}
else {
super.endElement(element, augs);
}
} // endElement(QName,Augmentations)
//
// MAIN
//
/** Main. */
public static void main(String[] argv) throws Exception {
HTMLConfiguration parser = new HTMLConfiguration();
parser.setFeature(AUGMENTATIONS, true);
XMLDocumentFilter[] filters = { new Script(parser), new Identity(), new Writer() };
parser.setProperty(FILTERS, filters);
for (int i = 0; i < argv.length; i++) {
parser.parse(new XMLInputSource(null, argv[i], null));
}
} // main(String[])
} // class Script
| zzh-simple-hr | Znekohtml/sample/sample/Script.java | Java | art | 8,190 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package sample;
import org.apache.xerces.parsers.AbstractSAXParser;
import org.cyberneko.html.HTMLConfiguration;
/**
* This sample shows how to extend a Xerces2 parser class, replacing
* the default parser configuration with the NekoHTML configuration.
*
* @author Andy Clark
*
* @version $Id: HTMLSAXParser.java,v 1.3 2004/02/19 20:00:17 andyc Exp $
*/
public class HTMLSAXParser
extends AbstractSAXParser {
//
// Constructors
//
/** Default constructor. */
public HTMLSAXParser() {
super(new HTMLConfiguration());
} // <init>()
} // class HTMLSAXParser
| zzh-simple-hr | Znekohtml/sample/sample/HTMLSAXParser.java | Java | art | 1,222 |
/*
* Copyright 2007-2008 Andy Clark
*
* Licensed 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.
*/
package sample;
import org.cyberneko.html.HTMLConfiguration;
import org.cyberneko.html.filters.DefaultFilter;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.parser.XMLParserConfiguration;
import org.apache.xerces.xni.parser.XMLInputSource;
/**
* This class demonstrates that the NekoHTML parser can be used with
* a minimal set of Xerces2 classes if you program directory the the
* Xerces Native Interface (XNI).
*
* @author Andy Clark
*/
public class Minimal extends DefaultFilter {
//
// MAIN
//
public static void main(String[] argv) throws Exception {
XMLParserConfiguration parser = new HTMLConfiguration();
parser.setDocumentHandler(new Minimal());
for (int i = 0; i < argv.length; i++) {
XMLInputSource source = new XMLInputSource(null, argv[i], null);
parser.parse(source);
}
} // main(String[])
//
// XMLDocumentHandler methods
//
public void startElement(QName element, XMLAttributes attrs, Augmentations augs) {
System.out.println("("+element.rawname);
}
public void endElement(QName element, Augmentations augs) {
System.out.println(")"+element.rawname);
}
} // class Minimal | zzh-simple-hr | Znekohtml/sample/sample/Minimal.java | Java | art | 1,842 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package sample;
import org.cyberneko.html.HTMLConfiguration;
import org.cyberneko.html.filters.ElementRemover;
import org.apache.xerces.xni.parser.XMLDocumentFilter;
import org.apache.xerces.xni.parser.XMLInputSource;
import org.apache.xerces.xni.parser.XMLParserConfiguration;
/**
* This is a sample that illustrates how to use the
* <code>ElementRemover</code> filter.
*
* @author Andy Clark
*
* @version $Id: RemoveElements.java,v 1.3 2004/02/19 20:00:17 andyc Exp $
*/
public class RemoveElements {
//
// MAIN
//
/** Main. */
public static void main(String[] argv) throws Exception {
// create element remover filter
ElementRemover remover = new ElementRemover();
// set which elements to accept
remover.acceptElement("b", null);
remover.acceptElement("i", null);
remover.acceptElement("u", null);
remover.acceptElement("a", new String[] { "href" });
// completely remove script elements
remover.removeElement("script");
// create writer filter
org.cyberneko.html.filters.Writer writer =
new org.cyberneko.html.filters.Writer();
// setup filter chain
XMLDocumentFilter[] filters = {
remover,
writer,
};
// create HTML parser
XMLParserConfiguration parser = new HTMLConfiguration();
parser.setProperty("http://cyberneko.org/html/properties/filters", filters);
// parse documents
for (int i = 0; i < argv.length; i++) {
String systemId = argv[i];
XMLInputSource source = new XMLInputSource(null, systemId, null);
parser.parse(source);
}
} // main(String[])
} // class RemoveElements | zzh-simple-hr | Znekohtml/sample/sample/RemoveElements.java | Java | art | 2,380 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package sample;
import org.apache.html.dom.HTMLDocumentImpl;
import org.cyberneko.html.parsers.DOMFragmentParser;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Node;
import org.w3c.dom.html.HTMLDocument;
/**
* This program tests the NekoHTML parser's use of the HTML DOM
* implementation to parse document fragments by printing the
* class names of all the nodes in the parsed document.
*
* @author Andy Clark
*
* @version $Id: TestHTMLDOMFragment.java,v 1.3 2004/02/19 20:00:17 andyc Exp $
*/
public class TestHTMLDOMFragment {
//
// MAIN
//
/** Main. */
public static void main(String[] argv) throws Exception {
DOMFragmentParser parser = new DOMFragmentParser();
HTMLDocument document = new HTMLDocumentImpl();
for (int i = 0; i < argv.length; i++) {
DocumentFragment fragment = document.createDocumentFragment();
parser.parse(argv[i], fragment);
print(fragment, "");
}
} // main(String[])
//
// Public static methods
//
/** Prints a node's class name. */
public static void print(Node node, String indent) {
System.out.println(indent+node.getClass().getName());
Node child = node.getFirstChild();
while (child != null) {
print(child, indent+" ");
child = child.getNextSibling();
}
} // print(Node)
} // class TestHTMLDOMFragment | zzh-simple-hr | Znekohtml/sample/sample/TestHTMLDOMFragment.java | Java | art | 2,047 |
package org.cyberneko.html;
import java.io.ByteArrayInputStream;
import junit.framework.TestCase;
import org.apache.xerces.parsers.AbstractSAXParser;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
/**
* Unit test for <a href="http://sourceforge.net/support/tracker.php?aid=2799585">Bug 2799585</a>.
* @author Charles Yates
* @author Marc Guillemot
*
*/
public class HeadNamespaceBug extends TestCase {
/**
* Ensure that the inserted head element has the right namespace
*/
public void testHeadNamespace() throws Exception {
final int[] nbTags = {0};
final ContentHandler handler = new DefaultHandler() {
public void startElement(final String ns, final String name, final String qName, final Attributes atts) {
assertEquals("http://www.w3.org/1999/xhtml:" + name, ns + ":" + name);
++nbTags[0];
}
};
InputSource source = new InputSource();
source.setByteStream(new ByteArrayInputStream("<html xmlns='http://www.w3.org/1999/xhtml'><body/></html>".getBytes()));
HTMLConfiguration conf = new HTMLConfiguration();
conf.setProperty("http://cyberneko.org/html/properties/names/elems", "lower");
conf.setFeature("http://cyberneko.org/html/features/insert-namespaces", true);
AbstractSAXParser parser = new AbstractSAXParser(conf){};
parser.setContentHandler(handler);
parser.parse(source);
// to be sure that test doesn't pass just because handler has never been called
assertEquals(5, nbTags[0]);
}
}
| zzh-simple-hr | Znekohtml/test/org/cyberneko/html/HeadNamespaceBug.java | Java | art | 1,678 |
package org.cyberneko.html;
import java.io.IOException;
import org.apache.xerces.util.DefaultErrorHandler;
import org.apache.xerces.xni.XNIException;
import org.apache.xerces.xni.parser.XMLParseException;
/**
* Error handler for test purposes: just logs the errors to the provided PrintWriter.
* @author Marc Guillemot
*/
class HTMLErrorHandler extends DefaultErrorHandler {
private final java.io.Writer out_;
public HTMLErrorHandler(final java.io.Writer out) {
out_ = out;
}
/** @see DefaultErrorHandler#error(String,String,XMLParseException) */
public void error(final String domain, final String key,
final XMLParseException exception) throws XNIException {
println("Err", key, exception);
}
private void println(final String type, String key, XMLParseException exception) throws XNIException {
try {
out_.append("[" + type + "] "
+ key + " " + exception.getMessage() + "\n");
}
catch (final IOException e) {
throw new XNIException(e);
}
}
/** @see DefaultErrorHandler#warning(String,String,XMLParseException) */
public void warning(final String domain, final String key,
final XMLParseException exception) throws XNIException {
println("Warn", key, exception);
}
}
| zzh-simple-hr | Znekohtml/test/org/cyberneko/html/HTMLErrorHandler.java | Java | art | 1,282 |
/*
* Copyright 2005-2008 Andy Clark
*
* Licensed 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.
*/
package org.cyberneko.html;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* This class is an input stream filter that skips the first
* three bytes read if they match the UTF-8 byte order mark,
* 0xEFBBBF. The UTF-8 BOM is most often generated by Windows®
* tools.
*
* @author Andy Clark
*/
public class UTF8BOMSkipper
extends FilterInputStream {
//
// Data
//
/** Start of reading. */
private boolean fStart = true;
/** Byte offset. */
private int fOffset;
/** First three bytes. */
private int[] fFirst3Bytes;
//
// Constructors
//
/** Constructs a UTF-8 BOM skipper. */
public UTF8BOMSkipper(InputStream stream) {
super(stream);
} // <init>(InputStream)
//
// InputStream methods
//
/** Returns the next byte. */
public int read() throws IOException {
// read first three bytes in order to skip UTF-8 BOM, if present
if (fStart) {
fStart = false;
int b1 = super.read();
int b2 = super.read();
int b3 = super.read();
if (b1 != 0xEF || b2 != 0xBB || b3 != 0xBF) {
fFirst3Bytes = new int[3];
fFirst3Bytes[0] = b1;
fFirst3Bytes[1] = b2;
fFirst3Bytes[2] = b3;
}
}
// return read bytes
if (fFirst3Bytes != null) {
int b = fFirst3Bytes[fOffset++];
if (fOffset == fFirst3Bytes.length) {
fFirst3Bytes = null;
}
return b;
}
// return next char
return super.read();
} // read():int
/** Reads bytes into specified buffer and returns total bytes read. */
public int read(byte[] buffer, int offset, int length) throws IOException {
if (fStart || fFirst3Bytes != null) {
for (int i = 0; i < length; i++) {
int b = this.read();
if (b == -1) {
return i > 0 ? i : -1;
}
buffer[offset + i] = (byte)b;
}
return length;
}
return super.read(buffer, offset, length);
} // read(byte[],int,int):int
/** Mark is not supported for this input stream. */
public boolean markSupported() {
return false;
} // markSupported():boolean
/** Returns the number of bytes available. */
public int available() throws IOException {
if (fFirst3Bytes != null) {
return fFirst3Bytes.length - fOffset;
}
return super.available();
} // available():int
} // class UTF8BOMSkipper
| zzh-simple-hr | Znekohtml/test/org/cyberneko/html/UTF8BOMSkipper.java | Java | art | 3,304 |
/*
* Copyright 2002-2009 Andy Clark, Marc Guillemot
*
* Licensed 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.
*/
package org.cyberneko.html;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import org.apache.xerces.util.XMLStringBuffer;
import org.apache.xerces.xni.Augmentations;
import org.apache.xerces.xni.NamespaceContext;
import org.apache.xerces.xni.QName;
import org.apache.xerces.xni.XMLAttributes;
import org.apache.xerces.xni.XMLLocator;
import org.apache.xerces.xni.XMLString;
import org.apache.xerces.xni.XNIException;
import org.cyberneko.html.filters.DefaultFilter;
/**
* This class implements an filter to output "canonical" files for
* regression testing.
*
* @author Andy Clark
*/
public class Writer
extends DefaultFilter {
//
// Data
//
/** Writer. */
protected PrintWriter out = new PrintWriter(System.out);
// temp vars
/** String buffer for collecting text content. */
private final XMLStringBuffer fStringBuffer = new XMLStringBuffer();
/** Are we currently in the middle of a block of characters? */
private boolean fInCharacters = false;
/**
* Beginning line number of the current block of characters (which may be
* reported in several characters chunks). Will be -1 if the parser
* isn't producing HTML augmentations.
*/
private int fCharactersBeginLine = -1;
/**
* Beginning column number of the current block of characters (which may be
* reported in several characters chunks). Will be -1 if the parser
* isn't producing HTML augmentations.
*/
private int fCharactersBeginColumn = -1;
/**
* Beginning character offset of the current block of characters (which may
* be reported in several characters chunks). Will be -1 if the parser
* isn't producing HTML augmentations.
*/
private int fCharactersBeginCharacterOffset = -1;
/**
* Ending line number of the current block of characters (which may be
* reported in several characters chunks). Will be -1 if the parser
* isn't producing HTML augmentations.
*/
private int fCharactersEndLine = -1;
/**
* Ending column number of the current block of characters (which may be
* reported in several characters chunks). Will be -1 if the parser
* isn't producing HTML augmentations.
*/
private int fCharactersEndColumn = -1;
/**
* Ending character offset of the current block of characters (which may be
* reported in several characters chunks). Will be -1 if the parser isn't
* producing HTML augmentations.
*/
private int fCharactersEndCharacterOffset = -1;
//
// Constructors
//
/**
* Creates a writer to the standard output stream using UTF-8
* encoding.
*/
public Writer() {
this(System.out);
} // <init>()
/**
* Creates a writer with the specified output stream using UTF-8
* encoding.
*/
public Writer(OutputStream stream) {
this(stream, "UTF8");
} // <init>(OutputStream)
/** Creates a writer with the specified output stream and encoding. */
public Writer(OutputStream stream, String encoding) {
try {
out = new PrintWriter(new OutputStreamWriter(stream, encoding), true);
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException("JVM must have "+encoding+" decoder");
}
} // <init>(OutputStream,String)
/** Creates a writer with the specified Java Writer. */
public Writer(java.io.Writer writer) {
out = new PrintWriter(writer);
} // <init>(java.io.Writer)
//
// XMLDocumentHandler methods
//
// since Xerces-J 2.2.0
/** Start document. */
public void startDocument(XMLLocator locator, String encoding,
NamespaceContext nscontext, Augmentations augs) throws XNIException {
fStringBuffer.clear();
} // startDocument(XMLLocator,String,NamespaceContext,Augmentations)
/** End document. */
public void endDocument(Augmentations augs) throws XNIException {
chars();
}
// old methods
/** Start document. */
public void startDocument(XMLLocator locator, String encoding, Augmentations augs) throws XNIException {
startDocument(locator, encoding, null, augs);
} // startDocument(XMLLocator,String,Augmentations)
/** XML declaration. */
public void xmlDecl(String version, String encoding, String standalone,
Augmentations augs) throws XNIException {
doAugs(augs);
if (version!=null) {
out.print("xversion ");
out.println(version);
}
if (encoding!=null) {
out.print("xencoding ");
out.println(encoding);
}
if (standalone!=null) {
out.print("xstandalone ");
out.println(standalone);
}
out.flush();
} // xmlDecl(String,String,String,Augmentations)
/** Doctype declaration. */
public void doctypeDecl(String root, String pubid, String sysid, Augmentations augs) throws XNIException {
chars();
doAugs(augs);
out.print('!');
if (root != null) {
out.print(root);
}
out.println();
if (pubid != null) {
out.print('p');
out.print(pubid);
out.println();
}
if (sysid != null) {
out.print('s');
out.print(sysid);
out.println();
}
out.flush();
} // doctypeDecl(String,String,String,Augmentations)
/** Processing instruction. */
public void processingInstruction(String target, XMLString data, Augmentations augs) throws XNIException {
chars();
doAugs(augs);
out.print('?');
out.print(target);
if (data != null && data.length > 0) {
out.print(' ');
print(data.toString());
}
out.println();
out.flush();
} // processingInstruction(String,XMLString,Augmentations)
/** Comment. */
public void comment(XMLString text, Augmentations augs) throws XNIException {
chars();
doAugs(augs);
out.print('#');
print(text.toString());
out.println();
out.flush();
} // comment(XMLString,Augmentations)
/** Start element. */
public void startElement(QName element, XMLAttributes attrs, Augmentations augs) throws XNIException {
chars();
doAugs(augs);
out.print('(');
out.print(element.rawname);
int acount = attrs != null ? attrs.getLength() : 0;
if (acount > 0) {
String[] anames = new String[acount];
String[] auris = new String[acount];
sortAttrNames(attrs, anames, auris);
for (int i = 0; i < acount; i++) {
String aname = anames[i];
out.println();
out.flush();
out.print('A');
if (auris[i] != null) {
out.print('{');
out.print(auris[i]);
out.print('}');
}
out.print(aname);
out.print(' ');
print(attrs.getValue(aname));
}
}
out.println();
out.flush();
} // startElement(QName,XMLAttributes,Augmentations)
/** End element. */
public void endElement(QName element, Augmentations augs) throws XNIException {
chars();
doAugs(augs);
out.print(')');
out.print(element.rawname);
out.println();
out.flush();
} // endElement(QName,Augmentations)
/** Empty element. */
public void emptyElement(QName element, XMLAttributes attrs, Augmentations augs) throws XNIException {
startElement(element, attrs, augs);
endElement(element, augs);
} // emptyElement(QName,XMLAttributes,Augmentations)
/** Characters. */
public void characters(XMLString text, Augmentations augs) throws XNIException {
storeCharactersEnd(augs);
if(!fInCharacters) {
storeCharactersStart(augs);
}
fInCharacters = true;
fStringBuffer.append(text);
} // characters(XMLString,Augmentations)
/** Ignorable whitespace. */
public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException {
characters(text, augs);
} // ignorableWhitespace(XMLString,Augmentations)
public void startCDATA(Augmentations augs) throws XNIException {
chars();
doAugs(augs);
out.println("((CDATA");
}
public void endCDATA(Augmentations augs) throws XNIException {
chars();
doAugs(augs);
out.println("))CDATA");
out.flush();
}
//
// Protected methods
//
/** Prints collected characters. */
protected void chars() {
fInCharacters = false;
if (fStringBuffer.length == 0) {
return;
}
doCharactersAugs();
out.print('"');
print(fStringBuffer.toString());
out.println();
out.flush();
fStringBuffer.clear();
} // chars()
/** Prints the specified string. */
protected void print(String s) {
int length = s != null ? s.length() : 0;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
switch (c) {
case '\n': {
out.print("\\n");
break;
}
case '\r': {
out.print("\\r");
break;
}
case '\t': {
out.print("\\t");
break;
}
case '\\': {
out.print("\\\\");
break;
}
default: {
out.print(c);
}
}
}
} // print(String)
/**
* Print out the HTML augmentations for the given augs. Prints nothing if
* there are no HTML augmentations available.
*/
protected void doAugs(Augmentations augs) {
HTMLEventInfo evInfo = (augs == null) ? null : (HTMLEventInfo)augs
.getItem("http://cyberneko.org/html/features/augmentations");
if(evInfo != null) {
if(evInfo.isSynthesized()) {
out.print("[synth]");
}
else {
out.print('[');
out.print(evInfo.getBeginLineNumber());
out.print(',');
out.print(evInfo.getBeginColumnNumber());
out.print(',');
out.print(evInfo.getBeginCharacterOffset());
out.print(';');
out.print(evInfo.getEndLineNumber());
out.print(',');
out.print(evInfo.getEndColumnNumber());
out.print(',');
out.print(evInfo.getEndCharacterOffset());
out.print(']');
}
}
} // doAugs(Augmentations)
/**
* Store the HTML augmentations for the given augs in temporary variables
* for the start of the current block of characters. Does nothing if there
* are no HTML augmentations available.
*/
protected void storeCharactersStart(Augmentations augs) {
HTMLEventInfo evInfo = (augs == null) ? null : (HTMLEventInfo)augs
.getItem("http://cyberneko.org/html/features/augmentations");
if(evInfo != null) {
fCharactersBeginLine = evInfo.getBeginLineNumber();
fCharactersBeginColumn = evInfo.getBeginColumnNumber();
fCharactersBeginCharacterOffset = evInfo.getBeginCharacterOffset();
}
} // storeCharactersStart(Augmentations)
/**
* Store the HTML augmentations for the given augs in temporary variables
* for the end of the current block of characters. Does nothing if there
* are no HTML augmentations available.
*/
protected void storeCharactersEnd(Augmentations augs) {
HTMLEventInfo evInfo = (augs == null) ? null : (HTMLEventInfo)augs
.getItem("http://cyberneko.org/html/features/augmentations");
if(evInfo != null) {
fCharactersEndLine = evInfo.getEndLineNumber();
fCharactersEndColumn = evInfo.getEndColumnNumber();
fCharactersEndCharacterOffset = evInfo.getEndCharacterOffset();
}
} // storeCharactersEnd(Augmentations)
/**
* Print out the HTML augmentation values for the current block of
* characters. Prints nothing if there were no HTML augmentations
* available.
*/
protected void doCharactersAugs() {
if(fCharactersBeginLine >= 0) {
out.print('[');
out.print(fCharactersBeginLine);
out.print(',');
out.print(fCharactersBeginColumn);
out.print(',');
out.print(fCharactersBeginCharacterOffset);
out.print(';');
out.print(fCharactersEndLine);
out.print(',');
out.print(fCharactersEndColumn);
out.print(',');
out.print(fCharactersEndCharacterOffset);
out.print(']');
}
} // doCharactersAugs()
//
// Protected static methods
//
/** Sorts the attribute names. */
protected static void sortAttrNames(XMLAttributes attrs,
String[] anames, String[] auris) {
for (int i = 0; i < anames.length; i++) {
anames[i] = attrs.getQName(i);
auris[i] = attrs.getURI(i);
}
// NOTE: This is super inefficient but it doesn't really matter. -Ac
for (int i = 0; i < anames.length - 1; i++) {
int index = i;
for (int j = i + 1; j < anames.length; j++) {
if (anames[j].compareTo(anames[index]) < 0) {
index = j;
}
}
if (index != i) {
String tn = anames[i];
anames[i] = anames[index];
anames[index] = tn;
String tu = auris[i];
auris[i] = auris[index];
auris[index] = tu;
}
}
} // sortAttrNames(XMLAttributes,String[])
//
// MAIN
//
/** Main program. */
public static void main(String[] argv) throws Exception {
org.apache.xerces.xni.parser.XMLDocumentFilter[] filters = {
new Writer(),
};
org.apache.xerces.xni.parser.XMLParserConfiguration parser =
new org.cyberneko.html.HTMLConfiguration();
parser.setProperty("http://cyberneko.org/html/properties/filters", filters);
for (int i = 0; i < argv.length; i++) {
org.apache.xerces.xni.parser.XMLInputSource source =
new org.apache.xerces.xni.parser.XMLInputSource(null, argv[i], null);
parser.parse(source);
}
} // main(String[])
} // class Writer
| zzh-simple-hr | Znekohtml/test/org/cyberneko/html/Writer.java | Java | art | 15,789 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>游戏</title>
<meta name="keywords" content="" />
<meta name="description" content="" />
<link rel="stylesheet" type="text/css" href="css/Global.css" media="all" />
<script stype="text/javascript">
var opens = []; //存放用于抽奖的1~200
var dict = {4:10,3:5,2:3,1:1}; //存放抽奖规则
var theLno = 5; //当前第几等奖
// var nodes = null; //当前被抽中的
var cNum = 0; //递增值,摇号次数
var theNum = 60; //停止条件值
var theTimer = null;
//初始化抽奖编码
(function initOpens(){
for(var n = 0; n < 200; n++) {
opens[n] = n + 1;
}
})();
//实现抽奖
function doGame() {
if(theLno == 1) return;
theLno--;
$("lno").innerHTML = theLno + "等奖:";
// nodes = selectNo(); //选出中奖号码
okview(); //渲染界面
}
function selectFrom(iFirstValue, iLastValue){
var iChoices = iLastValue-iFirstValue+1;
var temp = Math.floor(Math.random()*iChoices+iFirstValue);
if(temp < 10){
return "00"+temp;
}else if(temp < 100){
return "0"+temp;
}else{
return temp;
}
}
function okview(){
cNum++;
theTimer = setTimeout("okview()", 2);
var nos = dict[theLno]; //获得要抽出的号码个数
if(nos == 3){
$("_c").style.paddingLeft = "180px";
}else if(nos == 1) {
$("_c").style.paddingLeft = "360px";
}
var html = "";
if(cNum > theNum) {
cNum = 0;
clearTimeout(theTimer);
var nodes = selectNo(); //选出中奖号码
for(var j = 0; j < nodes.length; j++) {
html += "<div class=\"or\" id=\"no" + j + "\"><span>" + nodes[j] + "</span></div>";
}
$("_c").innerHTML = html;
return;
}
for(var n = 0; n < nos; n++) {
var no = selectFrom(1, 200);
html += "<div class=\"or\" id=\"no" + n + "\"><span>" + no + "</span></div>";
}
$("_c").innerHTML = html;
}
//在opens中产生随机数
function myRandom(){
var iChoices = opens.length;
var cusor = Math.floor(Math.random()*iChoices+0);
var rval = opens[cusor];
opens.splice(cusor, 1);
return rval;
}
function selectNo() {
var nos = dict[theLno]; //获得要抽出的号码个数
var rval = [];
for(n = 0; n < nos; n++) {
rval[n] = myRandom();
}
return rval;
}
function $(i) {
return document.getElementById(i);
}
//注册事件
document.onkeydown = function(_e){
_e = _e || event;
if(_e.keyCode == 32) doGame();
};
</script>
</head>
<body>
<div class="abody" style="height:600px;">
<div class="logo_media"><img src="images/logo_media.png" /></div>
<div class="logo"><img src="images/logo.png" /></div>
<div class="line_01" id="lno">4等奖:</div>
<div class="line_02" id="_c">
<div class="or" id="no1"><span>000</span></div>
<div class="or" id="no2"><span>000</span></div>
<div class="or" id="no3"><span>000</span></div>
<div class="or" id="no4"><span>000</span></div>
<div class="or" id="no5"><span>000</span></div>
<div class="or" id="no1"><span>000</span></div>
<div class="or" id="no2"><span>000</span></div>
<div class="or" id="no3"><span>000</span></div>
<div class="or" id="no4"><span>000</span></div>
<div class="or" id="no5"><span>000</span></div>
</div>
</div>
</body>
</html>
| zzh-simple-hr | Zhopool/document/抽奖/index.html | HTML | art | 3,863 |
body{font-size:12px; font-family:Verdana, "Lucida Grande", Arial, Helvetica, sans-serif; color:#333;}
body{ padding:0px; margin:0px; background:#FFF;}
div,ul,li,img,p{ margin:0px; padding:0px;}
a img{ border:0px;}
.bold {font-weight:bold;}
.normal {font-weight:normal;}
.pointer {cursor:pointer;}
.underline a , .underline a:visited , .underline a:hover{ text-decoration:underline; }
.notunderline a , .notunderline a:visited { text-decoration:none; }
.notunderline a:hover{ text-decoration:underline;}
.left{ float:left;}
.right{ float:right;}
.align-center{ margin-left:auto; margin-right:auto;}
.margin-t-7{ margin-top:7px;}
.margin-b-7{ margin-bottom:7px;}
.width250{ width:250px;}
.width350{ width:350px;}
.blue a , .blue a:visited { color:#157DFE;}
.blue a:hover{ color:#2268E8; }
.gray{color:#999;}
.red{color:#F00;}
.clear { clear:both; }
.abody{ background:url("../images/body_bg.jpg") center bottom no-repeat; width:1000px; margin:auto; position:relative;}
.logo_media{ position:absolute; left:0px;}
.logo{ position:absolute; right:60px;}
.logo_media img{azimuth:expression(this.pngSet?this.pngSet=true:(this.nodeName == "IMG" && this.src.toLowerCase().indexOf('.png')>-1?(this.runtimeStyle.backgroundImage = "none",this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "', sizingMethod='image')",this.src = "images/transparent.gif"):(this.origBg = this.origBg? this.origBg :this.currentStyle.backgroundImage.toString().replace('url("','').replace('")',''),this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.origBg + "', sizingMethod='crop')",this.runtimeStyle.backgroundImage = "none")),this.pngSet=true);}
.logo img{azimuth:expression(this.pngSet?this.pngSet=true:(this.nodeName == "IMG" && this.src.toLowerCase().indexOf('.png')>-1?(this.runtimeStyle.backgroundImage = "none",this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "', sizingMethod='image')",this.src = "images/transparent.gif"):(this.origBg = this.origBg? this.origBg :this.currentStyle.backgroundImage.toString().replace('url("','').replace('")',''),this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.origBg + "', sizingMethod='crop')",this.runtimeStyle.backgroundImage = "none")),this.pngSet=true);}
.line_01{ position:absolute; top:110px; left:20px;}
.line_01{ color:#fff; font-size:70px; font-size-adjust:none; font-stretch:normal; font-style:normal; font-variant:normal; line-height:100px; margin-bottom:6px; font-weight:800; text-align:center;}
.line_02{ position:absolute; top:210px; padding-left:40px;}
.line_02 .or{ float:left; margin:10px; height:160px; width:160px; background:#E2B0BB; text-align:center;}
.line_02 .or{ color:#fff; font-size:70px; font-size-adjust:none; font-stretch:normal; font-style:normal; font-variant:normal; line-height:100px; margin-bottom:6px; font-weight:800; text-align:center;}
.line_02 .or span{ display:block; padding-top:25px;} | zzh-simple-hr | Zhopool/document/抽奖/css/Global.css | CSS | art | 3,074 |
package com.hopool.shop.exception;
public class ServiceException extends Exception{
public ServiceException() {
super();
}
public ServiceException(String message) {
super(message);
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/exception/ServiceException.java | Java | art | 211 |
package com.hopool.shop.exception;
public class OrderException extends Exception{
public OrderException() {
super();
}
public OrderException(String message) {
super(message);
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/exception/OrderException.java | Java | art | 205 |
package com.hopool.shop.service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hopool.shop.BaseTest;
public class ServiceBaseTest extends BaseTest {
protected ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
public ServiceBaseTest() {
super();
}
public ServiceBaseTest(String name) {
super(name);
}
@Override
protected void setUp() throws Exception {
}
@Override
protected void tearDown() throws Exception {
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/service/ServiceBaseTest.java | Java | art | 587 |
package com.hopool.shop.service;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.hopool.shop.dao.BaseDao;
import com.hopool.shop.exception.ServiceException;
public class BaseService implements BaseServiceI{
protected BaseDao baseDao;
protected JdbcTemplate jdbcTemplate;
protected SessionFactory sessionFactory;
protected HibernateTemplate hibernateTemplate;
public void setBaseDao(BaseDao baseDao) {
this.baseDao = baseDao;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Session getSession(){
return sessionFactory.getCurrentSession();
}
public List page(Object exampleobj, Integer firstResult,
Integer maxResults, String orderType, String... customProperties)
throws ServiceException {
return baseDao.page(exampleobj, firstResult, maxResults, orderType, customProperties);
}
public Integer count(Object exampleobj, String... customProperties)
throws ServiceException {
return baseDao.count(exampleobj, customProperties);
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/service/BaseService.java | Java | art | 1,455 |
package com.hopool.shop.service.order;
import java.util.List;
import com.hopool.shop.exception.OrderException;
import com.hopool.shop.order.Order;
import com.hopool.shop.order.OrderProducts;
import com.hopool.shop.service.BaseServiceI;
public interface OrderServiceI extends BaseServiceI{
public void addOrder(Order order)throws OrderException;
public void processOrder(Order order)throws OrderException;
public Order getOrderById(Long orderId)throws OrderException;
public Order getOrderByCode(String code)throws OrderException;
public List<OrderProducts> getOrderDetail(Long orderId)throws OrderException;
public void deleteOrder(Order order)throws OrderException;
public OrderProducts getOrderProduct(Long opId)throws OrderException;
public void modifyOrderProducts(List<OrderProducts> ops)throws OrderException;
public void deleteOrderProducts(List<OrderProducts> ops)throws OrderException;
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/service/order/OrderServiceI.java | Java | art | 956 |
package com.hopool.shop.service.order;
import java.util.List;
import org.hibernate.Session;
import com.hopool.shop.exception.OrderException;
import com.hopool.shop.exception.ServiceException;
import com.hopool.shop.order.Order;
import com.hopool.shop.order.OrderProducts;
import com.hopool.shop.service.BaseService;
public class OrderService extends BaseService implements OrderServiceI{
@Override
public List page(Object exampleobj, Integer firstResult,
Integer maxResults, String orderType, String... customProperties)
throws ServiceException {
return super.page(exampleobj, firstResult, maxResults, orderType,
customProperties);
}
@Override
public Integer count(Object exampleobj, String... customProperties)
throws ServiceException {
return super.count(exampleobj, customProperties);
}
public void addOrder(Order order)throws OrderException{
getSession().save(order);
}
public void processOrder(Order order)throws OrderException{
getSession().update(order);
}
public Order getOrderById(Long orderId)throws OrderException{
return (Order)getSession().get(Order.class, orderId);
}
public Order getOrderByCode(String code)throws OrderException{
return (Order) getSession()
.createQuery("from Order o where o.orderNumber=?")
.setString(0, code).uniqueResult();
}
public List<OrderProducts> getOrderDetail(Long orderId)throws OrderException{
return getSession()
.createQuery("from OrderProducts op where op.order.id=?")
.setLong(0, orderId).list();
}
public void deleteOrder(Order order)throws OrderException{
getSession().delete(order);
}
public OrderProducts getOrderProduct(Long opId)throws OrderException{
return (OrderProducts) getSession().get(OrderProducts.class, opId);
}
public void modifyOrderProducts(List<OrderProducts> ops)throws OrderException{
for(OrderProducts op:ops){
getSession().saveOrUpdate(op);
}
}
public void deleteOrderProducts(List<OrderProducts> ops)throws OrderException{
for(OrderProducts op:ops){
getSession().delete(op);
}
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/service/order/OrderService.java | Java | art | 2,137 |
package com.hopool.shop.service;
import java.util.List;
import org.hibernate.Session;
import com.hopool.shop.exception.ServiceException;
public interface BaseServiceI {
public List page(Object exampleobj,Integer firstResult,
Integer maxResults,String orderType,String... customProperties)throws ServiceException;
public Integer count(Object exampleobj,String... customProperties)throws ServiceException;
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/service/BaseServiceI.java | Java | art | 431 |
package com.hopool.shop.member;
import java.util.Date;
import org.hibernate.Session;
import com.hopool.shop.BaseTest;
public class MemberTest extends BaseTest{
public void testMemberCRUD(){
Member mem = new Member();
mem.setAccount("xiao1");
mem.setEmail("as@dd.com");
mem.setMobile("130");
mem.setPassword("123");
mem.setRegisterDate(new Date());
Session s = sf.openSession();
s.getTransaction().begin();
s.save(mem);
mem.setEmail("zzh@163.com");
Member mem1 = (Member) s.get(Member.class, mem.getAccount());
assertEquals("zzh@163.com", mem1.getEmail());
s.delete(mem);
s.getTransaction().commit();
s.close();
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/member/MemberTest.java | Java | art | 697 |
package com.hopool.shop.member;
import java.util.Date;
public class Member {
private String account;
private String password;
private String mobile;
private String email;
private Date registerDate;
private Integer status;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getRegisterDate() {
return registerDate;
}
public void setRegisterDate(Date registerDate) {
this.registerDate = registerDate;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/member/Member.java | Java | art | 1,022 |
package com.hopool.shop;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import junit.framework.TestCase;
public class BaseTest extends TestCase{
protected SessionFactory sf;
public BaseTest() {
super();
}
public BaseTest(String name) {
super(name);
}
@Override
protected void setUp() throws Exception {
Configuration cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
}
@Override
protected void tearDown() throws Exception {
sf.close();
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/BaseTest.java | Java | art | 553 |
package com.hopool.shop.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.hopool.shop.BaseTest;
public class DaoBaseTest extends BaseTest {
protected ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
public DaoBaseTest() {
super();
}
public DaoBaseTest(String name) {
super(name);
}
@Override
protected void setUp() throws Exception {
// ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
// SessionFactory sf = (SessionFactory) ctx.getBean("sessionFactory");
}
@Override
protected void tearDown() throws Exception {
// SessionUtil.getCurrentSession().flush();
// SessionUtil.closeSession();
// SessionUtil.closeSessionFactory();
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/dao/DaoBaseTest.java | Java | art | 950 |
package com.hopool.shop.dao.product;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.hopool.shop.dao.BaseDao;
import com.hopool.shop.product.ProductType;
public class ProductTypeDao extends BaseDao{
public void deleteAllNode(){
getSession().createQuery("delete from ProductType").executeUpdate();
}
public List<ProductType> findFirstSubLevelNode(long parentId){
String hql = "from ProductType pt where pt.parentType = ?";
Query q = getSession().createQuery(hql);
q.setLong(0, parentId);
List<ProductType> pts = q.list();
return pts;
}
public ProductType findNodeByName(String nodeName){
return (ProductType) getSession()
.createQuery("from ProductType pt where pt.name=?").setString(0, nodeName).uniqueResult();
}
public List<ProductType> retrievFullTree(long rootId){
String hql = "select new ProductType" +
" (node.id,node.name,node.parentType,node.left,node.right,node.depth,node.createDate)" +
" from ProductType as node ,ProductType as parent" +
" where node.left between parent.left and parent.right" +
" and parent.id =?";
Query q = getSession().createQuery(hql);
q.setLong(0, rootId);
List<ProductType> pts = q.list();
return pts;
}
public List<ProductType> findAllLeafNodes(){
String hql = "from ProductType pt where pt.right = pt.left +1";
Query q = getSession().createQuery(hql);
List<ProductType> pts = q.list();
return pts;
}
public List<ProductType> retrievSinglePath(Long leafNodeId){
String hql = "select new ProductType" +
" (parent.id,parent.name,parent.parentType,parent.left,parent.right,parent.depth,parent.createDate)" +
" from ProductType node ,ProductType parent" +
" where node.left between parent.left and parent.right" +
" and node.id = ? " +
" order by parent.left";
Query q = getSession().createQuery(hql);
q.setLong(0, leafNodeId);
List<ProductType> pts = q.list();
return pts;
}
public List<ProductType> findDepthOfNodes(){
String hql = "select new ProductType" +
" (node.id,node.name,node.parentType,node.left,node.right,count(parent.name)-1,node.createDate)" +
" from ProductType node ,ProductType parent" +
" where node.left between parent.left and parent.right" +
" group by node.name" +
" order by node.left";
Query q = getSession().createQuery(hql);
List<ProductType> pts = q.list();
return pts;
}
public List<ProductType> findDepthOfSubTree(Long startNodeId){
String hql = "select new ProductType" +
" (node.id,node.name,node.parentType,node.left,node.right,count(parent.name)-(sub_tree.depth +1),node.createDate)" +
" from ProductType node,ProductType parent,ProductType sub_parent," +
" ProductTypeTreeDepth as sub_tree" + //hql suselect
" where node.left between parent.left and parent.right" +
" and node.left between sub_parent.left and sub_parent.right" +
" and sub_parent.name = sub_tree.name " +
" and sub_tree.id=?" +
" group by node.name" +
" order by node.left";
Query q = getSession().createQuery(hql);
q.setLong(0, startNodeId);
List<ProductType> pts = q.list();
return pts;
}
public List<ProductType> findImmediateSubordinatesNode(Long startNodeId,Long depth){
//TODO the native jdbc implement for the hql can not implements;
return null;
}
public boolean isProductTypeNoData(){
Long count = (Long) getSession().createQuery("select count(*) from ProductType pt").uniqueResult();
if(count>0){
return false;
}else{
return true;
}
}
public void addNewNodeTheSame(ProductType newPt,Long brotherPtId){
Session session = getSession();
ProductType brotherProductType =
(ProductType) session.createQuery("from ProductType pt where pt.id=?")
.setLong(0, brotherPtId).uniqueResult();
if(brotherProductType==null){
if(!isProductTypeNoData()){
throw new RuntimeException("the ProductType is not Exist for id: "+brotherPtId+" is error");
}
newPt.setDepth(0L);
newPt.setParentType(0L);
newPt.setLeft(1L);
newPt.setRight(2L);
}else{
Long myRight = brotherProductType.getRight();
session.createQuery("update ProductType pt set pt.right = pt.right+2 where pt.right > ?")
.setLong(0, myRight).executeUpdate();
session.createQuery("update ProductType pt set pt.left = pt.left+2 where pt.left > ?")
.setLong(0, myRight).executeUpdate();
newPt.setDepth(brotherProductType.getDepth());
newPt.setParentType(brotherProductType.getParentType());
newPt.setLeft(myRight+1);
newPt.setRight(myRight+2);
}
session.save(newPt);
}
public void addNewNodeTheChild(ProductType newPt,Long parentPtId){
Session session = getSession();
ProductType parentProductType =
(ProductType) session.createQuery("from ProductType pt where pt.id=?")
.setLong(0, parentPtId).uniqueResult();
if(parentProductType==null){
if(!isProductTypeNoData()){
throw new RuntimeException("the ProductType is not Exist for id: "+parentPtId+" is error");
}
newPt.setDepth(0L);
newPt.setParentType(0L);
newPt.setLeft(1L);
newPt.setRight(2L);
}else{
Long myLeft = parentProductType.getLeft();
session.createQuery("update ProductType pt set pt.right = pt.right+2 where pt.right > ?")
.setLong(0, myLeft).executeUpdate();
session.createQuery("update ProductType pt set pt.left = pt.left+2 where pt.left > ?")
.setLong(0, myLeft).executeUpdate();
newPt.setDepth(parentProductType.getDepth()+1);
newPt.setParentType(parentProductType.getId());
newPt.setLeft(myLeft+1);
newPt.setRight(myLeft+2);
}
session.save(newPt);
}
public void deleteNode(Long deletePtId){
Session session = getSession();
ProductType pt =
(ProductType) session.createQuery("from ProductType pt where pt.id=?")
.setLong(0, deletePtId).uniqueResult();
Long myLeft = pt.getLeft();
Long myRight = pt.getRight();
Long myWidth = pt.getRight() - pt.getLeft() +1;
session.createQuery("delete from ProductType pt where pt.left between ? and ?")
.setLong(0, myLeft).setLong(1, myRight).executeUpdate();
session.createQuery("update ProductType pt set pt.right = pt.right-? where pt.right > ?")
.setLong(0, myWidth).setLong(1, myRight).executeUpdate();
session.createQuery("update ProductType pt set pt.left = pt.left-? where pt.left > ?")
.setLong(0, myWidth).setLong(1, myRight).executeUpdate();
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/dao/product/ProductTypeDao.java | Java | art | 6,838 |
package com.hopool.shop.dao.product;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Projections;
import com.hopool.shop.dao.BaseDao;
import com.hopool.shop.product.Product;
public class ProductDao extends BaseDao{
/*
@SuppressWarnings("unchecked")
public List page(Object exampleobj,Integer firstResult,
Integer maxResult,String orderType,String... customProperties){
Example example =
Example.create(exampleobj)
.excludeZeroes() //exclude zero valued properties
// .excludeProperty("color") //exclude the property named "color"
.ignoreCase() //perform case insensitive string comparisons
.enableLike();
List ps =
getSession().createCriteria(exampleobj.getClass()).add(example)
// .createCriteria("productType").add(Example.create(exampleProduct.getProductType()))
.setFirstResult(firstResult).setMaxResults(maxResult).list();
return ps;
}
public Integer count(Object exampleobj,String... customProperties){
Example example =
Example.create(exampleobj)
.excludeZeroes() //exclude zero valued properties
// .excludeProperty("color") //exclude the property named "color"
.ignoreCase() //perform case insensitive string comparisons
.enableLike();
return (Integer) getSession().createCriteria(exampleobj.getClass())
.setProjection(Projections.countDistinct("id"))
.add(example).uniqueResult();
}
*/
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/dao/product/ProductDao.java | Java | art | 1,577 |
package com.hopool.shop.dao.product;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.hopool.shop.dao.DaoBaseTest;
import com.hopool.shop.product.Product;
import com.hopool.shop.product.ProductType;
public class ProductDaoTest extends DaoBaseTest{
private ProductDao pd = (ProductDao) ctx.getBean("productDao");
public void testBaseCRUD(){
Session s = ((SessionFactory)ctx.getBean("sessionFactory")).openSession();
Product p = new Product();
p.setCode("10001");
p.setCreateDate(new Date());
p.setName("test");
p.setStatus("1");
s.beginTransaction();
s.save(p);
p.setName("testUpdate");
Product pDB = (Product) s.get(Product.class, p.getId());
assertEquals("testUpdate", pDB.getName());
s.getTransaction().commit();
s.beginTransaction();
s.delete(p);
s.getTransaction().commit();
s.beginTransaction();
Product pDB2 = (Product) s.get(Product.class, p.getId());
assertNull(pDB2);
s.getTransaction().commit();
}
public void testPage(){
Product p = new Product();
p.setCode("10");
p.setName("t");
ProductType pt = new ProductType();
pt.setId(2L);
pt.setName("test");
p.setProductType(pt);
pd.page(p, 0, 10,"asc","productType");
}
public void testCount(){
Product p = new Product();
p.setCode("10");
p.setName("t");
int i = pd.count(p,"productType");
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/dao/product/ProductDaoTest.java | Java | art | 1,434 |
package com.hopool.shop.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class BaseDao {
protected SessionFactory sessionFactory;
protected HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public Session getSession(){
return sessionFactory.getCurrentSession();
}
public List page(Object exampleobj,Integer firstResult,
Integer maxResults,String orderType,String... customProperties){
Example example =
Example.create(exampleobj)
.excludeZeroes()
.ignoreCase()
.enableLike();
Criteria crt = getSession().createCriteria(exampleobj.getClass());
crt.add(example);
if(orderType!=null&&PageUtil.isExistCreateTimeProp(exampleobj)){
if(orderType.equals(PageUtil.ORDER_ASC)){
crt.addOrder(Order.asc(PageUtil.DEFAULT_ORDER_PROPERTY));
}else{
crt.addOrder(Order.desc(PageUtil.DEFAULT_ORDER_PROPERTY));
}
}
this.addCustomProperties(exampleobj, crt, customProperties);
crt.setFirstResult(firstResult);
crt.setMaxResults(maxResults);
List list = crt.list();
return list;
}
public Integer count(Object exampleobj,String... customProperties){
Example example =
Example.create(exampleobj)
.excludeZeroes()
.ignoreCase()
.enableLike();
Criteria crt = getSession().createCriteria(exampleobj.getClass());
this.addCustomProperties(exampleobj, crt, customProperties);
crt.setProjection(Projections.rowCount());
crt.add(example);
return (Integer) crt.uniqueResult();
}
private void addCustomProperties(Object exampleobj,Criteria crt,String... customProperties){
for(String customProperty:customProperties){
Object obj = PageUtil.getCustomProperty(exampleobj, customProperty);
if(obj!=null){
crt.createCriteria(customProperty).add(Example.create(obj));
}
}
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/dao/BaseDao.java | Java | art | 2,331 |
package com.hopool.shop.dao;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import org.hibernate.Criteria;
public class PageUtil {
public static final String DEFAULT_ORDER_PROPERTY = "createDate";
public static final String ORDER_ASC = "asc";
public static final String ORDER_DESC = "desc";
public synchronized static boolean isExistCreateTimeProp(Object obj){
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
for(Field f:fields){
String fieldName = f.getName();
System.out.println(fieldName);
if(DEFAULT_ORDER_PROPERTY.toLowerCase().equals(fieldName.toLowerCase())){
return true;
}
}
return false;
}
public synchronized static Object getCustomProperty(Object objExample,String fieldName){
String method = "get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
Object fieldValue =null;
try {
fieldValue = objExample.getClass().getMethod(method).invoke(objExample);
} catch (Exception e) {
e.printStackTrace();
}
return fieldValue;
}
public static boolean isPrimitive(Class clazz){
try {
return ((Class) clazz.getField("TYPE").get(null)).isPrimitive();
}catch (Exception e) {
return false;
}
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/dao/PageUtil.java | Java | art | 1,290 |
package com.hopool.shop.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class SessionUtil {
protected static SessionFactory sf;
protected static ThreadLocal<Session> tl = new ThreadLocal<Session>();
static{
Configuration cfg = new Configuration().configure();
sf = cfg.buildSessionFactory();
}
public SessionFactory getSf() {
return sf;
}
public static Session getCurrentSession(){
Session s = tl.get();
if(s==null){
s = sf.openSession();
tl.set(s);
}
return s;
}
public static void closeSession(){
tl.get().close();
}
public static void closeSessionFactory(){
sf.close();
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/dao/SessionUtil.java | Java | art | 724 |
package com.hopool.shop.product;
import java.util.Date;
/**
*
* @author zzh
*
*/
public class Product {
private Long id;
private String name;
private String code;
// private String photo;
private Date createDate;
private String status;
private ProductType productType;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public ProductType getProductType() {
return productType;
}
public void setProductType(ProductType productType) {
this.productType = productType;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/product/Product.java | Java | art | 1,042 |
package com.hopool.shop.product;
import java.util.Date;
import java.util.List;
public class ProductType {
private Long id;
private String name;
private Long parentType;
private Long left;
private Long right;
private Long depth;
private Date createDate;
private List<Product> products;
public ProductType() {
super();
}
public ProductType(Long id, String name, Long depth) {
super();
this.id = id;
this.name = name;
this.depth = depth;
}
public ProductType(Long id, String name, Long left, Long right) {
super();
this.id = id;
this.name = name;
this.left = left;
this.right = right;
}
public ProductType(Long id, String name, Long parentType, Long left,
Long right, Long depth, Date createDate) {
super();
this.id = id;
this.name = name;
this.parentType = parentType;
this.left = left;
this.right = right;
this.depth = depth;
this.createDate = createDate;
}
public Long getDepth() {
return depth;
}
public void setDepth(Long depth) {
this.depth = depth;
}
public Long getLeft() {
return left;
}
public void setLeft(Long left) {
this.left = left;
}
public Long getRight() {
return right;
}
public void setRight(Long right) {
this.right = right;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getParentType() {
return parentType;
}
public void setParentType(Long parentType) {
this.parentType = parentType;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/product/ProductType.java | Java | art | 1,924 |
package com.hopool.shop.market;
public class PromotionalLimitTime extends Promotional{
private LimitTime limitTime;
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/market/PromotionalLimitTime.java | Java | art | 128 |
package com.hopool.shop.market;
import java.util.Date;
public class LimitTime{
private Date startDate;
private Date endDate;
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/market/LimitTime.java | Java | art | 399 |
package com.hopool.shop.market;
public class PromotionalType {
private Long id;
private String description;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/market/PromotionalType.java | Java | art | 365 |
package com.hopool.shop.market.integral;
public class Integral {
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/market/integral/Integral.java | Java | art | 74 |
package com.hopool.shop.market.gift;
public class Gift {
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/market/gift/Gift.java | Java | art | 66 |
package com.hopool.shop.market;
import java.util.List;
import com.hopool.shop.product.Product;
public class PromotionalProduct extends PromotionalLimitTime{
private List<Product> products;
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/market/PromotionalProduct.java | Java | art | 207 |
package com.hopool.shop.market;
import java.util.List;
import com.hopool.shop.product.ProductType;
public class PromotionalProductType extends PromotionalLimitTime{
private List<ProductType> productTypes;
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/market/PromotionalProductType.java | Java | art | 223 |
package com.hopool.shop.market;
import java.util.Date;
/**
* an abstract promotional
* @author Administrator
*
*/
public class Promotional {
private Long id;
private String name;
private Integer status;
private Date createDate;
private PromotionalType promotionalType;
public PromotionalType getPromotionalType() {
return promotionalType;
}
public void setPromotionalType(PromotionalType promotionalType) {
this.promotionalType = promotionalType;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/market/Promotional.java | Java | art | 962 |
package com.hopool.shop.market.award;
public class Award {
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/market/award/Award.java | Java | art | 68 |
package com.hopool.shop.market;
import java.util.List;
import com.hopool.shop.product.Product;
public class PromotionalAllMarket extends PromotionalLimitTime{
private List<Product> excludeProducts;
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/market/PromotionalAllMarket.java | Java | art | 216 |
package com.hopool.shop.market.charity;
public class Charity {
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/market/charity/Charity.java | Java | art | 72 |
package com.hopool.shop.order;
import java.util.Date;
import java.util.List;
import com.hopool.shop.member.Member;
public class Order {
private Long id;
private String orderNumber;
private Double money;
private String status;
private Date createDate;
private Member member;
private List<OrderProducts> orderProducts;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(String orderNumber) {
this.orderNumber = orderNumber;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Member getMember() {
return member;
}
public void setMember(Member member) {
this.member = member;
}
public List<OrderProducts> getOrderProducts() {
return orderProducts;
}
public void setOrderProducts(List<OrderProducts> orderProducts) {
this.orderProducts = orderProducts;
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/order/Order.java | Java | art | 1,285 |
package com.hopool.shop.order;
import com.hopool.shop.product.Product;
public class OrderProducts {
private Long id;
private Order order;
private Product product;
private Double productAmount;
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Double getProductAmount() {
return productAmount;
}
public void setProductAmount(Double productAmount) {
this.productAmount = productAmount;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
| zzh-simple-hr | Zshop/src/com/hopool/shop/order/OrderProducts.java | Java | art | 713 |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see http://ckeditor.com/license
*/
package com.ckeditor;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Helper class for CKEditor tags.
*/
public class TagHelper {
private static final String[] CHARS_FROM
= {"\\", "/", "\n", "\t", "\r", "\b", "\f", "\""};
private static final String[] CHARS_TO
= {"\\\\", "\\/", "\\\n", "\\\t", "\\\r", "\\\b", "\\\f", "\\\""};
/**
* Wraps a String with a JavaScript tag.
* @param input input String
* @return input wrapped with a JavaScript tag
*/
public static String script(final String input) {
String out = "<script type=\"text/javascript\">";
out += "//<![CDATA[\n";
out += input;
out += "\n//]]>";
out += "</script>\n";
return out;
}
/**
* Creates JavaScript code for including ckeditor.js.
* @param basePath CKEditor base path
* @param args script arguments
* @return JavaScript code
*/
public static String createCKEditorIncJS(final String basePath, final String args) {
return "<script type=\"text/javascript\" src=\""
+ basePath + "ckeditor.js" + args + "\"></script>\n";
}
/**
* Provides basic JSON support.
* @param o object to encode
* @return encoded configuration object value
*/
@SuppressWarnings("unchecked")
public static String jsEncode(final Object o) {
if (o == null) {
return "null";
}
if (o instanceof String) {
return jsEncode((String) o);
}
if (o instanceof Number) {
return jsEncode((Number) o);
}
if (o instanceof Boolean) {
return jsEncode((Boolean) o);
}
if (o instanceof Map) {
return jsEncode((Map<String, Object>) o);
}
if (o instanceof List) {
return jsEncode((List<Object>) o);
}
if (o instanceof CKEditorConfig) {
return jsEncode((CKEditorConfig) o);
}
return "";
}
/**
* Provides basic JSON support for String objects.
* @param s String object to encode
* @return encoded configuration String object value
*/
public static String jsEncode(final String s) {
if (s.indexOf("@@") == 0) {
return s.substring(2);
}
if (s.length() > 9
&& s.substring(0, 9).toUpperCase().equals("CKEDITOR.")) {
return s;
}
return clearString(s);
}
/**
* Provides basic JSON support for Number objects.
* @param n Number object to encode
* @return encoded Number object value
*/
public static String jsEncode(final Number n) {
return n.toString().replace(",", ".");
}
/**
* Provides basic JSON support for Boolean objects.
* @param b Boolean object to encode
* @return encoded Boolean object value
*/
public static String jsEncode(final Boolean b) {
return b.toString();
}
/**
* Provides basic JSON support for Map objects.
* @param map Map object to encode
* @return encoded Map object value
*/
public static String jsEncode(final Map<String, Object> map) {
StringBuilder sb = new StringBuilder("{");
for (Object obj : map.keySet()) {
if (sb.length() > 1) {
sb.append(",");
}
sb.append(jsEncode(obj));
sb.append(":");
sb.append(jsEncode(map.get(obj)));
}
sb.append("}");
return sb.toString();
}
/**
* Provides basic JSON support for List objects.
* @param list List object to encode
* @return encoded List object value
*/
public static String jsEncode(final List<Object> list) {
StringBuilder sb = new StringBuilder("[");
for (Object obj : list) {
if (sb.length() > 1) {
sb.append(",");
}
sb.append(jsEncode(obj));
}
sb.append("]");
return sb.toString();
}
/**
* Provides basic JSON support for the configuration object.
* @param config configuration object to encode
* @return encoded configuration object value
*/
public static String jsEncode(final CKEditorConfig config) {
StringBuilder sb = new StringBuilder("{");
for (Object obj : config.getConfigValues().keySet()) {
if (sb.length() > 1) {
sb.append(",");
}
sb.append(jsEncode(obj));
sb.append(":");
sb.append(jsEncode((config.getConfigValue((String) obj))));
}
sb.append("}");
return sb.toString();
}
/**
* Clears a String from special characters and quotes it.
* @param s input String
* @return cleared String
*/
private static String clearString(final String s) {
String string = s;
for (int i = 0; i < CHARS_FROM.length; i++) {
string = string.replace(CHARS_FROM[i], CHARS_TO[i]);
}
if (Pattern.compile("[\\[{].*[\\]}]").matcher(string).matches()) {
return string;
} else {
return "\"" + string + "\"";
}
}
}
| zzh-simple-hr | ZJs/src/com/ckeditor/TagHelper.java | Java | art | 4,815 |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see http://ckeditor.com/license
*/
package com.ckeditor;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* CKEditor event handler class.
* <b>Usage:</b>
* <pre>
EventHandler eventHandler = new EventHandler();
eventHandler.addEventHandler("instanceReady","function (ev) {
alert(\"Loaded: \" + ev.editor.name); }");
</pre>
*/
public class EventHandler {
protected Map<String, Set<String>> events;
/**
* Default constructor.
*/
public EventHandler() {
events = new HashMap<String, Set<String>>();
}
/**
* Adds an event listener.
* @param event Event name
* @param jsCode JavaScript anonymous function or a function name
*/
public void addEventHandler(final String event, final String jsCode) {
if (events.get(event) == null) {
events.put(event, new LinkedHashSet<String>());
}
events.get(event).add(jsCode);
}
/**
* Clears registered event handlers.
* @param event Event name. If null, all event handlers will be removed (optional).
*/
public void clearEventHandlers(final String event) {
if (event == null) {
events = new HashMap<String, Set<String>>();
} else {
if (events.get(event) != null) {
events.get(event).clear();
}
}
}
/**
* Gets all registered events.
* @return all registered events
*/
public Map<String, Set<String>> getEvents() {
return events;
}
}
| zzh-simple-hr | ZJs/src/com/ckeditor/EventHandler.java | Java | art | 1,578 |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see http://ckeditor.com/license
*/
package com.ckeditor;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
/**
* Base class for CKEditor tags.
*/
public abstract class CKEditorTag extends TagSupport {
private static final String TIMESTAMP = "B37D54V";
/**
*
*/
private static final long serialVersionUID = -5642419066547779817L;
private String basePath;
private String timestamp;
private boolean initialized;
private CKEditorConfig config;
private EventHandler events;
private GlobalEventHandler globalEvents;
/**
* Default constructor.
*/
public CKEditorTag() {
timestamp = "B37D54V";
basePath = "";
initialized = false;
config = null;
events = null;
}
@Override
public int doEndTag() throws JspException {
JspWriter out = pageContext.getOut();
configureContextParams();
try {
String output = "";
if (!initialized && !isInitializedParam()) {
out.write(init());
}
if (globalEvents != null) {
output += globalEvents.returnGlobalEvents();
}
CKEditorConfig cfg = null;
if (config != null) {
cfg = config.configSettings(this.events);
}
output += getTagOutput(cfg);
out.write(TagHelper.script(output));
} catch (Exception e) {
try {
HttpServletResponse resp = (HttpServletResponse)
pageContext.getResponse();
resp.reset();
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Problem with tag creation.");
e.printStackTrace();
} catch (IOException e1) {
throw new JspException(e1);
}
}
return EVAL_PAGE;
}
/**
* Adds to config params from pageContext. Used in integration with CKFinder.
*/
private void configureContextParams() {
if (pageContext.getAttribute("ckeditor-params") != null) {
@SuppressWarnings("unchecked")
Map<String, Map<String, String>> map =
(Map<String, Map<String, String>>)
pageContext.getAttribute("ckeditor-params");
if (map.get(getCKEditorName()) != null) {
parseParamsFromContext(map.get(getCKEditorName()));
} else if (map.get("*") != null) {
parseParamsFromContext(map.get("*"));
}
}
}
/**
* Parse params from pageContext attribute.
* @param map attributes map
*/
private void parseParamsFromContext(final Map<String, String> map) {
if (!map.isEmpty() && config == null) {
config = new CKEditorConfig();
}
for (String key : map.keySet()) {
config.addConfigValue(key, map.get(key));
}
}
/**
* Check if earlier CKEditor's have initialized ckeditor.js.
* @return true if have.
*/
private boolean isInitializedParam() {
if ("initialized".equals(pageContext.getAttribute("ckeditor-initialized"))) {
return true;
} else {
pageContext.setAttribute("ckeditor-initialized", "initialized");
return false;
}
}
/**
* Returns standard tag output.
* @param config configuration resolved to a string
* @return tag standard output
*/
protected abstract String getTagOutput(final CKEditorConfig config);
/**
* Initialization method for tags.
* @return include ckfinder.js code with attributes and additional code.
*/
protected String init() {
String out = "";
String args = "";
String ckeditorPath = getBasePath();
if (timestamp != null) {
args += "?t=" + timestamp;
}
if (ckeditorPath.contains("..")) {
out += TagHelper.script("window.CKEDITOR_BASEPATH='" + ckeditorPath + "';");
}
out += TagHelper.createCKEditorIncJS(ckeditorPath, args);
String extraCode = "";
if (timestamp != TIMESTAMP) {
extraCode += (extraCode.length() > 0) ? "\n" : ""
.concat("CKEDITOR.timestamp = '")
.concat(timestamp)
.concat("';");
}
if (extraCode.length() > 0) {
out += TagHelper.script(extraCode);
}
return out;
}
/**
* Checks if basePath contains "/" at the end and adds it if it does not.
* @return basePath or basePath with "/" added at the end
*/
private String getBasePath() {
if (basePath.equals("") || basePath.charAt(basePath.length() - 1) != '/') {
return basePath.concat("/");
} else {
return basePath;
}
}
/**
* @param basePath the basePath to set
*/
public final void setBasePath(final String basePath) {
this.basePath = basePath;
}
/**
* @return the timestamp attribute
*/
public final String getTimestamp() {
return timestamp;
}
/**
* @param timestamp the timestamp attribute to set
*/
public final void setTimestamp(final String timestamp) {
this.timestamp = timestamp;
}
/**
* @return the initialized attribute
*/
public final boolean isInitialized() {
return initialized;
}
/**
* @param initialized the initialized attribute to set
*/
public final void setInitialized(final boolean initialized) {
this.initialized = initialized;
}
/**
* @return the globalEvents attribute
*/
public final GlobalEventHandler getGlobalEvents() {
return globalEvents;
}
/**
* @param globalEvents the globalEvents attribute to set
*/
public final void setGlobalEvents(final GlobalEventHandler globalEvents) {
this.globalEvents = globalEvents;
}
/**
* @return the config attribute
*/
public final CKEditorConfig getConfig() {
return config;
}
/**
* @param config the config attribute to set
*/
public final void setConfig(final CKEditorConfig config) {
this.config = config;
}
/**
* @return the events attribute
*/
public final EventHandler getEvents() {
return events;
}
/**
* @param events the events attribute to set
*/
public final void setEvents(final EventHandler events) {
this.events = events;
}
/**
* gets name of the CKEditor instance.
* @return name if CKEditor instance.
*/
protected abstract String getCKEditorName();
}
| zzh-simple-hr | ZJs/src/com/ckeditor/CKEditorTag.java | Java | art | 6,221 |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see http://ckeditor.com/license
*/
package com.ckeditor;
/**
* <code><ckeditor:replaceAll></code> tag code.
* <b>Usage:</b>
* <pre><ckeditor:replaceAll basePath="/ckeditor/" /></pre>
*/
public class CKEditorReplaceAllTag extends CKEditorTag {
/**
*
*/
private static final long serialVersionUID = -7331873466295495480L;
private String className;
/**
* Default constructor.
*/
public CKEditorReplaceAllTag() {
this.className = "";
}
@Override
protected String getTagOutput(final CKEditorConfig config) {
if (config == null || config.isEmpty()) {
if (className == null || "".equals(className)) {
return "CKEDITOR.replaceAll();";
} else {
return "CKEDITOR.replaceAll('" + className + "');";
}
} else {
StringBuilder sb = new StringBuilder(
"CKEDITOR.replaceAll( function(textarea, config) {\n");
if (className != null && !"".equals(className)) {
sb.append(" var classRegex = new RegExp('(?:^| )' + '");
sb.append(className);
sb.append("' + '(?:$| )');\n");
sb.append(" if (!classRegex.test(textarea.className))\n");
sb.append(" return false;\n");
}
sb.append(" CKEDITOR.tools.extend(config, ");
sb.append(TagHelper.jsEncode(config));
sb.append(", true);} );");
return sb.toString();
}
}
/**
* @param className the class name to set
*/
public final void setClassName(final String className) {
this.className = className;
}
@Override
protected String getCKEditorName() {
return "";
}
}
| zzh-simple-hr | ZJs/src/com/ckeditor/CKEditorReplaceAllTag.java | Java | art | 1,672 |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see http://ckeditor.com/license
*/
/**
* CKEditor for Java - the server side integration for CKEditor.
*/
package com.ckeditor; | zzh-simple-hr | ZJs/src/com/ckeditor/package-info.java | Java | art | 230 |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see http://ckeditor.com/license
*/
package com.ckeditor;
/**
* <code><ckeditor:replace></code> tag code.
* <b>Usage:</b>
* <pre><ckeditor:replace replace="editor1" basePath="/ckeditor/" /></pre>
*/
public class CKEditorReplaceTag extends CKEditorTag {
/**
*
*/
private static final long serialVersionUID = 1316780332328233835L;
private String replace;
/**
* Default constructor.
*/
public CKEditorReplaceTag() {
replace = "";
}
@Override
protected String getTagOutput(final CKEditorConfig config) {
if (config != null && !config.isEmpty()) {
return "CKEDITOR.replace('" + replace + "', "
+ TagHelper.jsEncode(config) + ");";
} else {
return "CKEDITOR.replace('" + replace + "');";
}
}
/**
* @param replace the name of the replaced element to set
*/
public final void setReplace(final String replace) {
this.replace = replace;
}
@Override
protected String getCKEditorName() {
return this.replace;
}
}
| zzh-simple-hr | ZJs/src/com/ckeditor/CKEditorReplaceTag.java | Java | art | 1,125 |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see http://ckeditor.com/license
*/
package com.ckeditor;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
/**
* <code><ckeditor:editor></code> tag code.
*
* <b>Usage:</b>
* <pre><ckeditor:editor basePath="/ckeditor/" editor="editor1" /></pre>
*/
public class CKEditorInsertTag extends CKEditorTag {
private static final long serialVersionUID = 1316780332328233835L;
private static final String DEFAULT_TEXTAREA_ROWS = "8";
private static final String DEFAULT_TEXTAREA_COLS = "60";
private static final String[] CHARS_FROM = {"&", "\"", "<", ">"};
private static final String[] CHARS_TO = {"&", """, "<", ">"};
private String editor;
private String value;
private Map<String, String> textareaAttributes;
/**
* Default constructor.
*/
public CKEditorInsertTag() {
textareaAttributes = new HashMap<String, String>();
editor = "";
value = "";
}
@Override
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
try {
out.write(createTextareaTag());
} catch (Exception e) {
try {
HttpServletResponse resp = (HttpServletResponse)
pageContext.getResponse();
resp.reset();
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Problem with tag creation.");
} catch (IOException e1) {
throw new JspException(e1);
}
}
return EVAL_PAGE;
}
@Override
protected String getTagOutput(final CKEditorConfig config) {
if (config != null && !config.isEmpty()) {
return "CKEDITOR.replace('" + editor + "', "
+ TagHelper.jsEncode(config) + ");";
} else {
return "CKEDITOR.replace('" + editor + "');";
}
}
/**
* Creates HTML code to insert a textarea element into the page.
* @return textarea code
*/
private String createTextareaTag() {
StringBuilder sb = new StringBuilder();
sb.append("<textarea name=\"");
sb.append(editor);
sb.append("\" ");
sb.append(createTextareaAttributesText());
sb.append(" >");
sb.append(escapeHtml(value));
sb.append("</textarea>");
sb.append("\n");
return sb.toString();
}
/**
* Convert special characters to HTML entities.
* @param text
* @return
*/
private Object escapeHtml(String text) {
String result = text;
if (text.equals(""))
return "";
for (int i = 0; i < CHARS_FROM.length; i++) {
result = result.replaceAll(CHARS_FROM[i], CHARS_TO[i]);
}
return result;
}
/**
* Creates a String object from the textarea attributes map.
* @return textarea attributes String object
*/
private String createTextareaAttributesText() {
if (textareaAttributes.isEmpty()) {
textareaAttributes.put("rows", DEFAULT_TEXTAREA_ROWS);
textareaAttributes.put("cols", DEFAULT_TEXTAREA_COLS);
}
StringBuilder sb = new StringBuilder();
for (String s : textareaAttributes.keySet()) {
sb.append(" ");
sb.append(s + "=\"" + textareaAttributes.get(s) + "\"");
}
return sb.toString();
}
/**
* @param editor the editor to set
*/
public final void setEditor(final String editor) {
this.editor = editor;
}
/**
* @param value the String value to set
*/
public final void setValue(final String value) {
this.value = value;
}
/**
* @param textareaAttr the textarea attributes to set
*/
public final void setTextareaAttributes(final Map<String, String> textareaAttr) {
this.textareaAttributes = textareaAttr;
}
@Override
protected String getCKEditorName() {
return this.editor;
}
}
| zzh-simple-hr | ZJs/src/com/ckeditor/CKEditorInsertTag.java | Java | art | 3,876 |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see http://ckeditor.com/license
*/
package com.ckeditor;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* CKEditor global events class.
* <b>Usage:</b>
* <pre>
GlobalEventHandler globalEventHandler = new GlobalEventHandler();
globalEventHandler.addEventHandler("dialogDefinition","function (ev) {
alert(\"Loading dialog window: \" + ev.data.name); }");
</pre>
*/
public class GlobalEventHandler extends EventHandler {
private static Map<String, Set<String>> returndEvents;
/**
* Resolves global events to a String.
* @return global events resolved to a String
*/
String returnGlobalEvents() {
String out = "";
if (returndEvents == null) {
returndEvents = new HashMap<String, Set<String>>();
}
for (String event : events.keySet()) {
for (String code : events.get(event)) {
if (returndEvents.get(event) == null) {
returndEvents.put(event, new LinkedHashSet<String>());
}
out += (!code.equals("") ? "\n" : "")
+ "CKEDITOR.on('" + event + "', " + code + ");";
returndEvents.get(event).add(code);
}
}
return out;
}
}
| zzh-simple-hr | ZJs/src/com/ckeditor/GlobalEventHandler.java | Java | art | 1,303 |
/*
Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved.
For licensing, see http://ckeditor.com/license
*/
package com.ckeditor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* CKEditor configuration class.
*/
public class CKEditorConfig implements Cloneable {
private Map<String, Object> config;
/**
* Default constructor.
*/
public CKEditorConfig() {
config = new HashMap<String, Object>();
}
/**
* Adds a Number parameter to the configuration.
* <b>Usage:</b>
* <pre>config.addConfigValue("width", 100);</pre>
* <pre>config.addConfigValue("dialog_backgroundCoverOpacity", 0.7);</pre>
* @param key configuration parameter key
* @param value configuration parameter value.
*/
public void addConfigValue(final String key, final Number value) {
config.put(key, value);
}
/**
* Adds a String parameter to the configuration.
* <b>Usage:</b>
* <pre>config.addConfigValue("baseHref", "http://www.example.com/path/");</pre>
* <pre>config.addConfigValue("toolbar", "[[ 'Source', '-', 'Bold', 'Italic' ]]");</pre>
* @param key configuration parameter key
* @param value configuration parameter value.
*/
public void addConfigValue(final String key, final String value) {
config.put(key, value);
}
/**
* Adds a Map parameter to the configuration.
* <b>Usage:</b>
* <pre>Map<String, Object> map = new HashMap<String, Object>();</pre>
* <pre>map.put("element", "span");</pre>
* <pre>map.put("styles", "{'background-color' : '#(color)'}");</pre>
* <pre>config.addConfigValue("colorButton_backStyle", map);</pre>
* @param key configuration parameter key
* @param value configuration parameter value.
*/
public void addConfigValue(final String key,
final Map<String, ? extends Object> value) {
config.put(key, value);
}
/**
* Adds a List parameter to the configuration.
* <b>Usage:</b>
* <pre>
List<List<String>> list = new ArrayList<List<String>>();
List<String> subList = new ArrayList<String>();
subList.add("Source");
subList.add("-");
subList.add("Bold");
subList.add("Italic");
list.add(subList);
config.addConfigValue("toolbar", list);
</pre>
* @param key configuration parameter key
* @param value configuration parameter value.
*/
public void addConfigValue(final String key, final List<? extends Object> value) {
config.put(key, value);
}
/**
* Adds a Boolean parameter to the configuration.
* <b>Usage:</b>
* <pre>config.addConfigValue("autoUpdateElement", true);</pre>
* @param key configuration parameter key
* @param value configuration parameter value.
*/
public void addConfigValue(final String key, final Boolean value) {
config.put(key, value);
}
/**
* Gets a configuration value by key.
* @param key configuration parameter key
* @return configuration parameter value.
*/
Object getConfigValue(final String key) {
return config.get(key);
}
/**
* @return all configuration values.
*/
Map<String, Object> getConfigValues() {
return config;
}
/**
* Removes a configuration value by key.
* <b>Usage:</b>
* <pre>config.removeConfigValue("toolbar");</pre>
* @param key configuration parameter key.
*/
public void removeConfigValue(final String key) {
config.remove(key);
}
/**
* Configure settings. Merge configuration and event handlers.
* @return setting configuration.
* @param eventHandler events
*/
CKEditorConfig configSettings(final EventHandler eventHandler) {
try {
CKEditorConfig cfg = (CKEditorConfig) this.clone();
if (eventHandler != null) {
for (String eventName : eventHandler.events.keySet()) {
Set<String> set = eventHandler.events.get(eventName);
if (set.isEmpty()) {
continue;
} else if (set.size() == 1) {
Map<String, String> hm = new HashMap<String, String>();
for (String code : set) {
hm.put(eventName, "@@" + code);
}
cfg.addConfigValue("on", hm);
} else {
Map<String, String> hm = new HashMap<String, String>();
StringBuilder sb = new StringBuilder("@@function (ev){");
for (String code : set) {
sb.append("(");
sb.append(code);
sb.append(")(ev);");
}
sb.append("}");
hm.put(eventName, sb.toString());
cfg.addConfigValue("on", hm);
}
}
}
return cfg;
} catch (CloneNotSupportedException e) {
return null;
}
}
/**
* Checks if configuration is empty.
* @return true if the configuration is empty.
*/
public boolean isEmpty() {
return config.isEmpty();
}
/**
* Override.
*/
protected Object clone() throws CloneNotSupportedException {
CKEditorConfig cfg = (CKEditorConfig) super.clone();
cfg.config = new HashMap<String, Object>(this.config);
return cfg;
}
}
| zzh-simple-hr | ZJs/src/com/ckeditor/CKEditorConfig.java | Java | art | 5,095 |
<html>
<head>
<title>ssss</title>
</head>
<body>
<h1>sdfsdfsdf</h1>
</body>
</html> | zzh-simple-hr | ZJs/webapp/index.html | HTML | art | 94 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="author" content="brull@163.com,brull" />
<script type="text/javascript">
/**
*JWindow,Jchat窗口类
*version 1.0
*@author brull
*@email brull@163.com
*@date 2007-01-31
*/
/*
*新建一个窗口视图,并显示在浏览器容器里
*类里有实例方法,min、changeStatus、close、drag
*/
JWindow = function (win_obj)
{
/*
窗口存在判断
如果窗口存在则只是显示它,并将它置为当前窗口
*/
if(document.getElementById(win_obj.id)){//窗口已存在
var existWin = document.getElementById(win_obj.id).quote;//存在窗口的引用
if (JWindow.curWindow != win_obj.id){//窗口不是当前窗口
if (existWin.contain.style.display == "none"){//窗口是隐藏的(MIN,CLOSE),窗口隐藏时标题活动样式不变
existWin.status = existWin.oldStatus;//还原原来状态
existWin.contain.style.display = "";//显示窗口
JWindow.curWindow = win_obj.id;//设置为当前窗口
me.previous = JWindow.curWindow;
}
else {
document.getElementById(JWindow.curWindow + "_caption").className = "win_caption_deactive";//设置当前窗口为非活动窗口样式
document.getElementById(JWindow.curWindow + "_task").className = "task_button_deactive";//设置任务栏按钮为非活动按钮样式
JWindow.curWindow = win_obj.id;//设置为当前窗口
document.getElementById(win_obj.id + "_caption").className = "win_caption_active";//设置窗口为活动窗口样式
document.getElementById(win_obj.id + "_task").className = "task_button_active";//设置任务栏按钮为活动按钮样式
}
existWin.contain.zIndex = JWindow.zIndex++;//窗口上移到层最顶端
}
return;
}
/**********创建窗口******************/
var win = win_obj;//包含窗口属性的原生对象
var isIe = /msie/i.test(navigator.userAgent);//是否是IE浏览器
this.contain = document.createElement("div");//窗口容器
this.id= win.id;//win_obj没有默认值,初始化时win_obj必须有id属性
this.width = win.width?win.width:420;//窗口宽,默认为420
this.height = win.height?win.height:360;//窗口关,默认为360
this.left = win.left?win.left:(document.documentElement.clientWidth-this.width)/2;//窗口左上角距离浏览器左边框距离,默认居中
this.top = win.top?win.top:(document.documentElement.clientHeight-this.height)/2;//窗口左上角距离浏览器上边框距离,默认居中
this.oldLeft = this.left;//记录窗口最大化时窗口左上角距离浏览器左边框距离
this.oldTop = this.top;//记录窗口最大化时窗口左上角距离浏览器顶边框距离
this.title = win.title?win.title:" ";//标题,默认为空
this.content = win.content ? win.content : "";//窗口内容,默认为空
this.icon = win.icon ? win.icon : "http://www.51js.com/attachments/2007/03/35270_200703102258421.gif";//窗口图标
this.minButton = (win.minButton == false) ? false:true;//是否显示最小化按钮,默认显示
this.maxButton = (win.maxButton == false) ? false:true;//是否显示最大化按钮,默认显示
this.closeButton = (win.closeButton==false) ? false:true;//是否显示关闭按钮,默认显示
this.status = "NORMAL";//窗口状态,包括MAX,MIN,NORMAL,CLOSE
this.previous = JWindow.curWindow ? JWindow.curWindow : null;//上个当前窗口,在窗口关闭和最小化时有用
win = null;//释放对象
var me = this;//对象引用,方便类内部引用
/*************生成窗口视图******************/
me.contain.id = this.id;
me.contain.quote = this;//对象引用,方便应用页面引用
me.contain.className="win_contain";
with(me.contain.style){
position = "absolute";
left = this.left + "px";
top = this.top + "px";
width =this.width + "px";
height =this.height + "px";
zIndex = JWindow.zIndex++;
}
me.contain.innerHTML = "<div class=\"win_caption_active\" id=\"" + this.id + "_caption\"" + " ondblclick=\"document.getElementById('" + this.id + "').quote.changeStatus('" + this.id + "')\"><img src=\"" + this.icon + "\" class=\"win_icon\" /><span class=\"win_title\">" + this.title + "</span><div class=\"win_button_div\">"+(this.minButton ? "<input class=\"win_min\" type=\"button\" title=\"最小化\" onclick=\"document.getElementById('" + this.id + "').quote.min();\" />":"")+(this.maxButton ? "<input class=\"win_max\" id=\"" + this.id + "_maxbutton\" type=\"button\" onmouseover=\"this.title=(document.getElementById('" + this.id + "').quote.status=='MAX')?'还原':'最大化'\" onclick=\"this.blur();document.getElementById('" + this.id + "').quote.changeStatus();\" />":"")+(this.closeButton ? "<input class=\"win_close\" type=\"button\" title=\"关闭\" onclick=\"document.getElementById(\'" + this.id + "\').quote.close();\"/>":"")+ "</div></div><div class=\"win_body\" id=\"" + this.id + "_body" + "\">" + this.content + "</div>";
/***************注册窗口事件************************/
me.contain.onmousedown = function (e)
{
e = e || window.event;
var srcElement = isIe ? e.srcElement : e.target;
if(JWindow.curWindow != me.id){
me.contain.style.zIndex = JWindow.zIndex++;
document.getElementById(JWindow.curWindow + "_caption").className = "win_caption_deactive";
document.getElementById(JWindow.curWindow + "_task").className = "task_button_deactive";
me.previous = JWindow.curWindow;
JWindow.curWindow = me.id;//设置为当前窗口
document.getElementById(JWindow.curWindow + "_caption").className = "win_caption_active";
document.getElementById(JWindow.curWindow + "_task").className = "task_button_active";
}
if (me.id + "_caption" ==srcElement.id && me.status == "NORMAL") me.drag(e);
}
/***********添加任务栏按钮**********/
var task = document.createElement("button");
task.id = me.id + "_task";
task.title = me.title;
task.className = "task_button_active";
task.innerHTML = "<img src=\"" + me.icon + "\" class=\"task_icon\" /><span class=\"task_font\">" + me.title + "</span>";
task.onclick = function () {
task.blur();//丢掉讨厌的虚线框
if(JWindow.curWindow != me.id){
me.contain.style.zIndex = JWindow.zIndex++;
document.getElementById(JWindow.curWindow + "_caption").className = "win_caption_deactive";
document.getElementById(JWindow.curWindow + "_task").className = "task_button_deactive";
me.previous = JWindow.curWindow;
JWindow.curWindow = me.id;//设置为当前窗口
document.getElementById(JWindow.curWindow + "_caption").className = "win_caption_active";
document.getElementById(JWindow.curWindow + "_task").className = "task_button_active";
if(me.status == "MIN"){
me.status = me.oldStatus;//还原原来状态
//document.getElementById(me.id + "_task").className = "task_button_active";
me.contain.style.display = "";//显示窗口
}
}
else if(me.status == "MAX" || me.status == "NORMAL") me.min();
else if(me.status == "MIN") {
me.status = me.oldStatus;//还原原来状态
document.getElementById(me.id + "_task").className = "task_button_active";
me.contain.style.display = "";//显示窗口
}
}
if(! document.getElementById("task")) JWindow.createTask();
document.getElementById("task").appendChild(task);
document.body.appendChild(me.contain);//将窗口放入浏览器容器
if (document.getElementById(JWindow.curWindow) != null){ //当前窗口不为空
document.getElementById(JWindow.curWindow + "_caption").className = "win_caption_deactive";//设置当前窗口为不活动状态
document.getElementById(JWindow.curWindow + "_task").className = "task_button_deactive";
}
/***********设置为当前窗口*************/
JWindow.curWindow = me.id;
/***********对象方法*************/
this.drag = function (e)
{
var w = me.contain;
var relLeft = e.clientX-parseInt(w.style.left);
var relTop = e.clientY-parseInt(w.style.top);
//每次拖动都注册事件,然后再注销
document.onmousemove = function (e)
{
e = e || event;
if(w !=null){
w.style.left = (e.clientX-relLeft) + "px";
w.style.top = (e.clientY-relTop) + "px";
}
}
document.onselectstart = function ()
{
return false;
}
document.onmouseup = function ()
{
w = null;//释放拖动对象
document.onmouseup = document.onmousemove = document.onselectstart = null;//注销注册事件,包括该事件本身
}
}
this.min = function ()
{
if(JWindow.curWindow == me.id && this.minButton){
me.contain.style.display = "none";//只是隐藏而已^_^
me.oldStatus = me.status;//保存最小化前的状态
document.getElementById(JWindow.curWindow + "_task").className = "task_button_deactive";
me.status = "MIN";
if(me.previous && document.getElementById(me.previous).quote.contain.style.display != "none"){
JWindow.curWindow = me.previous;//设置为当前窗口
document.getElementById(JWindow.curWindow + "_caption").className = "win_caption_active";
document.getElementById(JWindow.curWindow + "_task").className = "task_button_active";
}
}
}
this.changeStatus = function ()
{
if (me.status == "MIN"||me.status == "CLOSE") return ;
if (me.status == "MAX" && this.maxButton)
{
with(me.contain.style){
left = me.oldLeft + "px";
top = me.oldTop + "px";
width = me.width + "px";
height = me.height + "px";
}
document.getElementById(me.id + "_maxbutton").className="win_max";
me.status = "NORMAL";
}
else if(me.status =="NORMAL" && this.maxButton)
{
//记录窗口位置,方便窗口还原大小时定位
me.oldLeft = parseInt(me.contain.style.left);
me.oldTop = parseInt(me.contain.style.top);
with(me.contain.style){
left = 0;
top = 0;
width = document.documentElement.clientWidth + "px";//only for XHTML
height = (document.documentElement.clientHeight-document.getElementById("task").offsetHeight) + "px";//only for XHTML
}
document.getElementById(me.id + "_maxbutton").className="win_res";
me.status = "MAX";
}
}
//窗口关闭
this.close = function ()
{
if(JWindow.curWindow == me.id && this.closeButton){
document.getElementById(JWindow.curWindow + "_task").style.display = "none";
me.contain.style.display = "none";//只是隐藏而已^_^
me.oldStatus = me.status;//保存关闭前的状态
me.status = "CLOSE";
if(me.previous && document.getElementById(me.previous).quote.contain.style.display != "none"){
JWindow.curWindow = me.previous;//设置为当前窗口
document.getElementById(JWindow.curWindow + "_caption").className = "win_caption_active";
document.getElementById(JWindow.curWindow + "_task").className = "task_button_active";
}
}
}
}
/***************静态属性和方法***********/
//静态属性
JWindow.zIndex = 100;//初始zIndex,任务栏的zIndex为30000,每点击一次窗口窗口zIndex自增1,也就是用户最多可以点击窗口29900次,应该已经足够
JWindow.curWindow = null;//当前活动窗口
/*********静态方法**********/
//创建任务栏
JWindow.createTask = function() {
var task = document.createElement("div");
task.id = "task";
with (task.style) {
position = "absolute";
height = "20px";
width = document.documentElement.clientWidth + "px";
left = 0;
bottom = 0;
padding = "1px";
border = "1px solid #EEE";
background = "#CCC";
zIndex = 30000;//设置一个比较大数,使其永远位于最上层
}
document.body.appendChild(task);
}
/*非本类方法,但是在这里编写可读性比较高
*注册系统事件
*/
/***********注册事件,在浏览器窗口大小调整时对任务栏的位置和宽度进行相应调整*********/
window.onresize = function () {
with(document.getElementById("task").style){
width = document.documentElement.clientWidth + "px";
top = (document.documentElement.clientHeight-parseInt(height)) + "px";
}
}
</script>
<title>web online communication</title>
<style type="text/css">
/*Jchat 客户端默认样式表*/
html,body
{
height:100%;
width:100%;
overflow:hidden;
border-width:0;
background-color:#336699;
margin:0;
padding:0;
}
/*窗口容器*/
.win_contain
{
border-width:2px;
border-style:outset;
border-color:#D4D0C8 #404040 #404040 #D4D0C8;
cursor:default;
background-color:#CCC;
}
/*活动窗口标题样式*/
.win_caption_active
{
width:100%;
height:18px;
font-size:14px;
background-color:#69C;
filter:progid:DXImageTransform.Microsoft.gradient(startColorStr=#10246B,endColorStr=#a5cbf7,GradientType=1);
}
/*非活动窗口标题样式*/
.win_caption_deactive
{
width:100%;
height:18px;
background-color:#808080;
font-size:14px;
filter:progid:DXImageTransform.Microsoft.gradient(startColorStr=#848284,endcolorstr=#c6c3c6,GradientType=1);
}
/*窗口窗体样式*/
.win_body
{
width:99%;
height:340px;
padding:2px;
overflow:hidden;
}
/*窗口图标样式*/
.win_icon
{
padding:1px;
vertical-align:text-bottom;
}
/*窗口标题样式*/
.win_title
{
color:#FFF;
/*font-size:14px;*/
font-weight:bold;
}
/*窗口按钮层样式*/
.win_button_div
{
display:inline;
position:absolute;
right:0;
padding:2px;
}
/*窗口按钮样式*/
.win_button_div input
{
width:16px;
height:14px;
background-color:#CCC;
}
/*活动任务栏按钮*/
.task_button_active
{
border:2px inset;
width:100px;
height:20px;
text-align:left;
margin-left:3px;
padding:0px;
overflow:hidden;
background-color:#CCC;
}
/*非活动任务栏按钮*/
.task_button_deactive
{
width:100px;
height:20px;
text-align:left;
margin-left:3px;
overflow:hidden;
padding:0px;
background-color:#CCC;
}
/*任务栏按钮文字*/
.task_font
{
font-size:12px;
}
/*任务栏按钮图标*/
.task_icon
{
vertical-align:bottom;
}
/*聊天内容窗口*/
.chat_frame
{
width:100%;
height:240px;
background-color:#FFF;
word-break:break-all;
}
.editor_frame
{
width:100%;
height:100px;
background-color:#FFF;
word-break:break-all;
}
/*窗口最小化按钮样式*/
.win_min
{
background:#d4d0c8 url(http://www.51js.com/attachments/2007/03/35270_200703102256511.gif) no-repeat center center;
}
/*窗口还原按钮样式*/
.win_res
{
background:#d4d0c8 url(http://www.51js.com/attachments/2007/03/35270_200703102257161.gif) no-repeat center center;
}
/*窗口最大化按钮样式*/
.win_max
{
background:#d4d0c8 url(http://www.51js.com/attachments/2007/03/35270_200703102256581.gif) no-repeat center center;
}
/*窗口关闭按钮样式*/
.win_close
{
background:#d4d0c8 url(http://www.51js.com/attachments/2007/03/35270_200703102257331.gif) no-repeat center center;
}
</style>
</head>
<body>
<script type="text/javascript">
/*******用户程序*********/
var content ="调用方法:<br />构造win对象,然后将win对象作为参数实例化JWindow类。具体如源代码下面的例子。<br />其中win对象的属性如下:<br />id:窗口id,用户必须提供值,并确保是唯一的<br />title:窗口标题,默认为空<br />content:窗体内显示的内容,可以是任何浏览器认得的东西,默认为空<br /> icon:窗口图标,如果用户没有提供值,类会提供个默认值<br />top:窗口左上角距离浏览器上边框距离,默认居中<br />left:窗口左上角距离浏览器左边框距离,默认居中<br />width:窗口宽,默认为420<br />height:窗口关,默认为360<br />minButton:(布尔值)是否显示最小化按钮,默认显示<br />maxButton:(布尔值)是否显示最大化按钮,默认显示<br />closeButton:(布尔值)是否显示关闭按钮,默认显示";
var win1={
title:"测试",
id:"1",
content:content
};
var win2={
id:"2",
content:content,
maxButton:false
};
var win3=new Object();
win3.title="测试";
win3.id="3"; win3.content=content;
win3.icon="http://www.51js.com/attachments/2007/03/35270_200703102258421.gif";
new JWindow(win1);
new JWindow(win2);
new JWindow(win3);
</script>
<!--information-->
<div style="position: absolute; bottom: 30px; right: 5px; word-break: break-all;
font-size: 12px; color: #CCC;">
兼容浏览器:IE5.5+、FireFox1.5+<br />
推荐浏览器:IE6.0、FireFox2.0<br />
design by brull. All right reserved ?2007
<br />
Email:brull@163.com
</div>
</body>
</html>
<a href="http://www.alixixi.com/Dev/HTML/jsrun/">欢迎访问代码学院网页脚本特效集</a>
更多代码请访问:<a href="http://www.codexy.com" target="_blank">代码学苑</a> | zzh-simple-hr | ZJs/webapp/my-js/windows-desktop.html | HTML | art | 19,199 |