001: /*
002: * Licensed to the Apache Software Foundation (ASF) under one or more
003: * contributor license agreements. See the NOTICE file distributed with
004: * this work for additional information regarding copyright ownership.
005: * The ASF licenses this file to You under the Apache License, Version 2.0
006: * (the "License"); you may not use this file except in compliance with
007: * the License. You may obtain a copy of the License at
008: *
009: * http://www.apache.org/licenses/LICENSE-2.0
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS,
013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014: * See the License for the specific language governing permissions and
015: * limitations under the License.
016: */
017:
018: // Aug 21, 2000:
019: // Fixed bug in isElement and made HTMLdtd public.
020: // Contributed by Eric SCHAEFFER" <eschaeffer@posterconseil.com>
021: package org.apache.xml.serialize;
022:
023: import org.apache.xerces.dom.DOMMessageFormatter;
024:
025: import java.io.InputStream;
026: import java.io.InputStreamReader;
027: import java.io.BufferedReader;
028: import java.util.Hashtable;
029: import java.util.Locale;
030:
031: /**
032: * Utility class for accessing information specific to HTML documents.
033: * The HTML DTD is expressed as three utility function groups. Two methods
034: * allow for checking whether an element requires an open tag on printing
035: * ({@link #isEmptyTag}) or on parsing ({@link #isOptionalClosing}).
036: * <P>
037: * Two other methods translate character references from name to value and
038: * from value to name. A small entities resource is loaded into memory the
039: * first time any of these methods is called for fast and efficient access.
040: *
041: * @deprecated This class was deprecated in Xerces 2.9.0. It is recommended
042: * that new applications use JAXP's Transformation API for XML (TrAX) for
043: * serializing HTML. See the Xerces documentation for more information.
044: * @version $Revision: 476047 $ $Date: 2006-11-16 23:27:45 -0500 (Thu, 16 Nov 2006) $
045: * @author <a href="mailto:arkin@intalio.com">Assaf Arkin</a>
046: */
047: public final class HTMLdtd {
048:
049: /**
050: * Public identifier for HTML 4.01 (Strict) document type.
051: */
052: public static final String HTMLPublicId = "-//W3C//DTD HTML 4.01//EN";
053:
054: /**
055: * System identifier for HTML 4.01 (Strict) document type.
056: */
057: public static final String HTMLSystemId = "http://www.w3.org/TR/html4/strict.dtd";
058:
059: /**
060: * Public identifier for XHTML 1.0 (Strict) document type.
061: */
062: public static final String XHTMLPublicId = "-//W3C//DTD XHTML 1.0 Strict//EN";
063:
064: /**
065: * System identifier for XHTML 1.0 (Strict) document type.
066: */
067: public static final String XHTMLSystemId = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";
068:
069: /**
070: * Table of reverse character reference mapping. Character codes are held
071: * as single-character strings, mapped to their reference name.
072: */
073: private static Hashtable _byChar;
074:
075: /**
076: * Table of entity name to value mapping. Entities are held as strings,
077: * character references as <TT>Character</TT> objects.
078: */
079: private static Hashtable _byName;
080:
081: private static Hashtable _boolAttrs;
082:
083: /**
084: * Holds element definitions.
085: */
086: private static Hashtable _elemDefs;
087:
088: /**
089: * Locates the HTML entities file that is loaded upon initialization.
090: * This file is a resource loaded with the default class loader.
091: */
092: private static final String ENTITIES_RESOURCE = "HTMLEntities.res";
093:
094: /**
095: * Only opening tag should be printed.
096: */
097: private static final int ONLY_OPENING = 0x0001;
098:
099: /**
100: * Element contains element content only.
101: */
102: private static final int ELEM_CONTENT = 0x0002;
103:
104: /**
105: * Element preserve spaces.
106: */
107: private static final int PRESERVE = 0x0004;
108:
109: /**
110: * Optional closing tag.
111: */
112: private static final int OPT_CLOSING = 0x0008;
113:
114: /**
115: * Element is empty (also means only opening tag)
116: */
117: private static final int EMPTY = 0x0010 | ONLY_OPENING;
118:
119: /**
120: * Allowed to appear in head.
121: */
122: private static final int ALLOWED_HEAD = 0x0020;
123:
124: /**
125: * When opened, closes P.
126: */
127: private static final int CLOSE_P = 0x0040;
128:
129: /**
130: * When opened, closes DD or DT.
131: */
132: private static final int CLOSE_DD_DT = 0x0080;
133:
134: /**
135: * When opened, closes itself.
136: */
137: private static final int CLOSE_SELF = 0x0100;
138:
139: /**
140: * When opened, closes another table section.
141: */
142: private static final int CLOSE_TABLE = 0x0200;
143:
144: /**
145: * When opened, closes TH or TD.
146: */
147: private static final int CLOSE_TH_TD = 0x04000;
148:
149: /**
150: * Returns true if element is declared to be empty. HTML elements are
151: * defines as empty in the DTD, not by the document syntax.
152: *
153: * @param tagName The element tag name (upper case)
154: * @return True if element is empty
155: */
156: public static boolean isEmptyTag(String tagName) {
157: return isElement(tagName, EMPTY);
158: }
159:
160: /**
161: * Returns true if element is declared to have element content.
162: * Whitespaces appearing inside element content will be ignored,
163: * other text will simply report an error.
164: *
165: * @param tagName The element tag name (upper case)
166: * @return True if element content
167: */
168: public static boolean isElementContent(String tagName) {
169: return isElement(tagName, ELEM_CONTENT);
170: }
171:
172: /**
173: * Returns true if element's textual contents preserves spaces.
174: * This only applies to PRE and TEXTAREA, all other HTML elements
175: * do not preserve space.
176: *
177: * @param tagName The element tag name (upper case)
178: * @return True if element's text content preserves spaces
179: */
180: public static boolean isPreserveSpace(String tagName) {
181: return isElement(tagName, PRESERVE);
182: }
183:
184: /**
185: * Returns true if element's closing tag is optional and need not
186: * exist. An error will not be reported for such elements if they
187: * are not closed. For example, <tt>LI</tt> is most often not closed.
188: *
189: * @param tagName The element tag name (upper case)
190: * @return True if closing tag implied
191: */
192: public static boolean isOptionalClosing(String tagName) {
193: return isElement(tagName, OPT_CLOSING);
194: }
195:
196: /**
197: * Returns true if element's closing tag is generally not printed.
198: * For example, <tt>LI</tt> should not print the closing tag.
199: *
200: * @param tagName The element tag name (upper case)
201: * @return True if only opening tag should be printed
202: */
203: public static boolean isOnlyOpening(String tagName) {
204: return isElement(tagName, ONLY_OPENING);
205: }
206:
207: /**
208: * Returns true if the opening of one element (<tt>tagName</tt>) implies
209: * the closing of another open element (<tt>openTag</tt>). For example,
210: * every opening <tt>LI</tt> will close the previously open <tt>LI</tt>,
211: * and every opening <tt>BODY</tt> will close the previously open <tt>HEAD</tt>.
212: *
213: * @param tagName The newly opened element
214: * @param openTag The already opened element
215: * @return True if closing tag closes opening tag
216: */
217: public static boolean isClosing(String tagName, String openTag) {
218: // Several elements are defined as closing the HEAD
219: if (openTag.equalsIgnoreCase("HEAD"))
220: return !isElement(tagName, ALLOWED_HEAD);
221: // P closes iteself
222: if (openTag.equalsIgnoreCase("P"))
223: return isElement(tagName, CLOSE_P);
224: // DT closes DD, DD closes DT
225: if (openTag.equalsIgnoreCase("DT")
226: || openTag.equalsIgnoreCase("DD"))
227: return isElement(tagName, CLOSE_DD_DT);
228: // LI and OPTION close themselves
229: if (openTag.equalsIgnoreCase("LI")
230: || openTag.equalsIgnoreCase("OPTION"))
231: return isElement(tagName, CLOSE_SELF);
232: // Each of these table sections closes all the others
233: if (openTag.equalsIgnoreCase("THEAD")
234: || openTag.equalsIgnoreCase("TFOOT")
235: || openTag.equalsIgnoreCase("TBODY")
236: || openTag.equalsIgnoreCase("TR")
237: || openTag.equalsIgnoreCase("COLGROUP"))
238: return isElement(tagName, CLOSE_TABLE);
239: // TD closes TH and TH closes TD
240: if (openTag.equalsIgnoreCase("TH")
241: || openTag.equalsIgnoreCase("TD"))
242: return isElement(tagName, CLOSE_TH_TD);
243: return false;
244: }
245:
246: /**
247: * Returns true if the specified attribute it a URI and should be
248: * escaped appropriately. In HTML URIs are escaped differently
249: * than normal attributes.
250: *
251: * @param tagName The element's tag name
252: * @param attrName The attribute's name
253: */
254: public static boolean isURI(String tagName, String attrName) {
255: // Stupid checks.
256: return (attrName.equalsIgnoreCase("href") || attrName
257: .equalsIgnoreCase("src"));
258: }
259:
260: /**
261: * Returns true if the specified attribute is a boolean and should be
262: * printed without the value. This applies to attributes that are true
263: * if they exist, such as selected (OPTION/INPUT).
264: *
265: * @param tagName The element's tag name
266: * @param attrName The attribute's name
267: */
268: public static boolean isBoolean(String tagName, String attrName) {
269: String[] attrNames;
270:
271: attrNames = (String[]) _boolAttrs.get(tagName
272: .toUpperCase(Locale.ENGLISH));
273: if (attrNames == null)
274: return false;
275: for (int i = 0; i < attrNames.length; ++i)
276: if (attrNames[i].equalsIgnoreCase(attrName))
277: return true;
278: return false;
279: }
280:
281: /**
282: * Returns the value of an HTML character reference by its name. If the
283: * reference is not found or was not defined as a character reference,
284: * returns EOF (-1).
285: *
286: * @param name Name of character reference
287: * @return Character code or EOF (-1)
288: */
289: public static int charFromName(String name) {
290: Object value;
291:
292: initialize();
293: value = _byName.get(name);
294: if (value != null && value instanceof Integer) {
295: return ((Integer) value).intValue();
296: }
297: return -1;
298: }
299:
300: /**
301: * Returns the name of an HTML character reference based on its character
302: * value. Only valid for entities defined from character references. If no
303: * such character value was defined, return null.
304: *
305: * @param value Character value of entity
306: * @return Entity's name or null
307: */
308: public static String fromChar(int value) {
309: if (value > 0xffff)
310: return null;
311:
312: String name;
313:
314: initialize();
315: name = (String) _byChar.get(new Integer(value));
316: return name;
317: }
318:
319: /**
320: * Initialize upon first access. Will load all the HTML character references
321: * into a list that is accessible by name or character value and is optimized
322: * for character substitution. This method may be called any number of times
323: * but will execute only once.
324: */
325: private static void initialize() {
326: InputStream is = null;
327: BufferedReader reader = null;
328: int index;
329: String name;
330: String value;
331: int code;
332: String line;
333:
334: // Make sure not to initialize twice.
335: if (_byName != null)
336: return;
337: try {
338: _byName = new Hashtable();
339: _byChar = new Hashtable();
340: is = HTMLdtd.class.getResourceAsStream(ENTITIES_RESOURCE);
341: if (is == null) {
342: throw new RuntimeException(DOMMessageFormatter
343: .formatMessage(
344: DOMMessageFormatter.SERIALIZER_DOMAIN,
345: "ResourceNotFound",
346: new Object[] { ENTITIES_RESOURCE }));
347: }
348: reader = new BufferedReader(new InputStreamReader(is,
349: "ASCII"));
350: line = reader.readLine();
351: while (line != null) {
352: if (line.length() == 0 || line.charAt(0) == '#') {
353: line = reader.readLine();
354: continue;
355: }
356: index = line.indexOf(' ');
357: if (index > 1) {
358: name = line.substring(0, index);
359: ++index;
360: if (index < line.length()) {
361: value = line.substring(index);
362: index = value.indexOf(' ');
363: if (index > 0)
364: value = value.substring(0, index);
365: code = Integer.parseInt(value);
366: defineEntity(name, (char) code);
367: }
368: }
369: line = reader.readLine();
370: }
371: is.close();
372: } catch (Exception except) {
373: throw new RuntimeException(DOMMessageFormatter
374: .formatMessage(
375: DOMMessageFormatter.SERIALIZER_DOMAIN,
376: "ResourceNotLoaded", new Object[] {
377: ENTITIES_RESOURCE,
378: except.toString() }));
379: } finally {
380: if (is != null) {
381: try {
382: is.close();
383: } catch (Exception except) {
384: }
385: }
386: }
387: }
388:
389: /**
390: * Defines a new character reference. The reference's name and value are
391: * supplied. Nothing happens if the character reference is already defined.
392: * <P>
393: * Unlike internal entities, character references are a string to single
394: * character mapping. They are used to map non-ASCII characters both on
395: * parsing and printing, primarily for HTML documents. '<amp;' is an
396: * example of a character reference.
397: *
398: * @param name The entity's name
399: * @param value The entity's value
400: */
401: private static void defineEntity(String name, char value) {
402: if (_byName.get(name) == null) {
403: _byName.put(name, new Integer(value));
404: _byChar.put(new Integer(value), name);
405: }
406: }
407:
408: private static void defineElement(String name, int flags) {
409: _elemDefs.put(name, new Integer(flags));
410: }
411:
412: private static void defineBoolean(String tagName, String attrName) {
413: defineBoolean(tagName, new String[] { attrName });
414: }
415:
416: private static void defineBoolean(String tagName, String[] attrNames) {
417: _boolAttrs.put(tagName, attrNames);
418: }
419:
420: private static boolean isElement(String name, int flag) {
421: Integer flags;
422:
423: flags = (Integer) _elemDefs.get(name
424: .toUpperCase(Locale.ENGLISH));
425: if (flags == null) {
426: return false;
427: }
428: return ((flags.intValue() & flag) == flag);
429: }
430:
431: static {
432: _elemDefs = new Hashtable();
433: defineElement("ADDRESS", CLOSE_P);
434: defineElement("AREA", EMPTY);
435: defineElement("BASE", EMPTY | ALLOWED_HEAD);
436: defineElement("BASEFONT", EMPTY);
437: defineElement("BLOCKQUOTE", CLOSE_P);
438: defineElement("BODY", OPT_CLOSING);
439: defineElement("BR", EMPTY);
440: defineElement("COL", EMPTY);
441: defineElement("COLGROUP", ELEM_CONTENT | OPT_CLOSING
442: | CLOSE_TABLE);
443: defineElement("DD", OPT_CLOSING | ONLY_OPENING | CLOSE_DD_DT);
444: defineElement("DIV", CLOSE_P);
445: defineElement("DL", ELEM_CONTENT | CLOSE_P);
446: defineElement("DT", OPT_CLOSING | ONLY_OPENING | CLOSE_DD_DT);
447: defineElement("FIELDSET", CLOSE_P);
448: defineElement("FORM", CLOSE_P);
449: defineElement("FRAME", EMPTY | OPT_CLOSING);
450: defineElement("H1", CLOSE_P);
451: defineElement("H2", CLOSE_P);
452: defineElement("H3", CLOSE_P);
453: defineElement("H4", CLOSE_P);
454: defineElement("H5", CLOSE_P);
455: defineElement("H6", CLOSE_P);
456: defineElement("HEAD", ELEM_CONTENT | OPT_CLOSING);
457: defineElement("HR", EMPTY | CLOSE_P);
458: defineElement("HTML", ELEM_CONTENT | OPT_CLOSING);
459: defineElement("IMG", EMPTY);
460: defineElement("INPUT", EMPTY);
461: defineElement("ISINDEX", EMPTY | ALLOWED_HEAD);
462: defineElement("LI", OPT_CLOSING | ONLY_OPENING | CLOSE_SELF);
463: defineElement("LINK", EMPTY | ALLOWED_HEAD);
464: defineElement("MAP", ALLOWED_HEAD);
465: defineElement("META", EMPTY | ALLOWED_HEAD);
466: defineElement("OL", ELEM_CONTENT | CLOSE_P);
467: defineElement("OPTGROUP", ELEM_CONTENT);
468: defineElement("OPTION", OPT_CLOSING | ONLY_OPENING | CLOSE_SELF);
469: defineElement("P", OPT_CLOSING | CLOSE_P | CLOSE_SELF);
470: defineElement("PARAM", EMPTY);
471: defineElement("PRE", PRESERVE | CLOSE_P);
472: defineElement("SCRIPT", ALLOWED_HEAD | PRESERVE);
473: defineElement("NOSCRIPT", ALLOWED_HEAD | PRESERVE);
474: defineElement("SELECT", ELEM_CONTENT);
475: defineElement("STYLE", ALLOWED_HEAD | PRESERVE);
476: defineElement("TABLE", ELEM_CONTENT | CLOSE_P);
477: defineElement("TBODY", ELEM_CONTENT | OPT_CLOSING | CLOSE_TABLE);
478: defineElement("TD", OPT_CLOSING | CLOSE_TH_TD);
479: defineElement("TEXTAREA", PRESERVE);
480: defineElement("TFOOT", ELEM_CONTENT | OPT_CLOSING | CLOSE_TABLE);
481: defineElement("TH", OPT_CLOSING | CLOSE_TH_TD);
482: defineElement("THEAD", ELEM_CONTENT | OPT_CLOSING | CLOSE_TABLE);
483: defineElement("TITLE", ALLOWED_HEAD);
484: defineElement("TR", ELEM_CONTENT | OPT_CLOSING | CLOSE_TABLE);
485: defineElement("UL", ELEM_CONTENT | CLOSE_P);
486:
487: _boolAttrs = new Hashtable();
488: defineBoolean("AREA", "href");
489: defineBoolean("BUTTON", "disabled");
490: defineBoolean("DIR", "compact");
491: defineBoolean("DL", "compact");
492: defineBoolean("FRAME", "noresize");
493: defineBoolean("HR", "noshade");
494: defineBoolean("IMAGE", "ismap");
495: defineBoolean("INPUT", new String[] { "defaultchecked",
496: "checked", "readonly", "disabled" });
497: defineBoolean("LINK", "link");
498: defineBoolean("MENU", "compact");
499: defineBoolean("OBJECT", "declare");
500: defineBoolean("OL", "compact");
501: defineBoolean("OPTGROUP", "disabled");
502: defineBoolean("OPTION", new String[] { "default-selected",
503: "selected", "disabled" });
504: defineBoolean("SCRIPT", "defer");
505: defineBoolean("SELECT", new String[] { "multiple", "disabled" });
506: defineBoolean("STYLE", "disabled");
507: defineBoolean("TD", "nowrap");
508: defineBoolean("TH", "nowrap");
509: defineBoolean("TEXTAREA",
510: new String[] { "disabled", "readonly" });
511: defineBoolean("UL", "compact");
512:
513: initialize();
514: }
515:
516: }
|