Initial load

This commit is contained in:
J. Duke 2007-12-01 00:00:00 +00:00
parent 686d76f772
commit 74f4779697
1972 changed files with 585739 additions and 0 deletions

View file

@ -0,0 +1,193 @@
/*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml;
/**
* <p>Utility class to contain basic XML values as constants.</p>
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @see <a href="http://www.w3.org/TR/xml11/">Extensible Markup Language (XML) 1.1</a>
* @see <a href="http://www.w3.org/TR/REC-xml">Extensible Markup Language (XML) 1.0 (Second Edition)</a>
* @see <a href="http://www.w3.org/XML/xml-V10-2e-errata">XML 1.0 Second Edition Specification Errata</a>
* @see <a href="http://www.w3.org/TR/xml-names11/">Namespaces in XML 1.1</a>
* @see <a href="http://www.w3.org/TR/REC-xml-names">Namespaces in XML</a>
* @see <a href="http://www.w3.org/XML/xml-names-19990114-errata">Namespaces in XML Errata</a>
* @see <a href="http://www.w3.org/TR/xmlschema-1/">XML Schema Part 1: Structures</a>
* @since 1.5
**/
public final class XMLConstants {
/**
* <p>Private constructor to prevent instantiation.</p>
*/
private XMLConstants() {
}
/**
* <p>Namespace URI to use to represent that there is no Namespace.</p>
*
* <p>Defined by the Namespace specification to be "".</p>
*
* @see <a href="http://www.w3.org/TR/REC-xml-names/#defaulting">
* Namespaces in XML, 5.2 Namespace Defaulting</a>
*/
public static final String NULL_NS_URI = "";
/**
* <p>Prefix to use to represent the default XML Namespace.</p>
*
* <p>Defined by the XML specification to be "".</p>
*
* @see <a
* href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">
* Namespaces in XML, 3. Qualified Names</a>
*/
public static final String DEFAULT_NS_PREFIX = "";
/**
* <p>The official XML Namespace name URI.</p>
*
* <p>Defined by the XML specification to be
* "<code>http://www.w3.org/XML/1998/namespace</code>".</p>
*
* @see <a
* href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">
* Namespaces in XML, 3. Qualified Names</a>
*/
public static final String XML_NS_URI =
"http://www.w3.org/XML/1998/namespace";
/**
* <p>The official XML Namespace prefix.</p>
*
* <p>Defined by the XML specification to be "<code>xml</code>".</p>
*
* @see <a
* href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">
* Namespaces in XML, 3. Qualified Names<</a>
*/
public static final String XML_NS_PREFIX = "xml";
/**
* <p>The official XML attribute used for specifying XML Namespace
* declarations, {@link #XMLNS_ATTRIBUTE
* XMLConstants.XMLNS_ATTRIBUTE}, Namespace name URI.</p>
*
* <p>Defined by the XML specification to be
* "<code>http://www.w3.org/2000/xmlns/</code>".</p>
*
* @see <a
* href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">
* Namespaces in XML, 3. Qualified Names</a>
* @see <a
* href="http://www.w3.org/XML/xml-names-19990114-errata/">
* Namespaces in XML Errata</a>
*/
public static final String XMLNS_ATTRIBUTE_NS_URI =
"http://www.w3.org/2000/xmlns/";
/**
* <p>The official XML attribute used for specifying XML Namespace
* declarations.</p>
*
* <p>It is <strong><em>NOT</em></strong> valid to use as a
* prefix. Defined by the XML specification to be
* "<code>xmlns</code>".</p>
*
* @see <a
* href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">
* Namespaces in XML, 3. Qualified Names</a>
*/
public static final String XMLNS_ATTRIBUTE = "xmlns";
/**
* <p>W3C XML Schema Namespace URI.</p>
*
* <p>Defined to be "<code>http://www.w3.org/2001/XMLSchema</code>".
*
* @see <a href=
* "http://www.w3.org/TR/xmlschema-1/#Instance_Document_Constructions">
* XML Schema Part 1:
* Structures, 2.6 Schema-Related Markup in Documents Being Validated</a>
*/
public static final String W3C_XML_SCHEMA_NS_URI =
"http://www.w3.org/2001/XMLSchema";
/**
* <p>W3C XML Schema Instance Namespace URI.</p>
*
* <p>Defined to be "<code>http://www.w3.org/2001/XMLSchema-instance</code>".</p>
*
* @see <a href=
* "http://www.w3.org/TR/xmlschema-1/#Instance_Document_Constructions">
* XML Schema Part 1:
* Structures, 2.6 Schema-Related Markup in Documents Being Validated</a>
*/
public static final String W3C_XML_SCHEMA_INSTANCE_NS_URI =
"http://www.w3.org/2001/XMLSchema-instance";
/**
* <p>W3C XPath Datatype Namespace URI.</p>
*
* <p>Defined to be "<code>http://www.w3.org/2003/11/xpath-datatypes</code>".</p>
*
* @see <a href="http://www.w3.org/TR/xpath-datamodel">XQuery 1.0 and XPath 2.0 Data Model</a>
*/
public static final String W3C_XPATH_DATATYPE_NS_URI = "http://www.w3.org/2003/11/xpath-datatypes";
/**
* <p>XML Document Type Declaration Namespace URI as an arbitrary value.</p>
*
* <p>Since not formally defined by any existing standard, arbitrarily define to be "<code>http://www.w3.org/TR/REC-xml</code>".
*/
public static final String XML_DTD_NS_URI = "http://www.w3.org/TR/REC-xml";
/**
* <p>RELAX NG Namespace URI.</p>
*
* <p>Defined to be "<code>http://relaxng.org/ns/structure/1.0</code>".</p>
*
* @see <a href="http://relaxng.org/spec-20011203.html">RELAX NG Specification</a>
*/
public static final String RELAXNG_NS_URI = "http://relaxng.org/ns/structure/1.0";
/**
* <p>Feature for secure processing.</p>
*
* <ul>
* <li>
* <code>true</code> instructs the implementation to process XML securely.
* This may set limits on XML constructs to avoid conditions such as denial of service attacks.
* </li>
* <li>
* <code>false</code> instructs the implementation to process XML acording the letter of the XML specifications
* ingoring security issues such as limits on XML constructs to avoid conditions such as denial of service attacks.
* </li>
* </ul>
*/
public static final String FEATURE_SECURE_PROCESSING = "http://javax.xml.XMLConstants/feature/secure-processing";
}

View file

@ -0,0 +1,79 @@
/*
* Copyright 2004-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.datatype;
/**
* <p>Indicates a serious configuration error.</p>
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @since 1.5
*/
public class DatatypeConfigurationException extends Exception {
/**
* <p>Create a new <code>DatatypeConfigurationException</code> with
* no specified detail mesage and cause.</p>
*/
public DatatypeConfigurationException() {
super();
}
/**
* <p>Create a new <code>DatatypeConfigurationException</code> with
* the specified detail message.</p>
*
* @param message The detail message.
*/
public DatatypeConfigurationException(String message) {
super(message);
}
/**
* <p>Create a new <code>DatatypeConfigurationException</code> with
* the specified detail message and cause.</p>
*
* @param message The detail message.
* @param cause The cause. A <code>null</code> value is permitted, and indicates that the cause is nonexistent or unknown.
*/
public DatatypeConfigurationException(String message, Throwable cause) {
super(message, cause);
}
/**
* <p>Create a new <code>DatatypeConfigurationException</code> with
* the specified cause.</p>
*
* @param cause The cause. A <code>null</code> value is permitted, and indicates that the cause is nonexistent or unknown.
*/
public DatatypeConfigurationException(Throwable cause) {
super(cause);
}
}

View file

@ -0,0 +1,274 @@
/*
* Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.datatype;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
/**
* <p>Utility class to contain basic Datatype values as constants.</p>
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @since 1.5
*/
public final class DatatypeConstants {
/**
* <p>Private constructor to prevent instantiation.</p>
*/
private DatatypeConstants() {
}
/**
* Value for first month of year.
*/
public static final int JANUARY = 1;
/**
* Value for second month of year.
*/
public static final int FEBRUARY = 2;
/**
* Value for third month of year.
*/
public static final int MARCH = 3;
/**
* Value for fourth month of year.
*/
public static final int APRIL = 4;
/**
* Value for fifth month of year.
*/
public static final int MAY = 5;
/**
* Value for sixth month of year.
*/
public static final int JUNE = 6;
/**
* Value for seventh month of year.
*/
public static final int JULY = 7;
/**
* Value for eighth month of year.
*/
public static final int AUGUST = 8;
/**
* Value for ninth month of year.
*/
public static final int SEPTEMBER = 9;
/**
* Value for tenth month of year.
*/
public static final int OCTOBER = 10;
/**
* Value for eleven month of year.
*/
public static final int NOVEMBER = 11;
/**
* Value for twelve month of year.
*/
public static final int DECEMBER = 12;
/**
* <p>Comparison result.</p>
*/
public static final int LESSER = -1;
/**
* <p>Comparison result.</p>
*/
public static final int EQUAL = 0;
/**
* <p>Comparison result.</p>
*/
public static final int GREATER = 1;
/**
* <p>Comparison result.</p>
*/
public static final int INDETERMINATE = 2;
/**
* Designation that an "int" field is not set.
*/
public static final int FIELD_UNDEFINED = Integer.MIN_VALUE;
/**
* <p>A constant that represents the years field.</p>
*/
public static final Field YEARS = new Field("YEARS", 0);
/**
* <p>A constant that represents the months field.</p>
*/
public static final Field MONTHS = new Field("MONTHS", 1);
/**
* <p>A constant that represents the days field.</p>
*/
public static final Field DAYS = new Field("DAYS", 2);
/**
* <p>A constant that represents the hours field.</p>
*/
public static final Field HOURS = new Field("HOURS", 3);
/**
* <p>A constant that represents the minutes field.</p>
*/
public static final Field MINUTES = new Field("MINUTES", 4);
/**
* <p>A constant that represents the seconds field.</p>
*/
public static final Field SECONDS = new Field("SECONDS", 5);
/**
* Type-safe enum class that represents six fields
* of the {@link Duration} class.
* @since 1.5
*/
public static final class Field {
/**
* <p><code>String</code> representation of <code>Field</code>.</p>
*/
private final String str;
/**
* <p>Unique id of the field.</p>
*
* <p>This value allows the {@link Duration} class to use switch
* statements to process fields.</p>
*/
private final int id;
/**
* <p>Construct a <code>Field</code> with specified values.</p>
* @param str <code>String</code> representation of <code>Field</code>
* @param id <code>int</code> representation of <code>Field</code>
*/
private Field(final String str, final int id) {
this.str = str;
this.id = id;
}
/**
* Returns a field name in English. This method
* is intended to be used for debugging/diagnosis
* and not for display to end-users.
*
* @return
* a non-null valid String constant.
*/
public String toString() { return str; }
/**
* <p>Get id of this Field.</p>
*
* @return Id of field.
*/
public int getId() {
return id;
}
}
/**
* <p>Fully qualified name for W3C XML Schema 1.0 datatype <code>dateTime</code>.</p>
*/
public static final QName DATETIME = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "dateTime");
/**
* <p>Fully qualified name for W3C XML Schema 1.0 datatype <code>time</code>.</p>
*/
public static final QName TIME = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "time");
/**
* <p>Fully qualified name for W3C XML Schema 1.0 datatype <code>date</code>.</p>
*/
public static final QName DATE = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "date");
/**
* <p>Fully qualified name for W3C XML Schema 1.0 datatype <code>gYearMonth</code>.</p>
*/
public static final QName GYEARMONTH = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gYearMonth");
/**
* <p>Fully qualified name for W3C XML Schema 1.0 datatype <code>gMonthDay</code>.</p>
*/
public static final QName GMONTHDAY = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gMonthDay");
/**
* <p>Fully qualified name for W3C XML Schema 1.0 datatype <code>gYear</code>.</p>
*/
public static final QName GYEAR = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gYear");
/**
* <p>Fully qualified name for W3C XML Schema 1.0 datatype <code>gMonth</code>.</p>
*/
public static final QName GMONTH = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gMonth");
/**
* <p>Fully qualified name for W3C XML Schema 1.0 datatype <code>gDay</code>.</p>
*/
public static final QName GDAY = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "gDay");
/**
* <p>Fully qualified name for W3C XML Schema datatype <code>duration</code>.</p>
*/
public static final QName DURATION = new QName(XMLConstants.W3C_XML_SCHEMA_NS_URI, "duration");
/**
* <p>Fully qualified name for XQuery 1.0 and XPath 2.0 datatype <code>dayTimeDuration</code>.</p>
*/
public static final QName DURATION_DAYTIME = new QName(XMLConstants.W3C_XPATH_DATATYPE_NS_URI, "dayTimeDuration");
/**
* <p>Fully qualified name for XQuery 1.0 and XPath 2.0 datatype <code>yearMonthDuration</code>.</p>
*/
public static final QName DURATION_YEARMONTH = new QName(XMLConstants.W3C_XPATH_DATATYPE_NS_URI, "yearMonthDuration");
/**
* W3C XML Schema max timezone offset is -14:00. Zone offset is in minutes.
*/
public static final int MAX_TIMEZONE_OFFSET = -14 * 60;
/**
* W3C XML Schema min timezone offset is +14:00. Zone offset is in minutes.
*/
public static final int MIN_TIMEZONE_OFFSET = 14 * 60;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,988 @@
/*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.datatype;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.xml.namespace.QName;
/**
* <p>Immutable representation of a time span as defined in
* the W3C XML Schema 1.0 specification.</p>
*
* <p>A Duration object represents a period of Gregorian time,
* which consists of six fields (years, months, days, hours,
* minutes, and seconds) plus a sign (+/-) field.</p>
*
* <p>The first five fields have non-negative (>=0) integers or null
* (which represents that the field is not set),
* and the seconds field has a non-negative decimal or null.
* A negative sign indicates a negative duration.</p>
*
* <p>This class provides a number of methods that make it easy
* to use for the duration datatype of XML Schema 1.0 with
* the errata.</p>
*
* <h2>Order relationship</h2>
* <p>Duration objects only have partial order, where two values A and B
* maybe either:</p>
* <ol>
* <li>A&lt;B (A is shorter than B)
* <li>A&gt;B (A is longer than B)
* <li>A==B (A and B are of the same duration)
* <li>A&lt;>B (Comparison between A and B is indeterminate)
* </ol>
*
* <p>For example, 30 days cannot be meaningfully compared to one month.
* The {@link #compare(Duration duration)} method implements this
* relationship.</p>
*
* <p>See the {@link #isLongerThan(Duration)} method for details about
* the order relationship among <code>Duration</code> objects.</p>
*
* <h2>Operations over Duration</h2>
* <p>This class provides a set of basic arithmetic operations, such
* as addition, subtraction and multiplication.
* Because durations don't have total order, an operation could
* fail for some combinations of operations. For example, you cannot
* subtract 15 days from 1 month. See the javadoc of those methods
* for detailed conditions where this could happen.</p>
*
* <p>Also, division of a duration by a number is not provided because
* the <code>Duration</code> class can only deal with finite precision
* decimal numbers. For example, one cannot represent 1 sec divided by 3.</p>
*
* <p>However, you could substitute a division by 3 with multiplying
* by numbers such as 0.3 or 0.333.</p>
*
* <h2>Range of allowed values</h2>
* <p>
* Because some operations of <code>Duration</code> rely on {@link Calendar}
* even though {@link Duration} can hold very large or very small values,
* some of the methods may not work correctly on such <code>Duration</code>s.
* The impacted methods document their dependency on {@link Calendar}.
*
* @author <a href="mailto:Joseph.Fialli@Sun.COM">Joseph Fialli</a>
* @author <a href="mailto:Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @author <a href="mailto:Sunitha.Reddy@Sun.com">Sunitha Reddy</a>
* @see XMLGregorianCalendar#add(Duration)
* @since 1.5
*/
public abstract class Duration {
/**
* <p>Debugging <code>true</code> or <code>false</code>.</p>
*/
private static final boolean DEBUG = true;
/**
* Default no-arg constructor.
*
* <p>Note: Always use the {@link DatatypeFactory} to
* construct an instance of <code>Duration</code>.
* The constructor on this class cannot be guaranteed to
* produce an object with a consistent state and may be
* removed in the future.</p>
*/
public Duration() {
}
/**
* <p>Return the name of the XML Schema date/time type that this instance
* maps to. Type is computed based on fields that are set,
* i.e. {@link #isSet(DatatypeConstants.Field field)} == <code>true</code>.</p>
*
* <table border="2" rules="all" cellpadding="2">
* <thead>
* <tr>
* <th align="center" colspan="7">
* Required fields for XML Schema 1.0 Date/Time Datatypes.<br/>
* <i>(timezone is optional for all date/time datatypes)</i>
* </th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>Datatype</td>
* <td>year</td>
* <td>month</td>
* <td>day</td>
* <td>hour</td>
* <td>minute</td>
* <td>second</td>
* </tr>
* <tr>
* <td>{@link DatatypeConstants#DURATION}</td>
* <td>X</td>
* <td>X</td>
* <td>X</td>
* <td>X</td>
* <td>X</td>
* <td>X</td>
* </tr>
* <tr>
* <td>{@link DatatypeConstants#DURATION_DAYTIME}</td>
* <td></td>
* <td></td>
* <td>X</td>
* <td>X</td>
* <td>X</td>
* <td>X</td>
* </tr>
* <tr>
* <td>{@link DatatypeConstants#DURATION_YEARMONTH}</td>
* <td>X</td>
* <td>X</td>
* <td></td>
* <td></td>
* <td></td>
* <td></td>
* </tr>
* </tbody>
* </table>
*
* @return one of the following constants:
* {@link DatatypeConstants#DURATION},
* {@link DatatypeConstants#DURATION_DAYTIME} or
* {@link DatatypeConstants#DURATION_YEARMONTH}.
*
* @throws IllegalStateException If the combination of set fields does not match one of the XML Schema date/time datatypes.
*/
public QName getXMLSchemaType() {
boolean yearSet = isSet(DatatypeConstants.YEARS);
boolean monthSet = isSet(DatatypeConstants.MONTHS);
boolean daySet = isSet(DatatypeConstants.DAYS);
boolean hourSet = isSet(DatatypeConstants.HOURS);
boolean minuteSet = isSet(DatatypeConstants.MINUTES);
boolean secondSet = isSet(DatatypeConstants.SECONDS);
// DURATION
if (yearSet
&& monthSet
&& daySet
&& hourSet
&& minuteSet
&& secondSet) {
return DatatypeConstants.DURATION;
}
// DURATION_DAYTIME
if (!yearSet
&& !monthSet
&& daySet
&& hourSet
&& minuteSet
&& secondSet) {
return DatatypeConstants.DURATION_DAYTIME;
}
// DURATION_YEARMONTH
if (yearSet
&& monthSet
&& !daySet
&& !hourSet
&& !minuteSet
&& !secondSet) {
return DatatypeConstants.DURATION_YEARMONTH;
}
// nothing matches
throw new IllegalStateException(
"javax.xml.datatype.Duration#getXMLSchemaType():"
+ " this Duration does not match one of the XML Schema date/time datatypes:"
+ " year set = " + yearSet
+ " month set = " + monthSet
+ " day set = " + daySet
+ " hour set = " + hourSet
+ " minute set = " + minuteSet
+ " second set = " + secondSet
);
}
/**
* Returns the sign of this duration in -1,0, or 1.
*
* @return
* -1 if this duration is negative, 0 if the duration is zero,
* and 1 if the duration is positive.
*/
public abstract int getSign();
/**
* <p>Get the years value of this <code>Duration</code> as an <code>int</code> or <code>0</code> if not present.</p>
*
* <p><code>getYears()</code> is a convenience method for
* {@link #getField(DatatypeConstants.Field field) getField(DatatypeConstants.YEARS)}.</p>
*
* <p>As the return value is an <code>int</code>, an incorrect value will be returned for <code>Duration</code>s
* with years that go beyond the range of an <code>int</code>.
* Use {@link #getField(DatatypeConstants.Field field) getField(DatatypeConstants.YEARS)} to avoid possible loss of precision.</p>
*
* @return If the years field is present, return its value as an <code>int</code>, else return <code>0</code>.
*/
public int getYears() {
return getField(DatatypeConstants.YEARS).intValue();
}
/**
* Obtains the value of the MONTHS field as an integer value,
* or 0 if not present.
*
* This method works just like {@link #getYears()} except
* that this method works on the MONTHS field.
*
* @return Months of this <code>Duration</code>.
*/
public int getMonths() {
return getField(DatatypeConstants.MONTHS).intValue();
}
/**
* Obtains the value of the DAYS field as an integer value,
* or 0 if not present.
*
* This method works just like {@link #getYears()} except
* that this method works on the DAYS field.
*
* @return Days of this <code>Duration</code>.
*/
public int getDays() {
return getField(DatatypeConstants.DAYS).intValue();
}
/**
* Obtains the value of the HOURS field as an integer value,
* or 0 if not present.
*
* This method works just like {@link #getYears()} except
* that this method works on the HOURS field.
*
* @return Hours of this <code>Duration</code>.
*
*/
public int getHours() {
return getField(DatatypeConstants.HOURS).intValue();
}
/**
* Obtains the value of the MINUTES field as an integer value,
* or 0 if not present.
*
* This method works just like {@link #getYears()} except
* that this method works on the MINUTES field.
*
* @return Minutes of this <code>Duration</code>.
*
*/
public int getMinutes() {
return getField(DatatypeConstants.MINUTES).intValue();
}
/**
* Obtains the value of the SECONDS field as an integer value,
* or 0 if not present.
*
* This method works just like {@link #getYears()} except
* that this method works on the SECONDS field.
*
* @return seconds in the integer value. The fraction of seconds
* will be discarded (for example, if the actual value is 2.5,
* this method returns 2)
*/
public int getSeconds() {
return getField(DatatypeConstants.SECONDS).intValue();
}
/**
* <p>Returns the length of the duration in milli-seconds.</p>
*
* <p>If the seconds field carries more digits than milli-second order,
* those will be simply discarded (or in other words, rounded to zero.)
* For example, for any Calendar value <code>x</code>,</p>
* <pre>
* <code>new Duration("PT10.00099S").getTimeInMills(x) == 10000</code>.
* <code>new Duration("-PT10.00099S").getTimeInMills(x) == -10000</code>.
* </pre>
*
* <p>
* Note that this method uses the {@link #addTo(Calendar)} method,
* which may work incorrectly with <code>Duration</code> objects with
* very large values in its fields. See the {@link #addTo(Calendar)}
* method for details.
*
* @param startInstant
* The length of a month/year varies. The <code>startInstant</code> is
* used to disambiguate this variance. Specifically, this method
* returns the difference between <code>startInstant</code> and
* <code>startInstant+duration</code>
*
* @return milliseconds between <code>startInstant</code> and
* <code>startInstant</code> plus this <code>Duration</code>
*
* @throws NullPointerException if <code>startInstant</code> parameter
* is null.
*
*/
public long getTimeInMillis(final Calendar startInstant) {
Calendar cal = (Calendar) startInstant.clone();
addTo(cal);
return getCalendarTimeInMillis(cal)
- getCalendarTimeInMillis(startInstant);
}
/**
* <p>Returns the length of the duration in milli-seconds.</p>
*
* <p>If the seconds field carries more digits than milli-second order,
* those will be simply discarded (or in other words, rounded to zero.)
* For example, for any <code>Date</code> value <code>x</code>,</p>
* <pre>
* <code>new Duration("PT10.00099S").getTimeInMills(x) == 10000</code>.
* <code>new Duration("-PT10.00099S").getTimeInMills(x) == -10000</code>.
* </pre>
*
* <p>
* Note that this method uses the {@link #addTo(Date)} method,
* which may work incorrectly with <code>Duration</code> objects with
* very large values in its fields. See the {@link #addTo(Date)}
* method for details.
*
* @param startInstant
* The length of a month/year varies. The <code>startInstant</code> is
* used to disambiguate this variance. Specifically, this method
* returns the difference between <code>startInstant</code> and
* <code>startInstant+duration</code>.
*
* @throws NullPointerException
* If the startInstant parameter is null.
*
* @return milliseconds between <code>startInstant</code> and
* <code>startInstant</code> plus this <code>Duration</code>
*
* @see #getTimeInMillis(Calendar)
*/
public long getTimeInMillis(final Date startInstant) {
Calendar cal = new GregorianCalendar();
cal.setTime(startInstant);
this.addTo(cal);
return getCalendarTimeInMillis(cal) - startInstant.getTime();
}
/**
* Gets the value of a field.
*
* Fields of a duration object may contain arbitrary large value.
* Therefore this method is designed to return a {@link Number} object.
*
* In case of YEARS, MONTHS, DAYS, HOURS, and MINUTES, the returned
* number will be a non-negative integer. In case of seconds,
* the returned number may be a non-negative decimal value.
*
* @param field
* one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
* MINUTES, or SECONDS.)
* @return
* If the specified field is present, this method returns
* a non-null non-negative {@link Number} object that
* represents its value. If it is not present, return null.
* For YEARS, MONTHS, DAYS, HOURS, and MINUTES, this method
* returns a {@link java.math.BigInteger} object. For SECONDS, this
* method returns a {@link java.math.BigDecimal}.
*
* @throws NullPointerException If the <code>field</code> is <code>null</code>.
*/
public abstract Number getField(final DatatypeConstants.Field field);
/**
* Checks if a field is set.
*
* A field of a duration object may or may not be present.
* This method can be used to test if a field is present.
*
* @param field
* one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
* MINUTES, or SECONDS.)
* @return
* true if the field is present. false if not.
*
* @throws NullPointerException
* If the field parameter is null.
*/
public abstract boolean isSet(final DatatypeConstants.Field field);
/**
* <p>Computes a new duration whose value is <code>this+rhs</code>.</p>
*
* <p>For example,</p>
* <pre>
* "1 day" + "-3 days" = "-2 days"
* "1 year" + "1 day" = "1 year and 1 day"
* "-(1 hour,50 minutes)" + "-20 minutes" = "-(1 hours,70 minutes)"
* "15 hours" + "-3 days" = "-(2 days,9 hours)"
* "1 year" + "-1 day" = IllegalStateException
* </pre>
*
* <p>Since there's no way to meaningfully subtract 1 day from 1 month,
* there are cases where the operation fails in
* {@link IllegalStateException}.</p>
*
* <p>
* Formally, the computation is defined as follows.</p>
* <p>
* Firstly, we can assume that two <code>Duration</code>s to be added
* are both positive without losing generality (i.e.,
* <code>(-X)+Y=Y-X</code>, <code>X+(-Y)=X-Y</code>,
* <code>(-X)+(-Y)=-(X+Y)</code>)
*
* <p>
* Addition of two positive <code>Duration</code>s are simply defined as
* field by field addition where missing fields are treated as 0.
* <p>
* A field of the resulting <code>Duration</code> will be unset if and
* only if respective fields of two input <code>Duration</code>s are unset.
* <p>
* Note that <code>lhs.add(rhs)</code> will be always successful if
* <code>lhs.signum()*rhs.signum()!=-1</code> or both of them are
* normalized.</p>
*
* @param rhs <code>Duration</code> to add to this <code>Duration</code>
*
* @return
* non-null valid Duration object.
*
* @throws NullPointerException
* If the rhs parameter is null.
* @throws IllegalStateException
* If two durations cannot be meaningfully added. For
* example, adding negative one day to one month causes
* this exception.
*
*
* @see #subtract(Duration)
*/
public abstract Duration add(final Duration rhs);
/**
* Adds this duration to a {@link Calendar} object.
*
* <p>
* Calls {@link java.util.Calendar#add(int,int)} in the
* order of YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, and MILLISECONDS
* if those fields are present. Because the {@link Calendar} class
* uses int to hold values, there are cases where this method
* won't work correctly (for example if values of fields
* exceed the range of int.)
* </p>
*
* <p>
* Also, since this duration class is a Gregorian duration, this
* method will not work correctly if the given {@link Calendar}
* object is based on some other calendar systems.
* </p>
*
* <p>
* Any fractional parts of this <code>Duration</code> object
* beyond milliseconds will be simply ignored. For example, if
* this duration is "P1.23456S", then 1 is added to SECONDS,
* 234 is added to MILLISECONDS, and the rest will be unused.
* </p>
*
* <p>
* Note that because {@link Calendar#add(int, int)} is using
* <code>int</code>, <code>Duration</code> with values beyond the
* range of <code>int</code> in its fields
* will cause overflow/underflow to the given {@link Calendar}.
* {@link XMLGregorianCalendar#add(Duration)} provides the same
* basic operation as this method while avoiding
* the overflow/underflow issues.
*
* @param calendar
* A calendar object whose value will be modified.
* @throws NullPointerException
* if the calendar parameter is null.
*/
public abstract void addTo(Calendar calendar);
/**
* Adds this duration to a {@link Date} object.
*
* <p>
* The given date is first converted into
* a {@link java.util.GregorianCalendar}, then the duration
* is added exactly like the {@link #addTo(Calendar)} method.
*
* <p>
* The updated time instant is then converted back into a
* {@link Date} object and used to update the given {@link Date} object.
*
* <p>
* This somewhat redundant computation is necessary to unambiguously
* determine the duration of months and years.
*
* @param date
* A date object whose value will be modified.
* @throws NullPointerException
* if the date parameter is null.
*/
public void addTo(Date date) {
// check data parameter
if (date == null) {
throw new NullPointerException(
"Cannot call "
+ this.getClass().getName()
+ "#addTo(Date date) with date == null."
);
}
Calendar cal = new GregorianCalendar();
cal.setTime(date);
this.addTo(cal);
date.setTime(getCalendarTimeInMillis(cal));
}
/**
* <p>Computes a new duration whose value is <code>this-rhs</code>.</p>
*
* <p>For example:</p>
* <pre>
* "1 day" - "-3 days" = "4 days"
* "1 year" - "1 day" = IllegalStateException
* "-(1 hour,50 minutes)" - "-20 minutes" = "-(1hours,30 minutes)"
* "15 hours" - "-3 days" = "3 days and 15 hours"
* "1 year" - "-1 day" = "1 year and 1 day"
* </pre>
*
* <p>Since there's no way to meaningfully subtract 1 day from 1 month,
* there are cases where the operation fails in {@link IllegalStateException}.</p>
*
* <p>Formally the computation is defined as follows.
* First, we can assume that two <code>Duration</code>s are both positive
* without losing generality. (i.e.,
* <code>(-X)-Y=-(X+Y)</code>, <code>X-(-Y)=X+Y</code>,
* <code>(-X)-(-Y)=-(X-Y)</code>)</p>
*
* <p>Then two durations are subtracted field by field.
* If the sign of any non-zero field <code>F</code> is different from
* the sign of the most significant field,
* 1 (if <code>F</code> is negative) or -1 (otherwise)
* will be borrowed from the next bigger unit of <code>F</code>.</p>
*
* <p>This process is repeated until all the non-zero fields have
* the same sign.</p>
*
* <p>If a borrow occurs in the days field (in other words, if
* the computation needs to borrow 1 or -1 month to compensate
* days), then the computation fails by throwing an
* {@link IllegalStateException}.</p>
*
* @param rhs <code>Duration</code> to subtract from this <code>Duration</code>.
*
* @return New <code>Duration</code> created from subtracting <code>rhs</code> from this <code>Duration</code>.
*
* @throws IllegalStateException
* If two durations cannot be meaningfully subtracted. For
* example, subtracting one day from one month causes
* this exception.
*
* @throws NullPointerException
* If the rhs parameter is null.
*
* @see #add(Duration)
*/
public Duration subtract(final Duration rhs) {
return add(rhs.negate());
}
/**
* <p>Computes a new duration whose value is <code>factor</code> times
* longer than the value of this duration.</p>
*
* <p>This method is provided for the convenience.
* It is functionally equivalent to the following code:</p>
* <pre>
* multiply(new BigDecimal(String.valueOf(factor)))
* </pre>
*
* @param factor Factor times longer of new <code>Duration</code> to create.
*
* @return New <code>Duration</code> that is <code>factor</code>times longer than this <code>Duration</code>.
*
* @see #multiply(BigDecimal)
*/
public Duration multiply(int factor) {
return multiply(new BigDecimal(String.valueOf(factor)));
}
/**
* Computes a new duration whose value is <code>factor</code> times
* longer than the value of this duration.
*
* <p>
* For example,
* <pre>
* "P1M" (1 month) * "12" = "P12M" (12 months)
* "PT1M" (1 min) * "0.3" = "PT18S" (18 seconds)
* "P1M" (1 month) * "1.5" = IllegalStateException
* </pre>
*
* <p>
* Since the <code>Duration</code> class is immutable, this method
* doesn't change the value of this object. It simply computes
* a new Duration object and returns it.
*
* <p>
* The operation will be performed field by field with the precision
* of {@link BigDecimal}. Since all the fields except seconds are
* restricted to hold integers,
* any fraction produced by the computation will be
* carried down toward the next lower unit. For example,
* if you multiply "P1D" (1 day) with "0.5", then it will be 0.5 day,
* which will be carried down to "PT12H" (12 hours).
* When fractions of month cannot be meaningfully carried down
* to days, or year to months, this will cause an
* {@link IllegalStateException} to be thrown.
* For example if you multiple one month by 0.5.</p>
*
* <p>
* To avoid {@link IllegalStateException}, use
* the {@link #normalizeWith(Calendar)} method to remove the years
* and months fields.
*
* @param factor to multiply by
*
* @return
* returns a non-null valid <code>Duration</code> object
*
* @throws IllegalStateException if operation produces fraction in
* the months field.
*
* @throws NullPointerException if the <code>factor</code> parameter is
* <code>null</code>.
*
*/
public abstract Duration multiply(final BigDecimal factor);
/**
* Returns a new <code>Duration</code> object whose
* value is <code>-this</code>.
*
* <p>
* Since the <code>Duration</code> class is immutable, this method
* doesn't change the value of this object. It simply computes
* a new Duration object and returns it.
*
* @return
* always return a non-null valid <code>Duration</code> object.
*/
public abstract Duration negate();
/**
* <p>Converts the years and months fields into the days field
* by using a specific time instant as the reference point.</p>
*
* <p>For example, duration of one month normalizes to 31 days
* given the start time instance "July 8th 2003, 17:40:32".</p>
*
* <p>Formally, the computation is done as follows:</p>
* <ol>
* <li>the given Calendar object is cloned</li>
* <li>the years, months and days fields will be added to the {@link Calendar} object
* by using the {@link Calendar#add(int,int)} method</li>
* <li>the difference between the two Calendars in computed in milliseconds and converted to days,
* if a remainder occurs due to Daylight Savings Time, it is discarded</li>
* <li>the computed days, along with the hours, minutes and seconds
* fields of this duration object is used to construct a new
* Duration object.</li>
* </ol>
*
* <p>Note that since the Calendar class uses <code>int</code> to
* hold the value of year and month, this method may produce
* an unexpected result if this duration object holds
* a very large value in the years or months fields.</p>
*
* @param startTimeInstant <code>Calendar</code> reference point.
*
* @return <code>Duration</code> of years and months of this <code>Duration</code> as days.
*
* @throws NullPointerException If the startTimeInstant parameter is null.
*/
public abstract Duration normalizeWith(final Calendar startTimeInstant);
/**
* <p>Partial order relation comparison with this <code>Duration</code> instance.</p>
*
* <p>Comparison result must be in accordance with
* <a href="http://www.w3.org/TR/xmlschema-2/#duration-order">W3C XML Schema 1.0 Part 2, Section 3.2.7.6.2,
* <i>Order relation on duration</i></a>.</p>
*
* <p>Return:</p>
* <ul>
* <li>{@link DatatypeConstants#LESSER} if this <code>Duration</code> is shorter than <code>duration</code> parameter</li>
* <li>{@link DatatypeConstants#EQUAL} if this <code>Duration</code> is equal to <code>duration</code> parameter</li>
* <li>{@link DatatypeConstants#GREATER} if this <code>Duration</code> is longer than <code>duration</code> parameter</li>
* <li>{@link DatatypeConstants#INDETERMINATE} if a conclusive partial order relation cannot be determined</li>
* </ul>
*
* @param duration to compare
*
* @return the relationship between <code>this</code> <code>Duration</code>and <code>duration</code> parameter as
* {@link DatatypeConstants#LESSER}, {@link DatatypeConstants#EQUAL}, {@link DatatypeConstants#GREATER}
* or {@link DatatypeConstants#INDETERMINATE}.
*
* @throws UnsupportedOperationException If the underlying implementation
* cannot reasonably process the request, e.g. W3C XML Schema allows for
* arbitrarily large/small/precise values, the request may be beyond the
* implementations capability.
* @throws NullPointerException if <code>duration</code> is <code>null</code>.
*
* @see #isShorterThan(Duration)
* @see #isLongerThan(Duration)
*/
public abstract int compare(final Duration duration);
/**
* <p>Checks if this duration object is strictly longer than
* another <code>Duration</code> object.</p>
*
* <p>Duration X is "longer" than Y if and only if X>Y
* as defined in the section 3.2.6.2 of the XML Schema 1.0
* specification.</p>
*
* <p>For example, "P1D" (one day) > "PT12H" (12 hours) and
* "P2Y" (two years) > "P23M" (23 months).</p>
*
* @param duration <code>Duration</code> to test this <code>Duration</code> against.
*
* @throws UnsupportedOperationException If the underlying implementation
* cannot reasonably process the request, e.g. W3C XML Schema allows for
* arbitrarily large/small/precise values, the request may be beyond the
* implementations capability.
* @throws NullPointerException If <code>duration</code> is null.
*
* @return
* true if the duration represented by this object
* is longer than the given duration. false otherwise.
*
* @see #isShorterThan(Duration)
* @see #compare(Duration duration)
*/
public boolean isLongerThan(final Duration duration) {
return compare(duration) == DatatypeConstants.GREATER;
}
/**
* <p>Checks if this duration object is strictly shorter than
* another <code>Duration</code> object.</p>
*
* @param duration <code>Duration</code> to test this <code>Duration</code> against.
*
* @return <code>true</code> if <code>duration</code> parameter is shorter than this <code>Duration</code>,
* else <code>false</code>.
*
* @throws UnsupportedOperationException If the underlying implementation
* cannot reasonably process the request, e.g. W3C XML Schema allows for
* arbitrarily large/small/precise values, the request may be beyond the
* implementations capability.
* @throws NullPointerException if <code>duration</code> is null.
*
* @see #isLongerThan(Duration duration)
* @see #compare(Duration duration)
*/
public boolean isShorterThan(final Duration duration) {
return compare(duration) == DatatypeConstants.LESSER;
}
/**
* <p>Checks if this duration object has the same duration
* as another <code>Duration</code> object.</p>
*
* <p>For example, "P1D" (1 day) is equal to "PT24H" (24 hours).</p>
*
* <p>Duration X is equal to Y if and only if time instant
* t+X and t+Y are the same for all the test time instants
* specified in the section 3.2.6.2 of the XML Schema 1.0
* specification.</p>
*
* <p>Note that there are cases where two <code>Duration</code>s are
* "incomparable" to each other, like one month and 30 days.
* For example,</p>
* <pre>
* !new Duration("P1M").isShorterThan(new Duration("P30D"))
* !new Duration("P1M").isLongerThan(new Duration("P30D"))
* !new Duration("P1M").equals(new Duration("P30D"))
* </pre>
*
* @param duration
* The object to compare this <code>Duration</code> against.
*
* @return
* <code>true</code> if this duration is the same length as
* <code>duration</code>.
* <code>false</code> if <code>duration</code> is <code>null</code>,
* is not a
* <code>Duration</code> object,
* or its length is different from this duration.
*
* @throws UnsupportedOperationException If the underlying implementation
* cannot reasonably process the request, e.g. W3C XML Schema allows for
* arbitrarily large/small/precise values, the request may be beyond the
* implementations capability.
*
* @see #compare(Duration duration)
*/
public boolean equals(final Object duration) {
if (duration == null || !(duration instanceof Duration)) {
return false;
}
return compare((Duration) duration) == DatatypeConstants.EQUAL;
}
/**
* Returns a hash code consistent with the definition of the equals method.
*
* @see Object#hashCode()
*/
public abstract int hashCode();
/**
* <p>Returns a <code>String</code> representation of this <code>Duration</code> <code>Object</code>.</p>
*
* <p>The result is formatted according to the XML Schema 1.0 spec and can be always parsed back later into the
* equivalent <code>Duration</code> <code>Object</code> by {@link DatatypeFactory#newDuration(String lexicalRepresentation)}.</p>
*
* <p>Formally, the following holds for any <code>Duration</code>
* <code>Object</code> x:</p>
* <pre>
* new Duration(x.toString()).equals(x)
* </pre>
*
* @return A non-<code>null</code> valid <code>String</code> representation of this <code>Duration</code>.
*/
public String toString() {
StringBuffer buf = new StringBuffer();
if (getSign() < 0) {
buf.append('-');
}
buf.append('P');
BigInteger years = (BigInteger) getField(DatatypeConstants.YEARS);
if (years != null) {
buf.append(years + "Y");
}
BigInteger months = (BigInteger) getField(DatatypeConstants.MONTHS);
if (months != null) {
buf.append(months + "M");
}
BigInteger days = (BigInteger) getField(DatatypeConstants.DAYS);
if (days != null) {
buf.append(days + "D");
}
BigInteger hours = (BigInteger) getField(DatatypeConstants.HOURS);
BigInteger minutes = (BigInteger) getField(DatatypeConstants.MINUTES);
BigDecimal seconds = (BigDecimal) getField(DatatypeConstants.SECONDS);
if (hours != null || minutes != null || seconds != null) {
buf.append('T');
if (hours != null) {
buf.append(hours + "H");
}
if (minutes != null) {
buf.append(minutes + "M");
}
if (seconds != null) {
buf.append(toString(seconds) + "S");
}
}
return buf.toString();
}
/**
* <p>Turns {@link BigDecimal} to a string representation.</p>
*
* <p>Due to a behavior change in the {@link BigDecimal#toString()}
* method in JDK1.5, this had to be implemented here.</p>
*
* @param bd <code>BigDecimal</code> to format as a <code>String</code>
*
* @return <code>String</code> representation of <code>BigDecimal</code>
*/
private String toString(BigDecimal bd) {
String intString = bd.unscaledValue().toString();
int scale = bd.scale();
if (scale == 0) {
return intString;
}
/* Insert decimal point */
StringBuffer buf;
int insertionPoint = intString.length() - scale;
if (insertionPoint == 0) { /* Point goes right before intVal */
return "0." + intString;
} else if (insertionPoint > 0) { /* Point goes inside intVal */
buf = new StringBuffer(intString);
buf.insert(insertionPoint, '.');
} else { /* We must insert zeros between point and intVal */
buf = new StringBuffer(3 - insertionPoint + intString.length());
buf.append("0.");
for (int i = 0; i < -insertionPoint; i++) {
buf.append('0');
}
buf.append(intString);
}
return buf.toString();
}
/**
* <p>Calls the {@link Calendar#getTimeInMillis} method.
* Prior to JDK1.4, this method was protected and therefore
* cannot be invoked directly.</p>
*
* <p>TODO: In future, this should be replaced by <code>cal.getTimeInMillis()</code>.</p>
*
* @param cal <code>Calendar</code> to get time in milliseconds.
*
* @return Milliseconds of <code>cal</code>.
*/
private static long getCalendarTimeInMillis(final Calendar cal) {
return cal.getTime().getTime();
}
}

View file

@ -0,0 +1,320 @@
/*
* Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.datatype;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
/**
* <p>Implements pluggable Datatypes.</p>
*
* <p>This class is duplicated for each JAXP subpackage so keep it in
* sync. It is package private for secure class loading.</p>
*
* @author Santiago.PericasGeertsen@sun.com
*/
class FactoryFinder {
/**
* Internal debug flag.
*/
private static boolean debug = false;
/**
* Cache for properties in java.home/lib/jaxp.properties
*/
static Properties cacheProps = new Properties();
/**
* Flag indicating if properties from java.home/lib/jaxp.properties
* have been cached.
*/
static boolean firstTime = true;
/**
* Security support class use to check access control before
* getting certain system resources.
*/
static SecuritySupport ss = new SecuritySupport();
// Define system property "jaxp.debug" to get output
static {
// Use try/catch block to support applets, which throws
// SecurityException out of this code.
try {
String val = ss.getSystemProperty("jaxp.debug");
// Allow simply setting the prop to turn on debug
debug = val != null && !"false".equals(val);
}
catch (SecurityException se) {
debug = false;
}
}
private static void dPrint(String msg) {
if (debug) {
System.err.println("JAXP: " + msg);
}
}
/**
* Attempt to load a class using the class loader supplied. If that fails
* and fall back is enabled, the current (i.e. bootstrap) class loader is
* tried.
*
* If the class loader supplied is <code>null</code>, first try using the
* context class loader followed by the current (i.e. bootstrap) class
* loader.
*/
static private Class getProviderClass(String className, ClassLoader cl,
boolean doFallback) throws ClassNotFoundException
{
try {
if (cl == null) {
cl = ss.getContextClassLoader();
if (cl == null) {
throw new ClassNotFoundException();
}
else {
return cl.loadClass(className);
}
}
else {
return cl.loadClass(className);
}
}
catch (ClassNotFoundException e1) {
if (doFallback) {
// Use current class loader - should always be bootstrap CL
return Class.forName(className, true, FactoryFinder.class.getClassLoader());
}
else {
throw e1;
}
}
}
/**
* Create an instance of a class. Delegates to method
* <code>getProviderClass()</code> in order to load the class.
*
* @param className Name of the concrete class corresponding to the
* service provider
*
* @param cl ClassLoader to use to load the class, null means to use
* the bootstrap ClassLoader
*
* @param doFallback True if the current ClassLoader should be tried as
* a fallback if the class is not found using cl
*/
static Object newInstance(String className, ClassLoader cl, boolean doFallback)
throws ConfigurationError
{
try {
Class providerClass = getProviderClass(className, cl, doFallback);
Object instance = providerClass.newInstance();
if (debug) { // Extra check to avoid computing cl strings
dPrint("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);
}
}
/**
* Finds the implementation Class object in the specified order. Main
* entry point.
* @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.
*
* Package private so this code can be shared.
*/
static Object find(String factoryId, String fallbackClassName)
throws ConfigurationError
{
dPrint("find factoryId =" + factoryId);
// Use the system property first
try {
String systemProp = ss.getSystemProperty(factoryId);
if (systemProp != null) {
dPrint("found system property, value=" + systemProp);
return newInstance(systemProp, null, true);
}
}
catch (SecurityException se) {
if (debug) se.printStackTrace();
}
// try to read from $java.home/lib/jaxp.properties
try {
String factoryClassName = null;
if (firstTime) {
synchronized (cacheProps) {
if (firstTime) {
String configFile = ss.getSystemProperty("java.home") + File.separator +
"lib" + File.separator + "jaxp.properties";
File f = new File(configFile);
firstTime = false;
if (ss.doesFileExist(f)) {
dPrint("Read properties file "+f);
cacheProps.load(ss.getFileInputStream(f));
}
}
}
}
factoryClassName = cacheProps.getProperty(factoryId);
if (factoryClassName != null) {
dPrint("found in $java.home/jaxp.properties, value=" + factoryClassName);
return newInstance(factoryClassName, null, true);
}
}
catch (Exception ex) {
if (debug) ex.printStackTrace();
}
// 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);
}
dPrint("loaded from fallback value: " + fallbackClassName);
return newInstance(fallbackClassName, null, true);
}
/*
* 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
{
String serviceId = "META-INF/services/" + factoryId;
InputStream is = null;
// First try the Context ClassLoader
ClassLoader cl = ss.getContextClassLoader();
if (cl != null) {
is = ss.getResourceAsStream(cl, serviceId);
// If no provider found then try the current ClassLoader
if (is == null) {
cl = FactoryFinder.class.getClassLoader();
is = ss.getResourceAsStream(cl, serviceId);
}
} else {
// No Context ClassLoader, try the current ClassLoader
cl = FactoryFinder.class.getClassLoader();
is = ss.getResourceAsStream(cl, serviceId);
}
if (is == null) {
// No provider found
return null;
}
if (debug) { // Extra check to avoid computing cl strings
dPrint("found jar resource=" + serviceId + " using ClassLoader: " + cl);
}
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
}
catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is));
}
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)) {
dPrint("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;
}
static class ConfigurationError extends Error {
private Exception exception;
/**
* Construct a new instance with the specified detail string and
* exception.
*/
ConfigurationError(String msg, Exception x) {
super(msg);
this.exception = x;
}
Exception getException() {
return exception;
}
}
}

View file

@ -0,0 +1,106 @@
/*
* Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.datatype;
import java.security.*;
import java.net.*;
import java.io.*;
import java.util.*;
/**
* 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 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;
}
});
}
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 doesFileExist(final File f) {
return ((Boolean)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return new Boolean(f.exists());
}
})).booleanValue();
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,170 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2004-2005 Sun Microsystems, Inc. All Rights Reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation. Sun designates this
particular file as subject to the "Classpath" exception as provided
by Sun in the LICENSE file that accompanied this code.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
CA 95054 USA or visit www.sun.com if you need additional information or
have any questions.
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>javax.xml.xpath</title>
<meta name="@author" content="mailto:Jeff.Suttor@Sun.com" />
<meta name="@version" content="$Revision: 1.2 $, $Date: 2005/06/10 03:50:27 $" />
<meta name="@see" content='<a href="http://www.w3.org/TR/xmlschema-2/#dateTime">W3C XML Schema 1.0 Part 2, Section 3.2.7-14</a>' />
<meta name="@see" content='<a href="http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration">XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration</a>' />
<meta name="@see" content='<a href="http://www.w3.org/TR/xpath-datamodel#dt-yearMonthDuration">XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration</a>' />
<meta name="@since" content="1.5" />
</head>
<body>
<p>XML/Java Type Mappings.</p>
<p><code>javax.xml.datatype</code>API provides XML/Java type mappings.</p>
<p>The following XML standards apply:</p>
<ul>
<li><a href="http://www.w3.org/TR/xmlschema-2/#dateTime">W3C XML Schema 1.0 Part 2, Section 3.2.7-14</a></li>
<li><a href="http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration">XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration</a></li>
<li><a href="http://www.w3.org/TR/xpath-datamodel#dt-yearMonthDuration">XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration</a></li>
</ul>
<hr />
<table border="1" cellpadding="2">
<thead>
<tr>
<th>W3C XML Schema Data Type</th>
<th>Java Data Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>xs:date</td>
<td>{@link javax.xml.datatype.XMLGregorianCalendar}</td>
</tr>
<tr>
<td>xs:dateTime</td>
<td>{@link javax.xml.datatype.XMLGregorianCalendar}</td>
</tr>
<tr>
<td>xs:duration</td>
<td>{@link javax.xml.datatype.Duration}</td>
</tr>
<tr>
<td>xs:gDay</td>
<td>{@link javax.xml.datatype.XMLGregorianCalendar}</td>
</tr>
<tr>
<td>xs:gMonth </td>
<td>{@link javax.xml.datatype.XMLGregorianCalendar}</td>
</tr>
<tr>
<td>xs:gMonthDay</td>
<td>{@link javax.xml.datatype.XMLGregorianCalendar}</td>
</tr>
<tr>
<td>xs:gYear</td>
<td>{@link javax.xml.datatype.XMLGregorianCalendar}</td>
</tr>
<tr>
<td>xs:gYearMonth</td>
<td>{@link javax.xml.datatype.XMLGregorianCalendar}</td>
</tr>
<tr>
<td>xs:time</td>
<td>{@link javax.xml.datatype.XMLGregorianCalendar}</td>
</tr>
</tbody>
</table>
<hr />
<table border="1" cellpadding="2">
<thead>
<tr>
<th>XQuery 1.0 and XPath 2.0 Data Model</th>
<th>Java Data Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>xdt:dayTimeDuration</td>
<td>{@link javax.xml.datatype.Duration}</td>
</tr>
<tr>
<td>xdt:yearMonthDuration</td>
<td>{@link javax.xml.datatype.Duration}</td>
</tr>
</tbody>
</table>
<hr />
<p>
W3C XML Schema data types that have a "<em>natural</em>" mapping to Java types are defined by
JSR 31: Java&trade; Architecture for XML Binding (JAXB) Specification, Binding XML Schema to Java Representations.
JAXB defined mappings for XML Schema built-in data types include:
</p>
<ul>
<li>xs:anySimpleType</li>
<li>xs:base64Binary</li>
<li>xs:boolean</li>
<li>xs:byte</li>
<li>xs:decimal</li>
<li>xs:double</li>
<li>xs:float</li>
<li>xs:hexBinary</li>
<li>xs:int</li>
<li>xs:integer</li>
<li>xs:long</li>
<li>xs:QName</li>
<li>xs:short</li>
<li>xs:string</li>
<li>xs:unsignedByte</li>
<li>xs:unsignedInt</li>
<li>xs:unsignedShort</li>
</ul>
<hr />
<ul>
<li>Author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a></li>
<li>See <a href="http://www.w3.org/TR/xmlschema-2/#dateTime">W3C XML Schema 1.0 Part 2, Section 3.2.7-14</a></li>
<li>See <a href="http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration">XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration</a></li>
<li>See <a href="http://www.w3.org/TR/xpath-datamodel#dt-yearMonthDuration">XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration</a></li>
<li>Since 1.5</li>
</ul>
<hr />
</body>
</html>

View file

@ -0,0 +1,288 @@
/*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.namespace;
import java.util.Iterator;
/**
* <p>Interface for read only XML Namespace context processing.</p>
*
* <p>An XML Namespace has the properties:</p>
* <ul>
* <li>Namespace URI:
* Namespace name expressed as a URI to which the prefix is bound</li>
* <li>prefix: syntactically, this is the part of the attribute name
* following the <code>XMLConstants.XMLNS_ATTRIBUTE</code>
* ("xmlns") in the Namespace declaration</li>
* </ul>
* <p>example:
* <code>&lt;element xmlns:prefix="http://Namespace-name-URI"&gt;</code></p>
*
* <p>All <code>get*(*)</code> methods operate in the current scope
* for Namespace URI and prefix resolution.</p>
*
* <p>Note that a Namespace URI can be bound to
* <strong>multiple</strong> prefixes in the current scope. This can
* occur when multiple <code>XMLConstants.XMLNS_ATTRIBUTE</code>
* ("xmlns") Namespace declarations occur in the same Start-Tag and
* refer to the same Namespace URI. e.g.<br />
* <pre>
* &lt;element xmlns:prefix1="http://Namespace-name-URI"
* xmlns:prefix2="http://Namespace-name-URI"&gt;
* </pre>
* This can also occur when the same Namespace URI is used in multiple
* <code>XMLConstants.XMLNS_ATTRIBUTE</code> ("xmlns") Namespace
* declarations in the logical parent element hierarchy. e.g.<br />
* <pre>
* &lt;parent xmlns:prefix1="http://Namespace-name-URI">
* &lt;child xmlns:prefix2="http://Namespace-name-URI"&gt;
* ...
* &lt;/child&gt;
* &lt;/parent&gt;
* </pre></p>
*
* <p>A prefix can only be bound to a <strong>single</strong>
* Namespace URI in the current scope.</p>
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @see javax.xml.XMLConstants
* javax.xml.XMLConstants for declarations of common XML values
* @see <a href="http://www.w3.org/TR/xmlschema-2/#QName">
* XML Schema Part2: Datatypes</a>
* @see <a href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">
* Namespaces in XML</a>
* @see <a href="http://www.w3.org/XML/xml-names-19990114-errata">
* Namespaces in XML Errata</a>
* @since 1.5
*/
public interface NamespaceContext {
/**
* <p>Get Namespace URI bound to a prefix in the current scope.</p>
*
* <p>When requesting a Namespace URI by prefix, the following
* table describes the returned Namespace URI value for all
* possible prefix values:</p>
*
* <table border="2" rules="all" cellpadding="4">
* <thead>
* <tr>
* <td align="center" colspan="2">
* <code>getNamespaceURI(prefix)</code>
* return value for specified prefixes
* </td>
* </tr>
* <tr>
* <td>prefix parameter</td>
* <td>Namespace URI return value</td>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td><code>DEFAULT_NS_PREFIX</code> ("")</td>
* <td>default Namespace URI in the current scope or
* <code>{@link
* javax.xml.XMLConstants#NULL_NS_URI XMLConstants.NULL_NS_URI("")}
* </code>
* when there is no default Namespace URI in the current scope</td>
* </tr>
* <tr>
* <td>bound prefix</td>
* <td>Namespace URI bound to prefix in current scope</td>
* </tr>
* <tr>
* <td>unbound prefix</td>
* <td>
* <code>{@link
* javax.xml.XMLConstants#NULL_NS_URI XMLConstants.NULL_NS_URI("")}
* </code>
* </td>
* </tr>
* <tr>
* <td><code>XMLConstants.XML_NS_PREFIX</code> ("xml")</td>
* <td><code>XMLConstants.XML_NS_URI</code>
* ("http://www.w3.org/XML/1998/namespace")</td>
* </tr>
* <tr>
* <td><code>XMLConstants.XMLNS_ATTRIBUTE</code> ("xmlns")</td>
* <td><code>XMLConstants.XMLNS_ATTRIBUTE_NS_URI</code>
* ("http://www.w3.org/2000/xmlns/")</td>
* </tr>
* <tr>
* <td><code>null</code></td>
* <td><code>IllegalArgumentException</code> is thrown</td>
* </tr>
* </tbody>
* </table>
*
* @param prefix prefix to look up
*
* @return Namespace URI bound to prefix in the current scope
*
* @throws IllegalArgumentException When <code>prefix</code> is
* <code>null</code>
*/
String getNamespaceURI(String prefix);
/**
* <p>Get prefix bound to Namespace URI in the current scope.</p>
*
* <p>To get all prefixes bound to a Namespace URI in the current
* scope, use {@link #getPrefixes(String namespaceURI)}.</p>
*
* <p>When requesting a prefix by Namespace URI, the following
* table describes the returned prefix value for all Namespace URI
* values:</p>
*
* <table border="2" rules="all" cellpadding="4">
* <thead>
* <tr>
* <th align="center" colspan="2">
* <code>getPrefix(namespaceURI)</code> return value for
* specified Namespace URIs
* </th>
* </tr>
* <tr>
* <th>Namespace URI parameter</th>
* <th>prefix value returned</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>&lt;default Namespace URI&gt;</td>
* <td><code>XMLConstants.DEFAULT_NS_PREFIX</code> ("")
* </td>
* </tr>
* <tr>
* <td>bound Namespace URI</td>
* <td>prefix bound to Namespace URI in the current scope,
* if multiple prefixes are bound to the Namespace URI in
* the current scope, a single arbitrary prefix, whose
* choice is implementation dependent, is returned</td>
* </tr>
* <tr>
* <td>unbound Namespace URI</td>
* <td><code>null</code></td>
* </tr>
* <tr>
* <td><code>XMLConstants.XML_NS_URI</code>
* ("http://www.w3.org/XML/1998/namespace")</td>
* <td><code>XMLConstants.XML_NS_PREFIX</code> ("xml")</td>
* </tr>
* <tr>
* <td><code>XMLConstants.XMLNS_ATTRIBUTE_NS_URI</code>
* ("http://www.w3.org/2000/xmlns/")</td>
* <td><code>XMLConstants.XMLNS_ATTRIBUTE</code> ("xmlns")</td>
* </tr>
* <tr>
* <td><code>null</code></td>
* <td><code>IllegalArgumentException</code> is thrown</td>
* </tr>
* </tbody>
* </table>
*
* @param namespaceURI URI of Namespace to lookup
*
* @return prefix bound to Namespace URI in current context
*
* @throws IllegalArgumentException When <code>namespaceURI</code> is
* <code>null</code>
*/
String getPrefix(String namespaceURI);
/**
* <p>Get all prefixes bound to a Namespace URI in the current
* scope.</p>
*
* <p>An Iterator over String elements is returned in an arbitrary,
* <strong>implementation dependent</strong>, order.</p>
*
* <p><strong>The <code>Iterator</code> is
* <em>not</em> modifiable. e.g. the
* <code>remove()</code> method will throw
* <code>UnsupportedOperationException</code>.</strong></p>
*
* <p>When requesting prefixes by Namespace URI, the following
* table describes the returned prefixes value for all Namespace
* URI values:</p>
*
* <table border="2" rules="all" cellpadding="4">
* <thead>
* <tr>
* <th align="center" colspan="2"><code>
* getPrefixes(namespaceURI)</code> return value for
* specified Namespace URIs</th>
* </tr>
* <tr>
* <th>Namespace URI parameter</th>
* <th>prefixes value returned</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>bound Namespace URI,
* including the &lt;default Namespace URI&gt;</td>
* <td>
* <code>Iterator</code> over prefixes bound to Namespace URI in
* the current scope in an arbitrary,
* <strong>implementation dependent</strong>,
* order
* </td>
* </tr>
* <tr>
* <td>unbound Namespace URI</td>
* <td>empty <code>Iterator</code></td>
* </tr>
* <tr>
* <td><code>XMLConstants.XML_NS_URI</code>
* ("http://www.w3.org/XML/1998/namespace")</td>
* <td><code>Iterator</code> with one element set to
* <code>XMLConstants.XML_NS_PREFIX</code> ("xml")</td>
* </tr>
* <tr>
* <td><code>XMLConstants.XMLNS_ATTRIBUTE_NS_URI</code>
* ("http://www.w3.org/2000/xmlns/")</td>
* <td><code>Iterator</code> with one element set to
* <code>XMLConstants.XMLNS_ATTRIBUTE</code> ("xmlns")</td>
* </tr>
* <tr>
* <td><code>null</code></td>
* <td><code>IllegalArgumentException</code> is thrown</td>
* </tr>
* </tbody>
* </table>
*
* @param namespaceURI URI of Namespace to lookup
*
* @return <code>Iterator</code> for all prefixes bound to the
* Namespace URI in the current scope
*
* @throws IllegalArgumentException When <code>namespaceURI</code> is
* <code>null</code>
*/
Iterator getPrefixes(String namespaceURI);
}

View file

@ -0,0 +1,511 @@
/*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.namespace;
import java.io.Serializable;
import java.security.AccessController;
import java.security.PrivilegedAction;
import javax.xml.XMLConstants;
/**
* <p><code>QName</code> represents a <strong>qualified name</strong>
* as defined in the XML specifications: <a
* href="http://www.w3.org/TR/xmlschema-2/#QName">XML Schema Part2:
* Datatypes specification</a>, <a
* href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">Namespaces
* in XML</a>, <a
* href="http://www.w3.org/XML/xml-names-19990114-errata">Namespaces
* in XML Errata</a>.</p>
*
* <p>The value of a <code>QName</code> contains a <strong>Namespace
* URI</strong>, <strong>local part</strong> and
* <strong>prefix</strong>.</p>
*
* <p>The prefix is included in <code>QName</code> to retain lexical
* information <strong><em>when present</em></strong> in an {@link
* javax.xml.transform.Source XML input source}. The prefix is
* <strong><em>NOT</em></strong> used in {@link #equals(Object)
* QName.equals(Object)} or to compute the {@link #hashCode()
* QName.hashCode()}. Equality and the hash code are defined using
* <strong><em>only</em></strong> the Namespace URI and local part.</p>
*
* <p>If not specified, the Namespace URI is set to {@link
* javax.xml.XMLConstants#NULL_NS_URI XMLConstants.NULL_NS_URI}.
* If not specified, the prefix is set to {@link
* javax.xml.XMLConstants#DEFAULT_NS_PREFIX
* XMLConstants.DEFAULT_NS_PREFIX}.</p>
*
* <p><code>QName</code> is immutable.</p>
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @see <a href="http://www.w3.org/TR/xmlschema-2/#QName">
* XML Schema Part2: Datatypes specification</a>
* @see <a href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">
* Namespaces in XML</a>
* @see <a href="http://www.w3.org/XML/xml-names-19990114-errata">
* Namespaces in XML Errata</a>
* @since 1.5
*/
public class QName implements Serializable {
/**
* <p>Stream Unique Identifier.</p>
*
* <p>Due to a historical defect, QName was released with multiple
* serialVersionUID values even though its serialization was the
* same.</p>
*
* <p>To workaround this issue, serialVersionUID is set with either
* a default value or a compatibility value. To use the
* compatiblity value, set the system property:</p>
*
* <code>com.sun.xml.namespace.QName.useCompatibleSerialVersionUID=1.0</code>
*
* <p>This workaround was inspired by classes in the javax.management
* package, e.g. ObjectName, etc.
* See CR6267224 for original defect report.</p>
*/
private static final long serialVersionUID;
/**
* <p>Default <code>serialVersionUID</code> value.</p>
*/
private static final long defaultSerialVersionUID = -9120448754896609940L;
/**
* <p>Compatibility <code>serialVersionUID</code> value.</p>
*/
private static final long compatibleSerialVersionUID = 4418622981026545151L;
/**
* <p>Flag to use default or campatible serialVersionUID.</p>
*/
private static boolean useDefaultSerialVersionUID = true;
static {
try {
// use a privileged block as reading a system property
String valueUseCompatibleSerialVersionUID = (String) AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
return System.getProperty("com.sun.xml.namespace.QName.useCompatibleSerialVersionUID");
}
}
);
useDefaultSerialVersionUID = (valueUseCompatibleSerialVersionUID != null && valueUseCompatibleSerialVersionUID.equals("1.0")) ? false : true;
} catch (Exception exception) {
// use default if any Exceptions
useDefaultSerialVersionUID = true;
}
// set serialVersionUID to desired value
if (useDefaultSerialVersionUID) {
serialVersionUID = defaultSerialVersionUID;
} else {
serialVersionUID = compatibleSerialVersionUID;
}
}
/**
* <p>Namespace URI of this <code>QName</code>.</p>
*/
private final String namespaceURI;
/**
* <p>local part of this <code>QName</code>.</p>
*/
private final String localPart;
/**
* <p>prefix of this <code>QName</code>.</p>
*/
private final String prefix;
/**
* <p><code>QName</code> constructor specifying the Namespace URI
* and local part.</p>
*
* <p>If the Namespace URI is <code>null</code>, it is set to
* {@link javax.xml.XMLConstants#NULL_NS_URI
* XMLConstants.NULL_NS_URI}. This value represents no
* explicitly defined Namespace as defined by the <a
* href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">Namespaces
* in XML</a> specification. This action preserves compatible
* behavior with QName 1.0. Explicitly providing the {@link
* javax.xml.XMLConstants#NULL_NS_URI
* XMLConstants.NULL_NS_URI} value is the preferred coding
* style.</p>
*
* <p>If the local part is <code>null</code> an
* <code>IllegalArgumentException</code> is thrown.
* A local part of "" is allowed to preserve
* compatible behavior with QName 1.0. </p>
*
* <p>When using this constructor, the prefix is set to {@link
* javax.xml.XMLConstants#DEFAULT_NS_PREFIX
* XMLConstants.DEFAULT_NS_PREFIX}.</p>
*
* <p>The Namespace URI is not validated as a
* <a href="http://www.ietf.org/rfc/rfc2396.txt">URI reference</a>.
* The local part is not validated as a
* <a href="http://www.w3.org/TR/REC-xml-names/#NT-NCName">NCName</a>
* as specified in <a href="http://www.w3.org/TR/REC-xml-names/">Namespaces
* in XML</a>.</p>
*
* @param namespaceURI Namespace URI of the <code>QName</code>
* @param localPart local part of the <code>QName</code>
*
* @throws IllegalArgumentException When <code>localPart</code> is
* <code>null</code>
*
* @see #QName(String namespaceURI, String localPart, String
* prefix) QName(String namespaceURI, String localPart, String
* prefix)
*/
public QName(final String namespaceURI, final String localPart) {
this(namespaceURI, localPart, XMLConstants.DEFAULT_NS_PREFIX);
}
/**
* <p><code>QName</code> constructor specifying the Namespace URI,
* local part and prefix.</p>
*
* <p>If the Namespace URI is <code>null</code>, it is set to
* {@link javax.xml.XMLConstants#NULL_NS_URI
* XMLConstants.NULL_NS_URI}. This value represents no
* explicitly defined Namespace as defined by the <a
* href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">Namespaces
* in XML</a> specification. This action preserves compatible
* behavior with QName 1.0. Explicitly providing the {@link
* javax.xml.XMLConstants#NULL_NS_URI
* XMLConstants.NULL_NS_URI} value is the preferred coding
* style.</p>
*
* <p>If the local part is <code>null</code> an
* <code>IllegalArgumentException</code> is thrown.
* A local part of "" is allowed to preserve
* compatible behavior with QName 1.0. </p>
*
* <p>If the prefix is <code>null</code>, an
* <code>IllegalArgumentException</code> is thrown. Use {@link
* javax.xml.XMLConstants#DEFAULT_NS_PREFIX
* XMLConstants.DEFAULT_NS_PREFIX} to explicitly indicate that no
* prefix is present or the prefix is not relevant.</p>
*
* <p>The Namespace URI is not validated as a
* <a href="http://www.ietf.org/rfc/rfc2396.txt">URI reference</a>.
* The local part and prefix are not validated as a
* <a href="http://www.w3.org/TR/REC-xml-names/#NT-NCName">NCName</a>
* as specified in <a href="http://www.w3.org/TR/REC-xml-names/">Namespaces
* in XML</a>.</p>
*
* @param namespaceURI Namespace URI of the <code>QName</code>
* @param localPart local part of the <code>QName</code>
* @param prefix prefix of the <code>QName</code>
*
* @throws IllegalArgumentException When <code>localPart</code>
* or <code>prefix</code> is <code>null</code>
*/
public QName(String namespaceURI, String localPart, String prefix) {
// map null Namespace URI to default
// to preserve compatibility with QName 1.0
if (namespaceURI == null) {
this.namespaceURI = XMLConstants.NULL_NS_URI;
} else {
this.namespaceURI = namespaceURI;
}
// local part is required.
// "" is allowed to preserve compatibility with QName 1.0
if (localPart == null) {
throw new IllegalArgumentException(
"local part cannot be \"null\" when creating a QName");
}
this.localPart = localPart;
// prefix is required
if (prefix == null) {
throw new IllegalArgumentException(
"prefix cannot be \"null\" when creating a QName");
}
this.prefix = prefix;
}
/**
* <p><code>QName</code> constructor specifying the local part.</p>
*
* <p>If the local part is <code>null</code> an
* <code>IllegalArgumentException</code> is thrown.
* A local part of "" is allowed to preserve
* compatible behavior with QName 1.0. </p>
*
* <p>When using this constructor, the Namespace URI is set to
* {@link javax.xml.XMLConstants#NULL_NS_URI
* XMLConstants.NULL_NS_URI} and the prefix is set to {@link
* javax.xml.XMLConstants#DEFAULT_NS_PREFIX
* XMLConstants.DEFAULT_NS_PREFIX}.</p>
*
* <p><em>In an XML context, all Element and Attribute names exist
* in the context of a Namespace. Making this explicit during the
* construction of a <code>QName</code> helps prevent hard to
* diagnosis XML validity errors. The constructors {@link
* #QName(String namespaceURI, String localPart) QName(String
* namespaceURI, String localPart)} and
* {@link #QName(String namespaceURI, String localPart, String prefix)}
* are preferred.</em></p>
*
* <p>The local part is not validated as a
* <a href="http://www.w3.org/TR/REC-xml-names/#NT-NCName">NCName</a>
* as specified in <a href="http://www.w3.org/TR/REC-xml-names/">Namespaces
* in XML</a>.</p>
*
* @param localPart local part of the <code>QName</code>
*
* @throws IllegalArgumentException When <code>localPart</code> is
* <code>null</code>
*
* @see #QName(String namespaceURI, String localPart) QName(String
* namespaceURI, String localPart)
* @see #QName(String namespaceURI, String localPart, String
* prefix) QName(String namespaceURI, String localPart, String
* prefix)
*/
public QName(String localPart) {
this(
XMLConstants.NULL_NS_URI,
localPart,
XMLConstants.DEFAULT_NS_PREFIX);
}
/**
* <p>Get the Namespace URI of this <code>QName</code>.</p>
*
* @return Namespace URI of this <code>QName</code>
*/
public String getNamespaceURI() {
return namespaceURI;
}
/**
* <p>Get the local part of this <code>QName</code>.</p>
*
* @return local part of this <code>QName</code>
*/
public String getLocalPart() {
return localPart;
}
/**
* <p>Get the prefix of this <code>QName</code>.</p>
*
* <p>The prefix assigned to a <code>QName</code> might
* <strong><em>NOT</em></strong> be valid in a different
* context. For example, a <code>QName</code> may be assigned a
* prefix in the context of parsing a document but that prefix may
* be invalid in the context of a different document.</p>
*
* @return prefix of this <code>QName</code>
*/
public String getPrefix() {
return prefix;
}
/**
* <p>Test this <code>QName</code> for equality with another
* <code>Object</code>.</p>
*
* <p>If the <code>Object</code> to be tested is not a
* <code>QName</code> or is <code>null</code>, then this method
* returns <code>false</code>.</p>
*
* <p>Two <code>QName</code>s are considered equal if and only if
* both the Namespace URI and local part are equal. This method
* uses <code>String.equals()</code> to check equality of the
* Namespace URI and local part. The prefix is
* <strong><em>NOT</em></strong> used to determine equality.</p>
*
* <p>This method satisfies the general contract of {@link
* java.lang.Object#equals(Object) Object.equals(Object)}</p>
*
* @param objectToTest the <code>Object</code> to test for
* equality with this <code>QName</code>
* @return <code>true</code> if the given <code>Object</code> is
* equal to this <code>QName</code> else <code>false</code>
*/
public final boolean equals(Object objectToTest) {
if (objectToTest == null || !(objectToTest instanceof QName)) {
return false;
}
QName qName = (QName) objectToTest;
return namespaceURI.equals(qName.namespaceURI)
&& localPart.equals(qName.localPart);
}
/**
* <p>Generate the hash code for this <code>QName</code>.</p>
*
* <p>The hash code is calculated using both the Namespace URI and
* the local part of the <code>QName</code>. The prefix is
* <strong><em>NOT</em></strong> used to calculate the hash
* code.</p>
*
* <p>This method satisfies the general contract of {@link
* java.lang.Object#hashCode() Object.hashCode()}.</p>
*
* @return hash code for this <code>QName</code> <code>Object</code>
*/
public final int hashCode() {
return namespaceURI.hashCode() ^ localPart.hashCode();
}
/**
* <p><code>String</code> representation of this
* <code>QName</code>.</p>
*
* <p>The commonly accepted way of representing a <code>QName</code>
* as a <code>String</code> was
* <a href="http://jclark.com/xml/xmlns.htm">defined</a>
* by James Clark. Although this is not a <em>standard</em>
* specification, it is in common use, e.g. {@link
* javax.xml.transform.Transformer#setParameter(String name, Object value)}.
* This implementation represents a <code>QName</code> as:
* "{" + Namespace URI + "}" + local part. If the Namespace URI
* <code>.equals(XMLConstants.NULL_NS_URI)</code>, only the
* local part is returned. An appropriate use of this method is
* for debugging or logging for human consumption.</p>
*
* <p>Note the prefix value is <strong><em>NOT</em></strong>
* returned as part of the <code>String</code> representation.</p>
*
* <p>This method satisfies the general contract of {@link
* java.lang.Object#toString() Object.toString()}.</p>
*
* @return <code>String</code> representation of this <code>QName</code>
*/
public String toString() {
if (namespaceURI.equals(XMLConstants.NULL_NS_URI)) {
return localPart;
} else {
return "{" + namespaceURI + "}" + localPart;
}
}
/**
* <p><code>QName</code> derived from parsing the formatted
* <code>String</code>.</p>
*
* <p>If the <code>String</code> is <code>null</code> or does not conform to
* {@link #toString() QName.toString()} formatting, an
* <code>IllegalArgumentException</code> is thrown.</p>
*
* <p><em>The <code>String</code> <strong>MUST</strong> be in the
* form returned by {@link #toString() QName.toString()}.</em></p>
*
* <p>The commonly accepted way of representing a <code>QName</code>
* as a <code>String</code> was
* <a href="http://jclark.com/xml/xmlns.htm">defined</a>
* by James Clark. Although this is not a <em>standard</em>
* specification, it is in common use, e.g. {@link
* javax.xml.transform.Transformer#setParameter(String name, Object value)}.
* This implementation parses a <code>String</code> formatted
* as: "{" + Namespace URI + "}" + local part. If the Namespace
* URI <code>.equals(XMLConstants.NULL_NS_URI)</code>, only the
* local part should be provided.</p>
*
* <p>The prefix value <strong><em>CANNOT</em></strong> be
* represented in the <code>String</code> and will be set to
* {@link javax.xml.XMLConstants#DEFAULT_NS_PREFIX
* XMLConstants.DEFAULT_NS_PREFIX}.</p>
*
* <p>This method does not do full validation of the resulting
* <code>QName</code>.
* <p>The Namespace URI is not validated as a
* <a href="http://www.ietf.org/rfc/rfc2396.txt">URI reference</a>.
* The local part is not validated as a
* <a href="http://www.w3.org/TR/REC-xml-names/#NT-NCName">NCName</a>
* as specified in
* <a href="http://www.w3.org/TR/REC-xml-names/">Namespaces in XML</a>.</p>
*
* @param qNameAsString <code>String</code> representation
* of the <code>QName</code>
*
* @throws IllegalArgumentException When <code>qNameAsString</code> is
* <code>null</code> or malformed
*
* @return <code>QName</code> corresponding to the given <code>String</code>
* @see #toString() QName.toString()
*/
public static QName valueOf(String qNameAsString) {
// null is not valid
if (qNameAsString == null) {
throw new IllegalArgumentException(
"cannot create QName from \"null\" or \"\" String");
}
// "" local part is valid to preserve compatible behavior with QName 1.0
if (qNameAsString.length() == 0) {
return new QName(
XMLConstants.NULL_NS_URI,
qNameAsString,
XMLConstants.DEFAULT_NS_PREFIX);
}
// local part only?
if (qNameAsString.charAt(0) != '{') {
return new QName(
XMLConstants.NULL_NS_URI,
qNameAsString,
XMLConstants.DEFAULT_NS_PREFIX);
}
// Namespace URI improperly specified?
if (qNameAsString.startsWith("{" + XMLConstants.NULL_NS_URI + "}")) {
throw new IllegalArgumentException(
"Namespace URI .equals(XMLConstants.NULL_NS_URI), "
+ ".equals(\"" + XMLConstants.NULL_NS_URI + "\"), "
+ "only the local part, "
+ "\""
+ qNameAsString.substring(2 + XMLConstants.NULL_NS_URI.length())
+ "\", "
+ "should be provided.");
}
// Namespace URI and local part specified
int endOfNamespaceURI = qNameAsString.indexOf('}');
if (endOfNamespaceURI == -1) {
throw new IllegalArgumentException(
"cannot create QName from \""
+ qNameAsString
+ "\", missing closing \"}\"");
}
return new QName(
qNameAsString.substring(1, endOfNamespaceURI),
qNameAsString.substring(endOfNamespaceURI + 1),
XMLConstants.DEFAULT_NS_PREFIX);
}
}

View file

@ -0,0 +1,54 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation. Sun designates this
particular file as subject to the "Classpath" exception as provided
by Sun in the LICENSE file that accompanied this code.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
CA 95054 USA or visit www.sun.com if you need additional information or
have any questions.
-->
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>javax.xml.namespace</title>
<meta name="CVS"
content="$Id: package.html,v 1.2 2005/06/10 03:50:28 jeffsuttor Exp $" />
<meta name="AUTHOR"
content="Jeff.Suttor@Sun.com" />
</head>
<body>
<p>XML Namespace processing.</p>
<p>The following XML standards apply:</p>
<ul>
<li><a href="http://www.w3.org/TR/xmlschema-2/#QName">XML Schema Part2: Datatypes specification</a></li>
<li><a href="http://www.w3.org/TR/REC-xml-names/#ns-qualnames">Namespaces in XML</a></li>
<li><a href="http://www.w3.org/XML/xml-names-19990114-errata">Namespaces in XML Errata</a></li>
</ul>
</body>
</html>

View file

@ -0,0 +1,348 @@
/*
* Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.parsers;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.validation.Schema;
import org.w3c.dom.Document;
import org.w3c.dom.DOMImplementation;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Defines the API to obtain DOM Document instances from an XML
* document. Using this class, an application programmer can obtain a
* {@link Document} from XML.<p>
*
* An instance of this class can be obtained from the
* {@link DocumentBuilderFactory#newDocumentBuilder()} method. Once
* an instance of this class is obtained, XML can be parsed from a
* variety of input sources. These input sources are InputStreams,
* Files, URLs, and SAX InputSources.<p>
*
* Note that this class reuses several classes from the SAX API. This
* does not require that the implementor of the underlying DOM
* implementation use a SAX parser to parse XML document into a
* <code>Document</code>. It merely requires that the implementation
* communicate with the application using these existing APIs.
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
*/
public abstract class DocumentBuilder {
/** Protected constructor */
protected DocumentBuilder () {
}
/**
* <p>Reset this <code>DocumentBuilder</code> to its original configuration.</p>
*
* <p><code>DocumentBuilder</code> is reset to the same state as when it was created with
* {@link DocumentBuilderFactory#newDocumentBuilder()}.
* <code>reset()</code> is designed to allow the reuse of existing <code>DocumentBuilder</code>s
* thus saving resources associated with the creation of new <code>DocumentBuilder</code>s.</p>
*
* <p>The reset <code>DocumentBuilder</code> is not guaranteed to have the same {@link EntityResolver} or {@link ErrorHandler}
* <code>Object</code>s, e.g. {@link Object#equals(Object obj)}. It is guaranteed to have a functionally equal
* <code>EntityResolver</code> and <code>ErrorHandler</code>.</p>
*
* @throws UnsupportedOperationException When implementation does not
* override this method.
*
* @since 1.5
*/
public void reset() {
// implementors should override this method
throw new UnsupportedOperationException(
"This DocumentBuilder, \"" + this.getClass().getName() + "\", does not support the reset functionality."
+ " Specification \"" + this.getClass().getPackage().getSpecificationTitle() + "\""
+ " version \"" + this.getClass().getPackage().getSpecificationVersion() + "\""
);
}
/**
* Parse the content of the given <code>InputStream</code> as an XML
* document and return a new DOM {@link Document} object.
* An <code>IllegalArgumentException</code> is thrown if the
* <code>InputStream</code> is null.
*
* @param is InputStream containing the content to be parsed.
*
* @return <code>Document</code> result of parsing the
* <code>InputStream</code>
*
* @throws IOException If any IO errors occur.
* @throws SAXException If any parse errors occur.
* @throws IllegalArgumentException When <code>is</code> is <code>null</code>
*
* @see org.xml.sax.DocumentHandler
*/
public Document parse(InputStream is)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException("InputStream cannot be null");
}
InputSource in = new InputSource(is);
return parse(in);
}
/**
* Parse the content of the given <code>InputStream</code> as an
* XML document and return a new DOM {@link Document} object.
* An <code>IllegalArgumentException</code> is thrown if the
* <code>InputStream</code> is null.
*
* @param is InputStream containing the content to be parsed.
* @param systemId Provide a base for resolving relative URIs.
*
* @return A new DOM Document object.
*
* @throws IOException If any IO errors occur.
* @throws SAXException If any parse errors occur.
* @throws IllegalArgumentException When <code>is</code> is <code>null</code>
*
* @see org.xml.sax.DocumentHandler
*/
public Document parse(InputStream is, String systemId)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException("InputStream cannot be null");
}
InputSource in = new InputSource(is);
in.setSystemId(systemId);
return parse(in);
}
/**
* Parse the content of the given URI as an XML document
* and return a new DOM {@link Document} object.
* An <code>IllegalArgumentException</code> is thrown if the
* URI is <code>null</code> null.
*
* @param uri The location of the content to be parsed.
*
* @return A new DOM Document object.
*
* @throws IOException If any IO errors occur.
* @throws SAXException If any parse errors occur.
* @throws IllegalArgumentException When <code>uri</code> is <code>null</code>
*
* @see org.xml.sax.DocumentHandler
*/
public Document parse(String uri)
throws SAXException, IOException {
if (uri == null) {
throw new IllegalArgumentException("URI cannot be null");
}
InputSource in = new InputSource(uri);
return parse(in);
}
/**
* Parse the content of the given file as an XML document
* and return a new DOM {@link Document} object.
* An <code>IllegalArgumentException</code> is thrown if the
* <code>File</code> is <code>null</code> null.
*
* @param f The file containing the XML to parse.
*
* @throws IOException If any IO errors occur.
* @throws SAXException If any parse errors occur.
* @throws IllegalArgumentException When <code>f</code> is <code>null</code>
*
* @see org.xml.sax.DocumentHandler
* @return A new DOM Document object.
*/
public Document parse(File f) throws SAXException, IOException {
if (f == null) {
throw new IllegalArgumentException("File cannot be null");
}
//convert file to appropriate URI, f.toURI().toASCIIString()
//converts the URI to string as per rule specified in
//RFC 2396,
InputSource in = new InputSource(f.toURI().toASCIIString());
return parse(in);
}
/**
* Parse the content of the given input source as an XML document
* and return a new DOM {@link Document} object.
* An <code>IllegalArgumentException</code> is thrown if the
* <code>InputSource</code> is <code>null</code> null.
*
* @param is InputSource containing the content to be parsed.
*
* @return A new DOM Document object.
*
* @throws IOException If any IO errors occur.
* @throws SAXException If any parse errors occur.
* @throws IllegalArgumentException When <code>is</code> is <code>null</code>
*
* @see org.xml.sax.DocumentHandler
*/
public abstract Document parse(InputSource is)
throws SAXException, IOException;
/**
* Indicates whether or not this parser is configured to
* understand namespaces.
*
* @return true if this parser is configured to understand
* namespaces; false otherwise.
*/
public abstract boolean isNamespaceAware();
/**
* Indicates whether or not this parser is configured to
* validate XML documents.
*
* @return true if this parser is configured to validate
* XML documents; false otherwise.
*/
public abstract boolean isValidating();
/**
* Specify the {@link EntityResolver} to be used to resolve
* entities present in the XML document to be parsed. Setting
* this to <code>null</code> will result in the underlying
* implementation using it's own default implementation and
* behavior.
*
* @param er The <code>EntityResolver</code> to be used to resolve entities
* present in the XML document to be parsed.
*/
public abstract void setEntityResolver(EntityResolver er);
/**
* Specify the {@link ErrorHandler} to be used by the parser.
* Setting this to <code>null</code> will result in the underlying
* implementation using it's own default implementation and
* behavior.
*
* @param eh The <code>ErrorHandler</code> to be used by the parser.
*/
public abstract void setErrorHandler(ErrorHandler eh);
/**
* Obtain a new instance of a DOM {@link Document} object
* to build a DOM tree with.
*
* @return A new instance of a DOM Document object.
*/
public abstract Document newDocument();
/**
* Obtain an instance of a {@link DOMImplementation} object.
*
* @return A new instance of a <code>DOMImplementation</code>.
*/
public abstract DOMImplementation getDOMImplementation();
/** <p>Get current state of canonicalization.</p>
*
* @return current state canonicalization control
*/
/*
public boolean getCanonicalization() {
return canonicalState;
}
*/
/** <p>Get a reference to the the {@link Schema} being used by
* the XML processor.</p>
*
* <p>If no schema is being used, <code>null</code> is returned.</p>
*
* @return {@link Schema} being used or <code>null</code>
* if none in use
*
* @throws UnsupportedOperationException When implementation does not
* override this method
*
* @since 1.5
*/
public Schema getSchema() {
throw new UnsupportedOperationException(
"This parser does not support specification \""
+ this.getClass().getPackage().getSpecificationTitle()
+ "\" version \""
+ this.getClass().getPackage().getSpecificationVersion()
+ "\""
);
}
/**
* <p>Get the XInclude processing mode for this parser.</p>
*
* @return
* the return value of
* the {@link DocumentBuilderFactory#isXIncludeAware()}
* when this parser was created from factory.
*
* @throws UnsupportedOperationException When implementation does not
* override this method
*
* @since 1.5
*
* @see DocumentBuilderFactory#setXIncludeAware(boolean)
*/
public boolean isXIncludeAware() {
throw new UnsupportedOperationException(
"This parser does not support specification \""
+ this.getClass().getPackage().getSpecificationTitle()
+ "\" version \""
+ this.getClass().getPackage().getSpecificationVersion()
+ "\""
);
}
}

View file

@ -0,0 +1,615 @@
/*
* Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.parsers;
import javax.xml.validation.Schema;
/**
* Defines a factory API that enables applications to obtain a
* parser that produces DOM object trees from XML documents.
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @author <a href="mailto:Neeraj.Bajaj@sun.com">Neeraj Bajaj</a>
*
*/
public abstract class DocumentBuilderFactory {
/** The default property name according to the JAXP spec */
private static final String DEFAULT_PROPERTY_NAME = "javax.xml.parsers.DocumentBuilderFactory";
private boolean validating = false;
private boolean namespaceAware = false;
private boolean whitespace = false;
private boolean expandEntityRef = true;
private boolean ignoreComments = false;
private boolean coalescing = false;
private boolean canonicalState = false;
/**
* <p>Protected constructor to prevent instantiation.
* Use {@link #newInstance()}.</p>
*/
protected DocumentBuilderFactory () {
}
/**
* Obtain a new instance of a
* <code>DocumentBuilderFactory</code>. This static method creates
* a new factory instance.
* This method uses the following ordered lookup procedure to determine
* the <code>DocumentBuilderFactory</code> implementation class to
* load:
* <ul>
* <li>
* Use the <code>javax.xml.parsers.DocumentBuilderFactory</code> system
* property.
* </li>
* <li>
* Use the properties file "lib/jaxp.properties" in the JRE directory.
* This configuration file is in standard <code>java.util.Properties
* </code> format and contains the fully qualified name of the
* implementation class with the key being the system property defined
* above.
*
* The jaxp.properties file is read only once by the JAXP implementation
* and it's values are then cached for future use. If the file does not exist
* when the first attempt is made to read from it, no further attempts are
* made to check for its existence. It is not possible to change the value
* of any property in jaxp.properties after it has been read for the first time.
* </li>
* <li>
* Use the Services API (as detailed in the JAR specification), if
* available, to determine the classname. The Services API will look
* for a classname in the file
* <code>META-INF/services/javax.xml.parsers.DocumentBuilderFactory</code>
* in jars available to the runtime.
* </li>
* <li>
* Platform default <code>DocumentBuilderFactory</code> instance.
* </li>
* </ul>
*
* Once an application has obtained a reference to a
* <code>DocumentBuilderFactory</code> it can use the factory to
* configure and obtain parser instances.
*
*
* <h2>Tip for Trouble-shooting</h2>
* <p>Setting the <code>jaxp.debug</code> system property will cause
* this method to print a lot of debug messages
* to <code>System.err</code> about what it is doing and where it is looking at.</p>
*
* <p> If you have problems loading {@link DocumentBuilder}s, try:</p>
* <pre>
* java -Djaxp.debug=1 YourProgram ....
* </pre>
*
* @return New instance of a <code>DocumentBuilderFactory</code>
*
* @throws FactoryConfigurationError if the implementation is not
* available or cannot be instantiated.
*/
public static DocumentBuilderFactory newInstance() {
try {
return (DocumentBuilderFactory) FactoryFinder.find(
/* The default property name according to the JAXP spec */
"javax.xml.parsers.DocumentBuilderFactory",
/* The fallback implementation class name */
"com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
} catch (FactoryFinder.ConfigurationError e) {
throw new FactoryConfigurationError(e.getException(),
e.getMessage());
}
}
/**
* <p>Obtain a new instance of a <code>DocumentBuilderFactory</code> from class name.
* This function is useful when there are multiple providers in the classpath.
* It gives more control to the application as it can specify which provider
* should be loaded.</p>
*
* <p>Once an application has obtained a reference to a <code>DocumentBuilderFactory</code>
* it can use the factory to configure and obtain parser instances.</p>
*
*
* <h2>Tip for Trouble-shooting</h2>
* <p>Setting the <code>jaxp.debug</code> system property will cause
* this method to print a lot of debug messages
* to <code>System.err</code> about what it is doing and where it is looking at.</p>
*
* <p> If you have problems try:</p>
* <pre>
* java -Djaxp.debug=1 YourProgram ....
* </pre>
*
* @param factoryClassName fully qualified factory class name that provides implementation of <code>javax.xml.parsers.DocumentBuilderFactory</code>.
*
* @param classLoader <code>ClassLoader</code> used to load the factory class. If <code>null</code>
* current <code>Thread</code>'s context classLoader is used to load the factory class.
*
* @return New instance of a <code>DocumentBuilderFactory</code>
*
* @throws FactoryConfigurationError if <code>factoryClassName</code> is <code>null</code>, or
* the factory class cannot be loaded, instantiated.
*
* @see #newInstance()
*
* @since 1.6
*/
public static DocumentBuilderFactory newInstance(String factoryClassName, ClassLoader classLoader){
try {
//do not fallback if given classloader can't find the class, throw exception
return (DocumentBuilderFactory) FactoryFinder.newInstance(factoryClassName, classLoader, false);
} catch (FactoryFinder.ConfigurationError e) {
throw new FactoryConfigurationError(e.getException(),
e.getMessage());
}
}
/**
* Creates a new instance of a {@link javax.xml.parsers.DocumentBuilder}
* using the currently configured parameters.
*
* @return A new instance of a DocumentBuilder.
*
* @throws ParserConfigurationException if a DocumentBuilder
* cannot be created which satisfies the configuration requested.
*/
public abstract DocumentBuilder newDocumentBuilder()
throws ParserConfigurationException;
/**
* Specifies that the parser produced by this code will
* provide support for XML namespaces. By default the value of this is set
* to <code>false</code>
*
* @param awareness true if the parser produced will provide support
* for XML namespaces; false otherwise.
*/
public void setNamespaceAware(boolean awareness) {
this.namespaceAware = awareness;
}
/**
* Specifies that the parser produced by this code will
* validate documents as they are parsed. By default the value of this
* is set to <code>false</code>.
*
* <p>
* Note that "the validation" here means
* <a href="http://www.w3.org/TR/REC-xml#proc-types">a validating
* parser</a> as defined in the XML recommendation.
* In other words, it essentially just controls the DTD validation.
* (except the legacy two properties defined in JAXP 1.2.)
* </p>
*
* <p>
* To use modern schema languages such as W3C XML Schema or
* RELAX NG instead of DTD, you can configure your parser to be
* a non-validating parser by leaving the {@link #setValidating(boolean)}
* method <code>false</code>, then use the {@link #setSchema(Schema)}
* method to associate a schema to a parser.
* </p>
*
* @param validating true if the parser produced will validate documents
* as they are parsed; false otherwise.
*/
public void setValidating(boolean validating) {
this.validating = validating;
}
/**
* Specifies that the parsers created by this factory must eliminate
* whitespace in element content (sometimes known loosely as
* 'ignorable whitespace') when parsing XML documents (see XML Rec
* 2.10). Note that only whitespace which is directly contained within
* element content that has an element only content model (see XML
* Rec 3.2.1) will be eliminated. Due to reliance on the content model
* this setting requires the parser to be in validating mode. By default
* the value of this is set to <code>false</code>.
*
* @param whitespace true if the parser created must eliminate whitespace
* in the element content when parsing XML documents;
* false otherwise.
*/
public void setIgnoringElementContentWhitespace(boolean whitespace) {
this.whitespace = whitespace;
}
/**
* Specifies that the parser produced by this code will
* expand entity reference nodes. By default the value of this is set to
* <code>true</code>
*
* @param expandEntityRef true if the parser produced will expand entity
* reference nodes; false otherwise.
*/
public void setExpandEntityReferences(boolean expandEntityRef) {
this.expandEntityRef = expandEntityRef;
}
/**
* <p>Specifies that the parser produced by this code will
* ignore comments. By default the value of this is set to <code>false
* </code>.</p>
*
* @param ignoreComments <code>boolean</code> value to ignore comments during processing
*/
public void setIgnoringComments(boolean ignoreComments) {
this.ignoreComments = ignoreComments;
}
/**
* Specifies that the parser produced by this code will
* convert CDATA nodes to Text nodes and append it to the
* adjacent (if any) text node. By default the value of this is set to
* <code>false</code>
*
* @param coalescing true if the parser produced will convert CDATA nodes
* to Text nodes and append it to the adjacent (if any)
* text node; false otherwise.
*/
public void setCoalescing(boolean coalescing) {
this.coalescing = coalescing;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which are namespace aware.
*
* @return true if the factory is configured to produce parsers which
* are namespace aware; false otherwise.
*/
public boolean isNamespaceAware() {
return namespaceAware;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which validate the XML content during parse.
*
* @return true if the factory is configured to produce parsers
* which validate the XML content during parse; false otherwise.
*/
public boolean isValidating() {
return validating;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which ignore ignorable whitespace in element content.
*
* @return true if the factory is configured to produce parsers
* which ignore ignorable whitespace in element content;
* false otherwise.
*/
public boolean isIgnoringElementContentWhitespace() {
return whitespace;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which expand entity reference nodes.
*
* @return true if the factory is configured to produce parsers
* which expand entity reference nodes; false otherwise.
*/
public boolean isExpandEntityReferences() {
return expandEntityRef;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which ignores comments.
*
* @return true if the factory is configured to produce parsers
* which ignores comments; false otherwise.
*/
public boolean isIgnoringComments() {
return ignoreComments;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which converts CDATA nodes to Text nodes and appends it to
* the adjacent (if any) Text node.
*
* @return true if the factory is configured to produce parsers
* which converts CDATA nodes to Text nodes and appends it to
* the adjacent (if any) Text node; false otherwise.
*/
public boolean isCoalescing() {
return coalescing;
}
/**
* Allows the user to set specific attributes on the underlying
* implementation.
*
* @param name The name of the attribute.
* @param value The value of the attribute.
*
* @throws IllegalArgumentException thrown if the underlying
* implementation doesn't recognize the attribute.
*/
public abstract void setAttribute(String name, Object value)
throws IllegalArgumentException;
/**
* Allows the user to retrieve specific attributes on the underlying
* implementation.
*
* @param name The name of the attribute.
*
* @return value The value of the attribute.
*
* @throws IllegalArgumentException thrown if the underlying
* implementation doesn't recognize the attribute.
*/
public abstract Object getAttribute(String name)
throws IllegalArgumentException;
/**
* <p>Set a feature for this <code>DocumentBuilderFactory</code> and <code>DocumentBuilder</code>s created by this factory.</p>
*
* <p>
* Feature names are fully qualified {@link java.net.URI}s.
* Implementations may define their own features.
* A {@link ParserConfigurationException} is thrown if this <code>DocumentBuilderFactory</code> or the
* <code>DocumentBuilder</code>s it creates cannot support the feature.
* It is possible for a <code>DocumentBuilderFactory</code> to expose a feature value but be unable to change its state.
* </p>
*
* <p>
* All implementations are required to support the {@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} feature.
* When the feature is:</p>
* <ul>
* <li>
* <code>true</code>: the implementation will limit XML processing to conform to implementation limits.
* Examples include enity expansion limits and XML Schema constructs that would consume large amounts of resources.
* If XML processing is limited for security reasons, it will be reported via a call to the registered
* {@link org.xml.sax.ErrorHandler#fatalError(SAXParseException exception)}.
* See {@link DocumentBuilder#setErrorHandler(org.xml.sax.ErrorHandler errorHandler)}.
* </li>
* <li>
* <code>false</code>: the implementation will processing XML according to the XML specifications without
* regard to possible implementation limits.
* </li>
* </ul>
*
* @param name Feature name.
* @param value Is feature state <code>true</code> or <code>false</code>.
*
* @throws ParserConfigurationException if this <code>DocumentBuilderFactory</code> or the <code>DocumentBuilder</code>s
* it creates cannot support this feature.
* @throws NullPointerException If the <code>name</code> parameter is null.
*/
public abstract void setFeature(String name, boolean value)
throws ParserConfigurationException;
/**
* <p>Get the state of the named feature.</p>
*
* <p>
* Feature names are fully qualified {@link java.net.URI}s.
* Implementations may define their own features.
* An {@link ParserConfigurationException} is thrown if this <code>DocumentBuilderFactory</code> or the
* <code>DocumentBuilder</code>s it creates cannot support the feature.
* It is possible for an <code>DocumentBuilderFactory</code> to expose a feature value but be unable to change its state.
* </p>
*
* @param name Feature name.
*
* @return State of the named feature.
*
* @throws ParserConfigurationException if this <code>DocumentBuilderFactory</code>
* or the <code>DocumentBuilder</code>s it creates cannot support this feature.
*/
public abstract boolean getFeature(String name)
throws ParserConfigurationException;
/** <p>Get current state of canonicalization.</p>
*
* @return current state canonicalization control
*/
/*
public boolean getCanonicalization() {
return canonicalState;
}
*/
/**
* Gets the {@link Schema} object specified through
* the {@link #setSchema(Schema schema)} method.
*
* @return
* the {@link Schema} object that was last set through
* the {@link #setSchema(Schema)} method, or null
* if the method was not invoked since a {@link DocumentBuilderFactory}
* is created.
*
* @throws UnsupportedOperationException When implementation does not
* override this method.
*
* @since 1.5
*/
public Schema getSchema() {
throw new UnsupportedOperationException(
"This parser does not support specification \""
+ this.getClass().getPackage().getSpecificationTitle()
+ "\" version \""
+ this.getClass().getPackage().getSpecificationVersion()
+ "\""
);
}
/* <p>Set canonicalization control to <code>true</code> or
* </code>false</code>.</p>
*
* @param state of canonicalization
*/
/*
public void setCanonicalization(boolean state) {
canonicalState = state;
}
*/
/**
* <p>Set the {@link Schema} to be used by parsers created
* from this factory.
*
* <p>
* When a {@link Schema} is non-null, a parser will use a validator
* created from it to validate documents before it passes information
* down to the application.
*
* <p>When errors are found by the validator, the parser is responsible
* to report them to the user-specified {@link org.xml.sax.ErrorHandler}
* (or if the error handler is not set, ignore them or throw them), just
* like any other errors found by the parser itself.
* In other words, if the user-specified {@link org.xml.sax.ErrorHandler}
* is set, it must receive those errors, and if not, they must be
* treated according to the implementation specific
* default error handling rules.
*
* <p>
* A validator may modify the outcome of a parse (for example by
* adding default values that were missing in documents), and a parser
* is responsible to make sure that the application will receive
* modified DOM trees.
*
* <p>
* Initialy, null is set as the {@link Schema}.
*
* <p>
* This processing will take effect even if
* the {@link #isValidating()} method returns <code>false</code>.
*
* <p>It is an error to use
* the <code>http://java.sun.com/xml/jaxp/properties/schemaSource</code>
* property and/or the <code>http://java.sun.com/xml/jaxp/properties/schemaLanguage</code>
* property in conjunction with a {@link Schema} object.
* Such configuration will cause a {@link ParserConfigurationException}
* exception when the {@link #newDocumentBuilder()} is invoked.</p>
*
*
* <h4>Note for implmentors</h4>
*
* <p>
* A parser must be able to work with any {@link Schema}
* implementation. However, parsers and schemas are allowed
* to use implementation-specific custom mechanisms
* as long as they yield the result described in the specification.
* </p>
*
* @param schema <code>Schema</code> to use or <code>null</code>
* to remove a schema.
*
* @throws UnsupportedOperationException When implementation does not
* override this method.
*
* @since 1.5
*/
public void setSchema(Schema schema) {
throw new UnsupportedOperationException(
"This parser does not support specification \""
+ this.getClass().getPackage().getSpecificationTitle()
+ "\" version \""
+ this.getClass().getPackage().getSpecificationVersion()
+ "\""
);
}
/**
* <p>Set state of XInclude processing.</p>
*
* <p>If XInclude markup is found in the document instance, should it be
* processed as specified in <a href="http://www.w3.org/TR/xinclude/">
* XML Inclusions (XInclude) Version 1.0</a>.</p>
*
* <p>XInclude processing defaults to <code>false</code>.</p>
*
* @param state Set XInclude processing to <code>true</code> or
* <code>false</code>
*
* @throws UnsupportedOperationException When implementation does not
* override this method.
*
* @since 1.5
*/
public void setXIncludeAware(final boolean state) {
throw new UnsupportedOperationException(
"This parser does not support specification \""
+ this.getClass().getPackage().getSpecificationTitle()
+ "\" version \""
+ this.getClass().getPackage().getSpecificationVersion()
+ "\""
);
}
/**
* <p>Get state of XInclude processing.</p>
*
* @return current state of XInclude processing
*
* @throws UnsupportedOperationException When implementation does not
* override this method.
*
* @since 1.5
*/
public boolean isXIncludeAware() {
throw new UnsupportedOperationException(
"This parser does not support specification \""
+ this.getClass().getPackage().getSpecificationTitle()
+ "\" version \""
+ this.getClass().getPackage().getSpecificationVersion()
+ "\""
);
}
}

View file

@ -0,0 +1,125 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.parsers;
/**
* Thrown when a problem with configuration with the Parser Factories
* exists. This error will typically be thrown when the class of a
* parser factory specified in the system properties cannot be found
* or instantiated.
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
*/
public class FactoryConfigurationError extends Error {
/**
*<code>Exception</code> that represents the error.
*/
private Exception exception;
/**
* Create a new <code>FactoryConfigurationError</code> with no
* detail mesage.
*/
public FactoryConfigurationError() {
super();
this.exception = null;
}
/**
* Create a new <code>FactoryConfigurationError</code> with
* the <code>String </code> specified as an error message.
*
* @param msg The error message for the exception.
*/
public FactoryConfigurationError(String msg) {
super(msg);
this.exception = null;
}
/**
* Create a new <code>FactoryConfigurationError</code> with a
* given <code>Exception</code> base cause of the error.
*
* @param e The exception to be encapsulated in a
* FactoryConfigurationError.
*/
public FactoryConfigurationError(Exception e) {
super(e.toString());
this.exception = e;
}
/**
* Create a new <code>FactoryConfigurationError</code> with the
* given <code>Exception</code> base cause and detail message.
*
* @param e The exception to be encapsulated in a
* FactoryConfigurationError
* @param msg The detail message.
*/
public FactoryConfigurationError(Exception e, String msg) {
super(msg);
this.exception = e;
}
/**
* Return the message (if any) for this error . If there is no
* message for the exception and there is an encapsulated
* exception then the message of that exception, if it exists will be
* returned. Else the name of the encapsulated exception will be
* returned.
*
* @return The error message.
*/
public String getMessage () {
String message = super.getMessage ();
if (message == null && exception != null) {
return exception.getMessage();
}
return message;
}
/**
* Return the actual exception (if any) that caused this exception to
* be raised.
*
* @return The encapsulated exception, or null if there is none.
*/
public Exception getException () {
return exception;
}
}

View file

@ -0,0 +1,320 @@
/*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.parsers;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
/**
* <p>Implements pluggable Datatypes.</p>
*
* <p>This class is duplicated for each JAXP subpackage so keep it in
* sync. It is package private for secure class loading.</p>
*
* @author Santiago.PericasGeertsen@sun.com
*/
class FactoryFinder {
/**
* Internal debug flag.
*/
private static boolean debug = false;
/**
* Cache for properties in java.home/lib/jaxp.properties
*/
static Properties cacheProps = new Properties();
/**
* Flag indicating if properties from java.home/lib/jaxp.properties
* have been cached.
*/
static boolean firstTime = true;
/**
* Security support class use to check access control before
* getting certain system resources.
*/
static SecuritySupport ss = new SecuritySupport();
// Define system property "jaxp.debug" to get output
static {
// Use try/catch block to support applets, which throws
// SecurityException out of this code.
try {
String val = ss.getSystemProperty("jaxp.debug");
// Allow simply setting the prop to turn on debug
debug = val != null && !"false".equals(val);
}
catch (SecurityException se) {
debug = false;
}
}
private static void dPrint(String msg) {
if (debug) {
System.err.println("JAXP: " + msg);
}
}
/**
* Attempt to load a class using the class loader supplied. If that fails
* and fall back is enabled, the current (i.e. bootstrap) class loader is
* tried.
*
* If the class loader supplied is <code>null</code>, first try using the
* context class loader followed by the current (i.e. bootstrap) class
* loader.
*/
static private Class getProviderClass(String className, ClassLoader cl,
boolean doFallback) throws ClassNotFoundException
{
try {
if (cl == null) {
cl = ss.getContextClassLoader();
if (cl == null) {
throw new ClassNotFoundException();
}
else {
return cl.loadClass(className);
}
}
else {
return cl.loadClass(className);
}
}
catch (ClassNotFoundException e1) {
if (doFallback) {
// Use current class loader - should always be bootstrap CL
return Class.forName(className, true, FactoryFinder.class.getClassLoader());
}
else {
throw e1;
}
}
}
/**
* Create an instance of a class. Delegates to method
* <code>getProviderClass()</code> in order to load the class.
*
* @param className Name of the concrete class corresponding to the
* service provider
*
* @param cl ClassLoader to use to load the class, null means to use
* the bootstrap ClassLoader
*
* @param doFallback True if the current ClassLoader should be tried as
* a fallback if the class is not found using cl
*/
static Object newInstance(String className, ClassLoader cl, boolean doFallback)
throws ConfigurationError
{
try {
Class providerClass = getProviderClass(className, cl, doFallback);
Object instance = providerClass.newInstance();
if (debug) { // Extra check to avoid computing cl strings
dPrint("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);
}
}
/**
* Finds the implementation Class object in the specified order. Main
* entry point.
* @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.
*
* Package private so this code can be shared.
*/
static Object find(String factoryId, String fallbackClassName)
throws ConfigurationError
{
dPrint("find factoryId =" + factoryId);
// Use the system property first
try {
String systemProp = ss.getSystemProperty(factoryId);
if (systemProp != null) {
dPrint("found system property, value=" + systemProp);
return newInstance(systemProp, null, true);
}
}
catch (SecurityException se) {
if (debug) se.printStackTrace();
}
// try to read from $java.home/lib/jaxp.properties
try {
String factoryClassName = null;
if (firstTime) {
synchronized (cacheProps) {
if (firstTime) {
String configFile = ss.getSystemProperty("java.home") + File.separator +
"lib" + File.separator + "jaxp.properties";
File f = new File(configFile);
firstTime = false;
if (ss.doesFileExist(f)) {
dPrint("Read properties file "+f);
cacheProps.load(ss.getFileInputStream(f));
}
}
}
}
factoryClassName = cacheProps.getProperty(factoryId);
if (factoryClassName != null) {
dPrint("found in $java.home/jaxp.properties, value=" + factoryClassName);
return newInstance(factoryClassName, null, true);
}
}
catch (Exception ex) {
if (debug) ex.printStackTrace();
}
// 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);
}
dPrint("loaded from fallback value: " + fallbackClassName);
return newInstance(fallbackClassName, null, true);
}
/*
* 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
{
String serviceId = "META-INF/services/" + factoryId;
InputStream is = null;
// First try the Context ClassLoader
ClassLoader cl = ss.getContextClassLoader();
if (cl != null) {
is = ss.getResourceAsStream(cl, serviceId);
// If no provider found then try the current ClassLoader
if (is == null) {
cl = FactoryFinder.class.getClassLoader();
is = ss.getResourceAsStream(cl, serviceId);
}
} else {
// No Context ClassLoader, try the current ClassLoader
cl = FactoryFinder.class.getClassLoader();
is = ss.getResourceAsStream(cl, serviceId);
}
if (is == null) {
// No provider found
return null;
}
if (debug) { // Extra check to avoid computing cl strings
dPrint("found jar resource=" + serviceId + " using ClassLoader: " + cl);
}
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
}
catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is));
}
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)) {
dPrint("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;
}
static class ConfigurationError extends Error {
private Exception exception;
/**
* Construct a new instance with the specified detail string and
* exception.
*/
ConfigurationError(String msg, Exception x) {
super(msg);
this.exception = x;
}
Exception getException() {
return exception;
}
}
}

View file

@ -0,0 +1,56 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.parsers;
/**
* Indicates a serious configuration error.
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
*/
public class ParserConfigurationException extends Exception {
/**
* Create a new <code>ParserConfigurationException</code> with no
* detail mesage.
*/
public ParserConfigurationException() {
super();
}
/**
* Create a new <code>ParserConfigurationException</code> with
* the <code>String</code> specified as an error message.
*
* @param msg The error message for the exception.
*/
public ParserConfigurationException(String msg) {
super(msg);
}
}

View file

@ -0,0 +1,532 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.parsers;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.validation.Schema;
import org.xml.sax.HandlerBase;
import org.xml.sax.InputSource;
import org.xml.sax.Parser;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
/**
* Defines the API that wraps an {@link org.xml.sax.XMLReader}
* implementation class. In JAXP 1.0, this class wrapped the
* {@link org.xml.sax.Parser} interface, however this interface was
* replaced by the {@link org.xml.sax.XMLReader}. For ease
* of transition, this class continues to support the same name
* and interface as well as supporting new methods.
*
* An instance of this class can be obtained from the
* {@link javax.xml.parsers.SAXParserFactory#newSAXParser()} method.
* Once an instance of this class is obtained, XML can be parsed from
* a variety of input sources. These input sources are InputStreams,
* Files, URLs, and SAX InputSources.<p>
*
* This static method creates a new factory instance based
* on a system property setting or uses the platform default
* if no property has been defined.<p>
*
* The system property that controls which Factory implementation
* to create is named <code>&quot;javax.xml.parsers.SAXParserFactory&quot;</code>.
* This property names a class that is a concrete subclass of this
* abstract class. If no property is defined, a platform default
* will be used.</p>
*
* As the content is parsed by the underlying parser, methods of the
* given {@link org.xml.sax.HandlerBase} or the
* {@link org.xml.sax.helpers.DefaultHandler} are called.<p>
*
* Implementors of this class which wrap an underlaying implementation
* can consider using the {@link org.xml.sax.helpers.ParserAdapter}
* class to initially adapt their SAX1 implementation to work under
* this revised class.
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
*/
public abstract class SAXParser {
/**
* <p>Protected constructor to prevent instaniation.
* Use {@link javax.xml.parsers.SAXParserFactory#newSAXParser()}.</p>
*/
protected SAXParser () {
}
/**
* <p>Reset this <code>SAXParser</code> to its original configuration.</p>
*
* <p><code>SAXParser</code> is reset to the same state as when it was created with
* {@link SAXParserFactory#newSAXParser()}.
* <code>reset()</code> is designed to allow the reuse of existing <code>SAXParser</code>s
* thus saving resources associated with the creation of new <code>SAXParser</code>s.</p>
*
* <p>The reset <code>SAXParser</code> is not guaranteed to have the same {@link Schema}
* <code>Object</code>, e.g. {@link Object#equals(Object obj)}. It is guaranteed to have a functionally equal
* <code>Schema</code>.</p>
*
* @throws UnsupportedOperationException When Implementations do not
* override this method
*
* @since 1.5
*/
public void reset() {
// implementors should override this method
throw new UnsupportedOperationException(
"This SAXParser, \"" + this.getClass().getName() + "\", does not support the reset functionality."
+ " Specification \"" + this.getClass().getPackage().getSpecificationTitle() + "\""
+ " version \"" + this.getClass().getPackage().getSpecificationVersion() + "\""
);
}
/**
* <p>Parse the content of the given {@link java.io.InputStream}
* instance as XML using the specified {@link org.xml.sax.HandlerBase}.
* <i> Use of the DefaultHandler version of this method is recommended as
* the HandlerBase class has been deprecated in SAX 2.0</i>.</p>
*
* @param is InputStream containing the content to be parsed.
* @param hb The SAX HandlerBase to use.
*
* @throws IllegalArgumentException If the given InputStream is null.
* @throws SAXException If parse produces a SAX error.
* @throws IOException If an IO error occurs interacting with the
* <code>InputStream</code>.
*
* @see org.xml.sax.DocumentHandler
*/
public void parse(InputStream is, HandlerBase hb)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException("InputStream cannot be null");
}
InputSource input = new InputSource(is);
this.parse(input, hb);
}
/**
* <p>Parse the content of the given {@link java.io.InputStream}
* instance as XML using the specified {@link org.xml.sax.HandlerBase}.
* <i> Use of the DefaultHandler version of this method is recommended as
* the HandlerBase class has been deprecated in SAX 2.0</i>.</p>
*
* @param is InputStream containing the content to be parsed.
* @param hb The SAX HandlerBase to use.
* @param systemId The systemId which is needed for resolving relative URIs.
*
* @throws IllegalArgumentException If the given <code>InputStream</code> is
* <code>null</code>.
* @throws IOException If any IO error occurs interacting with the
* <code>InputStream</code>.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler version of this method instead.
*/
public void parse(
InputStream is,
HandlerBase hb,
String systemId)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException("InputStream cannot be null");
}
InputSource input = new InputSource(is);
input.setSystemId(systemId);
this.parse(input, hb);
}
/**
* Parse the content of the given {@link java.io.InputStream}
* instance as XML using the specified
* {@link org.xml.sax.helpers.DefaultHandler}.
*
* @param is InputStream containing the content to be parsed.
* @param dh The SAX DefaultHandler to use.
*
* @throws IllegalArgumentException If the given InputStream is null.
* @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler
*/
public void parse(InputStream is, DefaultHandler dh)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException("InputStream cannot be null");
}
InputSource input = new InputSource(is);
this.parse(input, dh);
}
/**
* Parse the content of the given {@link java.io.InputStream}
* instance as XML using the specified
* {@link org.xml.sax.helpers.DefaultHandler}.
*
* @param is InputStream containing the content to be parsed.
* @param dh The SAX DefaultHandler to use.
* @param systemId The systemId which is needed for resolving relative URIs.
*
* @throws IllegalArgumentException If the given InputStream is null.
* @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler version of this method instead.
*/
public void parse(
InputStream is,
DefaultHandler dh,
String systemId)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException("InputStream cannot be null");
}
InputSource input = new InputSource(is);
input.setSystemId(systemId);
this.parse(input, dh);
}
/**
* Parse the content described by the giving Uniform Resource
* Identifier (URI) as XML using the specified
* {@link org.xml.sax.HandlerBase}.
* <i> Use of the DefaultHandler version of this method is recommended as
* the <code>HandlerBase</code> class has been deprecated in SAX 2.0</i>
*
* @param uri The location of the content to be parsed.
* @param hb The SAX HandlerBase to use.
*
* @throws IllegalArgumentException If the uri is null.
* @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler
*/
public void parse(String uri, HandlerBase hb)
throws SAXException, IOException {
if (uri == null) {
throw new IllegalArgumentException("uri cannot be null");
}
InputSource input = new InputSource(uri);
this.parse(input, hb);
}
/**
* Parse the content described by the giving Uniform Resource
* Identifier (URI) as XML using the specified
* {@link org.xml.sax.helpers.DefaultHandler}.
*
* @param uri The location of the content to be parsed.
* @param dh The SAX DefaultHandler to use.
*
* @throws IllegalArgumentException If the uri is null.
* @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler
*/
public void parse(String uri, DefaultHandler dh)
throws SAXException, IOException {
if (uri == null) {
throw new IllegalArgumentException("uri cannot be null");
}
InputSource input = new InputSource(uri);
this.parse(input, dh);
}
/**
* Parse the content of the file specified as XML using the
* specified {@link org.xml.sax.HandlerBase}.
* <i> Use of the DefaultHandler version of this method is recommended as
* the HandlerBase class has been deprecated in SAX 2.0</i>
*
* @param f The file containing the XML to parse
* @param hb The SAX HandlerBase to use.
*
* @throws IllegalArgumentException If the File object is null.
* @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler
*/
public void parse(File f, HandlerBase hb)
throws SAXException, IOException {
if (f == null) {
throw new IllegalArgumentException("File cannot be null");
}
//convert file to appropriate URI, f.toURI().toASCIIString()
//converts the URI to string as per rule specified in
//RFC 2396,
InputSource input = new InputSource(f.toURI().toASCIIString());
this.parse(input, hb);
}
/**
* Parse the content of the file specified as XML using the
* specified {@link org.xml.sax.helpers.DefaultHandler}.
*
* @param f The file containing the XML to parse
* @param dh The SAX DefaultHandler to use.
*
* @throws IllegalArgumentException If the File object is null.
* @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler
*/
public void parse(File f, DefaultHandler dh)
throws SAXException, IOException {
if (f == null) {
throw new IllegalArgumentException("File cannot be null");
}
//convert file to appropriate URI, f.toURI().toASCIIString()
//converts the URI to string as per rule specified in
//RFC 2396,
InputSource input = new InputSource(f.toURI().toASCIIString());
this.parse(input, dh);
}
/**
* Parse the content given {@link org.xml.sax.InputSource}
* as XML using the specified
* {@link org.xml.sax.HandlerBase}.
* <i> Use of the DefaultHandler version of this method is recommended as
* the HandlerBase class has been deprecated in SAX 2.0</i>
*
* @param is The InputSource containing the content to be parsed.
* @param hb The SAX HandlerBase to use.
*
* @throws IllegalArgumentException If the <code>InputSource</code> object
* is <code>null</code>.
* @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler
*/
public void parse(InputSource is, HandlerBase hb)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException("InputSource cannot be null");
}
Parser parser = this.getParser();
if (hb != null) {
parser.setDocumentHandler(hb);
parser.setEntityResolver(hb);
parser.setErrorHandler(hb);
parser.setDTDHandler(hb);
}
parser.parse(is);
}
/**
* Parse the content given {@link org.xml.sax.InputSource}
* as XML using the specified
* {@link org.xml.sax.helpers.DefaultHandler}.
*
* @param is The InputSource containing the content to be parsed.
* @param dh The SAX DefaultHandler to use.
*
* @throws IllegalArgumentException If the <code>InputSource</code> object
* is <code>null</code>.
* @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler
*/
public void parse(InputSource is, DefaultHandler dh)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException("InputSource cannot be null");
}
XMLReader reader = this.getXMLReader();
if (dh != null) {
reader.setContentHandler(dh);
reader.setEntityResolver(dh);
reader.setErrorHandler(dh);
reader.setDTDHandler(dh);
}
reader.parse(is);
}
/**
* Returns the SAX parser that is encapsultated by the
* implementation of this class.
*
* @return The SAX parser that is encapsultated by the
* implementation of this class.
*
* @throws SAXException If any SAX errors occur during processing.
*/
public abstract org.xml.sax.Parser getParser() throws SAXException;
/**
* Returns the {@link org.xml.sax.XMLReader} that is encapsulated by the
* implementation of this class.
*
* @return The XMLReader that is encapsulated by the
* implementation of this class.
*
* @throws SAXException If any SAX errors occur during processing.
*/
public abstract org.xml.sax.XMLReader getXMLReader() throws SAXException;
/**
* Indicates whether or not this parser is configured to
* understand namespaces.
*
* @return true if this parser is configured to
* understand namespaces; false otherwise.
*/
public abstract boolean isNamespaceAware();
/**
* Indicates whether or not this parser is configured to
* validate XML documents.
*
* @return true if this parser is configured to
* validate XML documents; false otherwise.
*/
public abstract boolean isValidating();
/**
* <p>Sets the particular property in the underlying implementation of
* {@link org.xml.sax.XMLReader}.
* A list of the core features and properties can be found at
* <a href="http://sax.sourceforge.net/?selected=get-set">
* http://sax.sourceforge.net/?selected=get-set</a>.</p>
*
* @param name The name of the property to be set.
* @param value The value of the property to be set.
*
* @throws SAXNotRecognizedException When the underlying XMLReader does
* not recognize the property name.
* @throws SAXNotSupportedException When the underlying XMLReader
* recognizes the property name but doesn't support the property.
*
* @see org.xml.sax.XMLReader#setProperty
*/
public abstract void setProperty(String name, Object value)
throws SAXNotRecognizedException, SAXNotSupportedException;
/**
* <p>Returns the particular property requested for in the underlying
* implementation of {@link org.xml.sax.XMLReader}.</p>
*
* @param name The name of the property to be retrieved.
* @return Value of the requested property.
*
* @throws SAXNotRecognizedException When the underlying XMLReader does
* not recognize the property name.
* @throws SAXNotSupportedException When the underlying XMLReader
* recognizes the property name but doesn't support the property.
*
* @see org.xml.sax.XMLReader#getProperty
*/
public abstract Object getProperty(String name)
throws SAXNotRecognizedException, SAXNotSupportedException;
/** <p>Get current state of canonicalization.</p>
*
* @return current state canonicalization control
*/
/*
public boolean getCanonicalization() {
return canonicalState;
}
*/
/** <p>Get a reference to the the {@link Schema} being used by
* the XML processor.</p>
*
* <p>If no schema is being used, <code>null</code> is returned.</p>
*
* @return {@link Schema} being used or <code>null</code>
* if none in use
*
* @throws UnsupportedOperationException When implementation does not
* override this method
*
* @since 1.5
*/
public Schema getSchema() {
throw new UnsupportedOperationException(
"This parser does not support specification \""
+ this.getClass().getPackage().getSpecificationTitle()
+ "\" version \""
+ this.getClass().getPackage().getSpecificationVersion()
+ "\""
);
}
/**
* <p>Get the XInclude processing mode for this parser.</p>
*
* @return
* the return value of
* the {@link SAXParserFactory#isXIncludeAware()}
* when this parser was created from factory.
*
* @throws UnsupportedOperationException When implementation does not
* override this method
*
* @since 1.5
*
* @see SAXParserFactory#setXIncludeAware(boolean)
*/
public boolean isXIncludeAware() {
throw new UnsupportedOperationException(
"This parser does not support specification \""
+ this.getClass().getPackage().getSpecificationTitle()
+ "\" version \""
+ this.getClass().getPackage().getSpecificationVersion()
+ "\""
);
}
}

View file

@ -0,0 +1,473 @@
/*
* Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.parsers;
import javax.xml.validation.Schema;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
/**
* Defines a factory API that enables applications to configure and
* obtain a SAX based parser to parse XML documents.
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @author <a href="mailto:Neeraj.Bajaj@sun.com">Neeraj Bajaj</a>
*
*
*/
public abstract class SAXParserFactory {
/** The default property name according to the JAXP spec */
private static final String DEFAULT_PROPERTY_NAME = "javax.xml.parsers.SAXParserFactory";
/**
* <p>Should Parsers be validating?</p>
*/
private boolean validating = false;
/**
* <p>Should Parsers be namespace aware?</p>
*/
private boolean namespaceAware = false;
/**
* <p>Protected constructor to force use of {@link #newInstance()}.</p>
*/
protected SAXParserFactory () {
}
/**
* Obtain a new instance of a <code>SAXParserFactory</code>. This
* static method creates a new factory instance
* This method uses the following ordered lookup procedure to determine
* the <code>SAXParserFactory</code> implementation class to
* load:
* <ul>
* <li>
* Use the <code>javax.xml.parsers.SAXParserFactory</code> system
* property.
* </li>
* <li>
* Use the properties file "lib/jaxp.properties" in the JRE directory.
* This configuration file is in standard <code>java.util.Properties
* </code> format and contains the fully qualified name of the
* implementation class with the key being the system property defined
* above.
*
* The jaxp.properties file is read only once by the JAXP implementation
* and it's values are then cached for future use. If the file does not exist
* when the first attempt is made to read from it, no further attempts are
* made to check for its existence. It is not possible to change the value
* of any property in jaxp.properties after it has been read for the first time.
* </li>
* <li>
* Use the Services API (as detailed in the JAR specification), if
* available, to determine the classname. The Services API will look
* for a classname in the file
* <code>META-INF/services/javax.xml.parsers.SAXParserFactory</code>
* in jars available to the runtime.
* </li>
* <li>
* Platform default <code>SAXParserFactory</code> instance.
* </li>
* </ul>
*
* Once an application has obtained a reference to a
* <code>SAXParserFactory</code> it can use the factory to
* configure and obtain parser instances.
*
*
*
* <h2>Tip for Trouble-shooting</h2>
* <p>Setting the <code>jaxp.debug</code> system property will cause
* this method to print a lot of debug messages
* to <code>System.err</code> about what it is doing and where it is looking at.</p>
*
* <p> If you have problems loading {@link DocumentBuilder}s, try:</p>
* <pre>
* java -Djaxp.debug=1 YourProgram ....
* </pre>
*
*
* @return A new instance of a SAXParserFactory.
*
* @throws FactoryConfigurationError if the implementation is
* not available or cannot be instantiated.
*/
public static SAXParserFactory newInstance() {
try {
return (SAXParserFactory) FactoryFinder.find(
/* The default property name according to the JAXP spec */
"javax.xml.parsers.SAXParserFactory",
/* The fallback implementation class name */
"com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
} catch (FactoryFinder.ConfigurationError e) {
throw new FactoryConfigurationError(e.getException(),
e.getMessage());
}
}
/**
* <p>Obtain a new instance of a <code>SAXParserFactory</code> from class name.
* This function is useful when there are multiple providers in the classpath.
* It gives more control to the application as it can specify which provider
* should be loaded.</p>
*
* <p>Once an application has obtained a reference to a <code>SAXParserFactory</code>
* it can use the factory to configure and obtain parser instances.</p>
*
*
* <h2>Tip for Trouble-shooting</h2>
* <p>Setting the <code>jaxp.debug</code> system property will cause
* this method to print a lot of debug messages
* to <code>System.err</code> about what it is doing and where it is looking at.</p>
*
* <p> If you have problems, try:</p>
* <pre>
* java -Djaxp.debug=1 YourProgram ....
* </pre>
*
* @param factoryClassName fully qualified factory class name that provides implementation of <code>javax.xml.parsers.SAXParserFactory</code>.
*
* @param classLoader <code>ClassLoader</code> used to load the factory class. If <code>null</code>
* current <code>Thread</code>'s context classLoader is used to load the factory class.
*
* @return New instance of a <code>SAXParserFactory</code>
*
* @throws FactoryConfigurationError if <code>factoryClassName</code> is <code>null</code>, or
* the factory class cannot be loaded, instantiated.
*
* @see #newInstance()
*
* @since 1.6
*/
public static SAXParserFactory newInstance(String factoryClassName, ClassLoader classLoader){
try {
//do not fallback if given classloader can't find the class, throw exception
return (SAXParserFactory) FactoryFinder.newInstance(factoryClassName, classLoader, false);
} catch (FactoryFinder.ConfigurationError e) {
throw new FactoryConfigurationError(e.getException(),
e.getMessage());
}
}
/**
* <p>Creates a new instance of a SAXParser using the currently
* configured factory parameters.</p>
*
* @return A new instance of a SAXParser.
*
* @throws ParserConfigurationException if a parser cannot
* be created which satisfies the requested configuration.
* @throws SAXException for SAX errors.
*/
public abstract SAXParser newSAXParser()
throws ParserConfigurationException, SAXException;
/**
* Specifies that the parser produced by this code will
* provide support for XML namespaces. By default the value of this is set
* to <code>false</code>.
*
* @param awareness true if the parser produced by this code will
* provide support for XML namespaces; false otherwise.
*/
public void setNamespaceAware(boolean awareness) {
this.namespaceAware = awareness;
}
/**
* Specifies that the parser produced by this code will
* validate documents as they are parsed. By default the value of this is
* set to <code>false</code>.
*
* <p>
* Note that "the validation" here means
* <a href="http://www.w3.org/TR/REC-xml#proc-types">a validating
* parser</a> as defined in the XML recommendation.
* In other words, it essentially just controls the DTD validation.
* (except the legacy two properties defined in JAXP 1.2.)
* </p>
*
* <p>
* To use modern schema languages such as W3C XML Schema or
* RELAX NG instead of DTD, you can configure your parser to be
* a non-validating parser by leaving the {@link #setValidating(boolean)}
* method <code>false</code>, then use the {@link #setSchema(Schema)}
* method to associate a schema to a parser.
* </p>
*
* @param validating true if the parser produced by this code will
* validate documents as they are parsed; false otherwise.
*/
public void setValidating(boolean validating) {
this.validating = validating;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which are namespace aware.
*
* @return true if the factory is configured to produce
* parsers which are namespace aware; false otherwise.
*/
public boolean isNamespaceAware() {
return namespaceAware;
}
/**
* Indicates whether or not the factory is configured to produce
* parsers which validate the XML content during parse.
*
* @return true if the factory is configured to produce parsers which validate
* the XML content during parse; false otherwise.
*/
public boolean isValidating() {
return validating;
}
/**
*
* <p>Sets the particular feature in the underlying implementation of
* org.xml.sax.XMLReader.
* A list of the core features and properties can be found at
* <a href="http://www.saxproject.org/">http://www.saxproject.org/</a></p>
*
* <p>All implementations are required to support the {@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} feature.
* When the feature is</p>
* <ul>
* <li>
* <code>true</code>: the implementation will limit XML processing to conform to implementation limits.
* Examples include enity expansion limits and XML Schema constructs that would consume large amounts of resources.
* If XML processing is limited for security reasons, it will be reported via a call to the registered
* {@link org.xml.sax.ErrorHandler#fatalError(SAXParseException exception)}.
* See {@link SAXParser} <code>parse</code> methods for handler specification.
* </li>
* <li>
* When the feature is <code>false</code>, the implementation will processing XML according to the XML specifications without
* regard to possible implementation limits.
* </li>
* </ul>
*
* @param name The name of the feature to be set.
* @param value The value of the feature to be set.
*
* @throws ParserConfigurationException if a parser cannot
* be created which satisfies the requested configuration.
* @throws SAXNotRecognizedException When the underlying XMLReader does
* not recognize the property name.
* @throws SAXNotSupportedException When the underlying XMLReader
* recognizes the property name but doesn't support the
* property.
* @throws NullPointerException If the <code>name</code> parameter is null.
*
* @see org.xml.sax.XMLReader#setFeature
*/
public abstract void setFeature(String name, boolean value)
throws ParserConfigurationException, SAXNotRecognizedException,
SAXNotSupportedException;
/**
*
* <p>Returns the particular property requested for in the underlying
* implementation of org.xml.sax.XMLReader.</p>
*
* @param name The name of the property to be retrieved.
*
* @return Value of the requested property.
*
* @throws ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
* @throws SAXNotRecognizedException When the underlying XMLReader does not recognize the property name.
* @throws SAXNotSupportedException When the underlying XMLReader recognizes the property name but doesn't support the property.
*
* @see org.xml.sax.XMLReader#getProperty
*/
public abstract boolean getFeature(String name)
throws ParserConfigurationException, SAXNotRecognizedException,
SAXNotSupportedException;
/* <p>Get current state of canonicalization.</p>
*
* @return current state canonicalization control
*/
/*
public boolean getCanonicalization() {
return canonicalState;
}
*/
/**
* Gets the {@link Schema} object specified through
* the {@link #setSchema(Schema schema)} method.
*
*
* @throws UnsupportedOperationException When implementation does not
* override this method
*
* @return
* the {@link Schema} object that was last set through
* the {@link #setSchema(Schema)} method, or null
* if the method was not invoked since a {@link SAXParserFactory}
* is created.
*
* @since 1.5
*/
public Schema getSchema() {
throw new UnsupportedOperationException(
"This parser does not support specification \""
+ this.getClass().getPackage().getSpecificationTitle()
+ "\" version \""
+ this.getClass().getPackage().getSpecificationVersion()
+ "\""
);
}
/** <p>Set canonicalization control to <code>true</code> or
* </code>false</code>.</p>
*
* @param state of canonicalization
*/
/*
public void setCanonicalization(boolean state) {
canonicalState = state;
}
*/
/**
* <p>Set the {@link Schema} to be used by parsers created
* from this factory.</p>
*
* <p>When a {@link Schema} is non-null, a parser will use a validator
* created from it to validate documents before it passes information
* down to the application.</p>
*
* <p>When warnings/errors/fatal errors are found by the validator, the parser must
* handle them as if those errors were found by the parser itself.
* In other words, if the user-specified {@link org.xml.sax.ErrorHandler}
* is set, it must receive those errors, and if not, they must be
* treated according to the implementation specific
* default error handling rules.
*
* <p>A validator may modify the SAX event stream (for example by
* adding default values that were missing in documents), and a parser
* is responsible to make sure that the application will receive
* those modified event stream.</p>
*
* <p>Initialy, <code>null</code> is set as the {@link Schema}.</p>
*
* <p>This processing will take effect even if
* the {@link #isValidating()} method returns <code>false</code>.
*
* <p>It is an error to use
* the <code>http://java.sun.com/xml/jaxp/properties/schemaSource</code>
* property and/or the <code>http://java.sun.com/xml/jaxp/properties/schemaLanguage</code>
* property in conjunction with a non-null {@link Schema} object.
* Such configuration will cause a {@link SAXException}
* exception when those properties are set on a {@link SAXParser}.</p>
*
* <h4>Note for implmentors</h4>
* <p>
* A parser must be able to work with any {@link Schema}
* implementation. However, parsers and schemas are allowed
* to use implementation-specific custom mechanisms
* as long as they yield the result described in the specification.
* </p>
*
* @param schema <code>Schema</code> to use, <code>null</code> to remove a schema.
*
* @throws UnsupportedOperationException When implementation does not
* override this method
*
* @since 1.5
*/
public void setSchema(Schema schema) {
throw new UnsupportedOperationException(
"This parser does not support specification \""
+ this.getClass().getPackage().getSpecificationTitle()
+ "\" version \""
+ this.getClass().getPackage().getSpecificationVersion()
+ "\""
);
}
/**
* <p>Set state of XInclude processing.</p>
*
* <p>If XInclude markup is found in the document instance, should it be
* processed as specified in <a href="http://www.w3.org/TR/xinclude/">
* XML Inclusions (XInclude) Version 1.0</a>.</p>
*
* <p>XInclude processing defaults to <code>false</code>.</p>
*
* @param state Set XInclude processing to <code>true</code> or
* <code>false</code>
*
* @throws UnsupportedOperationException When implementation does not
* override this method
*
* @since 1.5
*/
public void setXIncludeAware(final boolean state) {
throw new UnsupportedOperationException(
"This parser does not support specification \""
+ this.getClass().getPackage().getSpecificationTitle()
+ "\" version \""
+ this.getClass().getPackage().getSpecificationVersion()
+ "\""
);
}
/**
* <p>Get state of XInclude processing.</p>
*
* @return current state of XInclude processing
*
* @throws UnsupportedOperationException When implementation does not
* override this method
*
* @since 1.5
*/
public boolean isXIncludeAware() {
throw new UnsupportedOperationException(
"This parser does not support specification \""
+ this.getClass().getPackage().getSpecificationTitle()
+ "\" version \""
+ this.getClass().getPackage().getSpecificationVersion()
+ "\""
);
}
}

View file

@ -0,0 +1,110 @@
/*
* Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.parsers;
import java.security.*;
import java.net.*;
import java.io.*;
import java.util.*;
/**
* 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 SecuritySupport {
ClassLoader getContextClassLoader() throws SecurityException{
return (ClassLoader)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ClassLoader cl = null;
//try {
cl = Thread.currentThread().getContextClassLoader();
//} catch (SecurityException ex) { }
if (cl == null)
cl = ClassLoader.getSystemClassLoader();
return cl;
}
});
}
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 doesFileExist(final File f) {
return ((Boolean)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return new Boolean(f.exists());
}
})).booleanValue();
}
}

View file

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation. Sun designates this
particular file as subject to the "Classpath" exception as provided
by Sun in the LICENSE file that accompanied this code.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
CA 95054 USA or visit www.sun.com if you need additional information or
have any questions.
-->
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>javax.xml.parsers</title>
<meta name="CVS"
content="$Id: package.html,v 1.2 2005/06/10 03:50:29 jeffsuttor Exp $" />
<meta name="AUTHOR"
content="Jeff.Suttor@Sun.com" />
</head>
<body>
<p>
Provides classes allowing the processing of XML documents. Two types
of plugable parsers are supported:
</p>
<ul>
<li>SAX (Simple API for XML)</li>
<li>DOM (Document Object Model)</li>
</ul>
</body>
</html>

View file

@ -0,0 +1,47 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
import javax.xml.stream.events.XMLEvent;
/**
* This interface declares a simple filter interface that one can
* create to filter XMLEventReaders
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface EventFilter {
/**
* Tests whether this event is part of this stream. This method
* will return true if this filter accepts this event and false
* otherwise.
*
* @param event the event to test
* @return true if this filter accepts this event, false otherwise
*/
public boolean accept(XMLEvent event);
}

View file

@ -0,0 +1,117 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
/**
* An error class for reporting factory configuration errors.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public class FactoryConfigurationError extends Error {
Exception nested;
/**
* Default constructor
*/
public FactoryConfigurationError(){}
/**
* Construct an exception with a nested inner exception
*
* @param e the exception to nest
*/
public FactoryConfigurationError(java.lang.Exception e){
nested = e;
}
/**
* Construct an exception with a nested inner exception
* and a message
*
* @param e the exception to nest
* @param msg the message to report
*/
public FactoryConfigurationError(java.lang.Exception e, java.lang.String msg){
super(msg);
nested = e;
}
/**
* Construct an exception with a nested inner exception
* and a message
*
* @param msg the message to report
* @param e the exception to nest
*/
public FactoryConfigurationError(java.lang.String msg, java.lang.Exception e){
super(msg);
nested = e;
}
/**
* Construct an exception with associated message
*
* @param msg the message to report
*/
public FactoryConfigurationError(java.lang.String msg) {
super(msg);
}
/**
* Return the nested exception (if any)
*
* @return the nested exception or null
*/
public Exception getException() {
return nested;
}
/**
* Report the message associated with this error
*
* @return the string value of the message
*/
public String getMessage() {
String msg = super.getMessage();
if(msg != null)
return msg;
if(nested != null){
msg = nested.getMessage();
if(msg == null)
msg = nested.getClass().toString();
}
return msg;
}
}

View file

@ -0,0 +1,330 @@
/*
* Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.stream;
import java.io.InputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* <p>Implements pluggable Datatypes.</p>
*
* <p>This class is duplicated for each JAXP subpackage so keep it in
* sync. It is package private for secure class loading.</p>
*
* @author Santiago.PericasGeertsen@sun.com
*/
class FactoryFinder {
/**
* Internal debug flag.
*/
private static boolean debug = false;
/**
* Cache for properties in java.home/lib/jaxp.properties
*/
static Properties cacheProps = new Properties();
/**
* Flag indicating if properties from java.home/lib/jaxp.properties
* have been cached.
*/
static boolean firstTime = true;
/**
* Security support class use to check access control before
* getting certain system resources.
*/
static SecuritySupport ss = new SecuritySupport();
// Define system property "jaxp.debug" to get output
static {
// Use try/catch block to support applets, which throws
// SecurityException out of this code.
try {
String val = ss.getSystemProperty("jaxp.debug");
// Allow simply setting the prop to turn on debug
debug = val != null && !"false".equals(val);
}
catch (SecurityException se) {
debug = false;
}
}
private static void dPrint(String msg) {
if (debug) {
System.err.println("JAXP: " + msg);
}
}
/**
* Attempt to load a class using the class loader supplied. If that fails
* and fall back is enabled, the current (i.e. bootstrap) class loader is
* tried.
*
* If the class loader supplied is <code>null</code>, first try using the
* context class loader followed by the current (i.e. bootstrap) class
* loader.
*/
static private Class getProviderClass(String className, ClassLoader cl,
boolean doFallback) throws ClassNotFoundException
{
try {
if (cl == null) {
cl = ss.getContextClassLoader();
if (cl == null) {
throw new ClassNotFoundException();
}
else {
return cl.loadClass(className);
}
}
else {
return cl.loadClass(className);
}
}
catch (ClassNotFoundException e1) {
if (doFallback) {
// Use current class loader - should always be bootstrap CL
return Class.forName(className, true, FactoryFinder.class.getClassLoader());
}
else {
throw e1;
}
}
}
/**
* Create an instance of a class. Delegates to method
* <code>getProviderClass()</code> in order to load the class.
*
* @param className Name of the concrete class corresponding to the
* service provider
*
* @param cl ClassLoader to use to load the class, null means to use
* the bootstrap ClassLoader
*
* @param doFallback True if the current ClassLoader should be tried as
* a fallback if the class is not found using cl
*/
static Object newInstance(String className, ClassLoader cl, boolean doFallback)
throws ConfigurationError
{
try {
Class providerClass = getProviderClass(className, cl, doFallback);
Object instance = providerClass.newInstance();
if (debug) { // Extra check to avoid computing cl strings
dPrint("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);
}
}
/**
* Finds the implementation Class object in the specified order. Main
* entry point.
* @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.
*
* Package private so this code can be shared.
*/
static Object find(String factoryId, String fallbackClassName)
throws ConfigurationError
{
dPrint("find factoryId =" + factoryId);
// Use the system property first
try {
String systemProp = ss.getSystemProperty(factoryId);
if (systemProp != null) {
dPrint("found system property, value=" + systemProp);
return newInstance(systemProp, null, true);
}
}
catch (SecurityException se) {
if (debug) se.printStackTrace();
}
// Try read $java.home/lib/stax.properties followed by
// $java.home/lib/jaxp.properties if former not present
String configFile = null;
try {
String factoryClassName = null;
if (firstTime) {
synchronized (cacheProps) {
if (firstTime) {
configFile = ss.getSystemProperty("java.home") + File.separator +
"lib" + File.separator + "stax.properties";
File f = new File(configFile);
firstTime = false;
if (ss.doesFileExist(f)) {
dPrint("Read properties file "+f);
cacheProps.load(ss.getFileInputStream(f));
}
else {
configFile = ss.getSystemProperty("java.home") + File.separator +
"lib" + File.separator + "jaxp.properties";
f = new File(configFile);
if (ss.doesFileExist(f)) {
dPrint("Read properties file "+f);
cacheProps.load(ss.getFileInputStream(f));
}
}
}
}
}
factoryClassName = cacheProps.getProperty(factoryId);
if (factoryClassName != null) {
dPrint("found in " + configFile + " value=" + factoryClassName);
return newInstance(factoryClassName, null, true);
}
}
catch (Exception ex) {
if (debug) ex.printStackTrace();
}
// 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);
}
dPrint("loaded from fallback value: " + fallbackClassName);
return newInstance(fallbackClassName, null, true);
}
/*
* 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
{
String serviceId = "META-INF/services/" + factoryId;
InputStream is = null;
// First try the Context ClassLoader
ClassLoader cl = ss.getContextClassLoader();
if (cl != null) {
is = ss.getResourceAsStream(cl, serviceId);
// If no provider found then try the current ClassLoader
if (is == null) {
cl = FactoryFinder.class.getClassLoader();
is = ss.getResourceAsStream(cl, serviceId);
}
} else {
// No Context ClassLoader, try the current ClassLoader
cl = FactoryFinder.class.getClassLoader();
is = ss.getResourceAsStream(cl, serviceId);
}
if (is == null) {
// No provider found
return null;
}
if (debug) { // Extra check to avoid computing cl strings
dPrint("found jar resource=" + serviceId + " using ClassLoader: " + cl);
}
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
}
catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is));
}
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)) {
dPrint("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;
}
static class ConfigurationError extends Error {
private Exception exception;
/**
* Construct a new instance with the specified detail string and
* exception.
*/
ConfigurationError(String msg, Exception x) {
super(msg);
this.exception = x;
}
Exception getException() {
return exception;
}
}
}

View file

@ -0,0 +1,76 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
/**
* Provides information on the location of an event.
*
* All the information provided by a Location is optional. For example
* an application may only report line numbers.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface Location {
/**
* Return the line number where the current event ends,
* returns -1 if none is available.
* @return the current line number
*/
int getLineNumber();
/**
* Return the column number where the current event ends,
* returns -1 if none is available.
* @return the current column number
*/
int getColumnNumber();
/**
* Return the byte or character offset into the input source this location
* is pointing to. If the input source is a file or a byte stream then
* this is the byte offset into that stream, but if the input source is
* a character media then the offset is the character offset.
* Returns -1 if there is no offset available.
* @return the current offset
*/
int getCharacterOffset();
/**
* Returns the public ID of the XML
* @return the public ID, or null if not available
*/
public String getPublicId();
/**
* Returns the system ID of the XML
* @return the system ID, or null if not available
*/
public String getSystemId();
}

View file

@ -0,0 +1,110 @@
/*
* Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.stream;
import java.security.*;
import java.net.*;
import java.io.*;
import java.util.*;
/**
* 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 SecuritySupport {
ClassLoader getContextClassLoader() throws SecurityException{
return (ClassLoader)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ClassLoader cl = null;
//try {
cl = Thread.currentThread().getContextClassLoader();
//} catch (SecurityException ex) { }
if (cl == null)
cl = ClassLoader.getSystemClassLoader();
return cl;
}
});
}
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 doesFileExist(final File f) {
return ((Boolean)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return new Boolean(f.exists());
}
})).booleanValue();
}
}

View file

@ -0,0 +1,49 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
/**
* This interface declares a simple filter interface that one can
* create to filter XMLStreamReaders
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface StreamFilter {
/**
* Tests whether the current state is part of this stream. This method
* will return true if this filter accepts this event and false otherwise.
*
* The method should not change the state of the reader when accepting
* a state.
*
* @param reader the event to test
* @return true if this filter accepts this event, false otherwise
*/
public boolean accept(XMLStreamReader reader);
}

View file

@ -0,0 +1,345 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
import javax.xml.stream.events.*;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import java.util.Iterator;
/**
* This interface defines a utility class for creating instances of
* XMLEvents
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see javax.xml.stream.events.StartElement
* @see javax.xml.stream.events.EndElement
* @see javax.xml.stream.events.ProcessingInstruction
* @see javax.xml.stream.events.Comment
* @see javax.xml.stream.events.Characters
* @see javax.xml.stream.events.StartDocument
* @see javax.xml.stream.events.EndDocument
* @see javax.xml.stream.events.DTD
* @since 1.6
*/
public abstract class XMLEventFactory {
protected XMLEventFactory(){}
/**
* Create a new instance of the factory
* @throws FactoryConfigurationError if an instance of this factory cannot be loaded
*/
public static XMLEventFactory newInstance()
throws FactoryConfigurationError
{
return (XMLEventFactory) FactoryFinder.find(
"javax.xml.stream.XMLEventFactory",
"com.sun.xml.internal.stream.events.XMLEventFactoryImpl");
}
/**
* Create a new instance of the factory
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param classLoader classLoader to use
* @return the factory implementation
* @throws FactoryConfigurationError if an instance of this factory cannot be loaded
*/
public static XMLEventFactory newInstance(String factoryId,
ClassLoader classLoader)
throws FactoryConfigurationError {
try {
//do not fallback if given classloader can't find the class, throw exception
return (XMLEventFactory) FactoryFinder.newInstance(factoryId, classLoader, false);
} catch (FactoryFinder.ConfigurationError e) {
throw new FactoryConfigurationError(e.getException(),
e.getMessage());
}
}
/**
* This method allows setting of the Location on each event that
* is created by this factory. The values are copied by value into
* the events created by this factory. To reset the location
* information set the location to null.
* @param location the location to set on each event created
*/
public abstract void setLocation(Location location);
/**
* Create a new Attribute
* @param prefix the prefix of this attribute, may not be null
* @param namespaceURI the attribute value is set to this value, may not be null
* @param localName the local name of the XML name of the attribute, localName cannot be null
* @param value the attribute value to set, may not be null
* @return the Attribute with specified values
*/
public abstract Attribute createAttribute(String prefix, String namespaceURI, String localName, String value);
/**
* Create a new Attribute
* @param localName the local name of the XML name of the attribute, localName cannot be null
* @param value the attribute value to set, may not be null
* @return the Attribute with specified values
*/
public abstract Attribute createAttribute(String localName, String value);
/**
* Create a new Attribute
* @param name the qualified name of the attribute, may not be null
* @param value the attribute value to set, may not be null
* @return the Attribute with specified values
*/
public abstract Attribute createAttribute(QName name, String value);
/**
* Create a new default Namespace
* @param namespaceURI the default namespace uri
* @return the Namespace with the specified value
*/
public abstract Namespace createNamespace(String namespaceURI);
/**
* Create a new Namespace
* @param prefix the prefix of this namespace, may not be null
* @param namespaceUri the attribute value is set to this value, may not be null
* @return the Namespace with the specified values
*/
public abstract Namespace createNamespace(String prefix, String namespaceUri);
/**
* Create a new StartElement. Namespaces can be added to this StartElement
* by passing in an Iterator that walks over a set of Namespace interfaces.
* Attributes can be added to this StartElement by passing an iterator
* that walks over a set of Attribute interfaces.
*
* @param name the qualified name of the attribute, may not be null
* @param attributes an optional unordered set of objects that
* implement Attribute to add to the new StartElement, may be null
* @param namespaces an optional unordered set of objects that
* implement Namespace to add to the new StartElement, may be null
* @return an instance of the requested StartElement
*/
public abstract StartElement createStartElement(QName name,
Iterator attributes,
Iterator namespaces);
/**
* Create a new StartElement. This defaults the NamespaceContext to
* an empty NamespaceContext. Querying this event for its namespaces or
* attributes will result in an empty iterator being returned.
*
* @param namespaceUri the uri of the QName of the new StartElement
* @param localName the local name of the QName of the new StartElement
* @param prefix the prefix of the QName of the new StartElement
* @return an instance of the requested StartElement
*/
public abstract StartElement createStartElement(String prefix,
String namespaceUri,
String localName);
/**
* Create a new StartElement. Namespaces can be added to this StartElement
* by passing in an Iterator that walks over a set of Namespace interfaces.
* Attributes can be added to this StartElement by passing an iterator
* that walks over a set of Attribute interfaces.
*
* @param namespaceUri the uri of the QName of the new StartElement
* @param localName the local name of the QName of the new StartElement
* @param prefix the prefix of the QName of the new StartElement
* @param attributes an unordered set of objects that implement
* Attribute to add to the new StartElement
* @param namespaces an unordered set of objects that implement
* Namespace to add to the new StartElement
* @return an instance of the requested StartElement
*/
public abstract StartElement createStartElement(String prefix,
String namespaceUri,
String localName,
Iterator attributes,
Iterator namespaces
);
/**
* Create a new StartElement. Namespaces can be added to this StartElement
* by passing in an Iterator that walks over a set of Namespace interfaces.
* Attributes can be added to this StartElement by passing an iterator
* that walks over a set of Attribute interfaces.
*
* @param namespaceUri the uri of the QName of the new StartElement
* @param localName the local name of the QName of the new StartElement
* @param prefix the prefix of the QName of the new StartElement
* @param attributes an unordered set of objects that implement
* Attribute to add to the new StartElement, may be null
* @param namespaces an unordered set of objects that implement
* Namespace to add to the new StartElement, may be null
* @param context the namespace context of this element
* @return an instance of the requested StartElement
*/
public abstract StartElement createStartElement(String prefix,
String namespaceUri,
String localName,
Iterator attributes,
Iterator namespaces,
NamespaceContext context
);
/**
* Create a new EndElement
* @param name the qualified name of the EndElement
* @param namespaces an optional unordered set of objects that
* implement Namespace that have gone out of scope, may be null
* @return an instance of the requested EndElement
*/
public abstract EndElement createEndElement(QName name,
Iterator namespaces);
/**
* Create a new EndElement
* @param namespaceUri the uri of the QName of the new StartElement
* @param localName the local name of the QName of the new StartElement
* @param prefix the prefix of the QName of the new StartElement
* @return an instance of the requested EndElement
*/
public abstract EndElement createEndElement(String prefix,
String namespaceUri,
String localName);
/**
* Create a new EndElement
* @param namespaceUri the uri of the QName of the new StartElement
* @param localName the local name of the QName of the new StartElement
* @param prefix the prefix of the QName of the new StartElement
* @param namespaces an unordered set of objects that implement
* Namespace that have gone out of scope, may be null
* @return an instance of the requested EndElement
*/
public abstract EndElement createEndElement(String prefix,
String namespaceUri,
String localName,
Iterator namespaces);
/**
* Create a Characters event, this method does not check if the content
* is all whitespace. To create a space event use #createSpace(String)
* @param content the string to create
* @return a Characters event
*/
public abstract Characters createCharacters(String content);
/**
* Create a Characters event with the CData flag set to true
* @param content the string to create
* @return a Characters event
*/
public abstract Characters createCData(String content);
/**
* Create a Characters event with the isSpace flag set to true
* @param content the content of the space to create
* @return a Characters event
*/
public abstract Characters createSpace(String content);
/**
* Create an ignorable space
* @param content the space to create
* @return a Characters event
*/
public abstract Characters createIgnorableSpace(String content);
/**
* Creates a new instance of a StartDocument event
* @return a StartDocument event
*/
public abstract StartDocument createStartDocument();
/**
* Creates a new instance of a StartDocument event
*
* @param encoding the encoding style
* @param version the XML version
* @param standalone the status of standalone may be set to "true" or "false"
* @return a StartDocument event
*/
public abstract StartDocument createStartDocument(String encoding,
String version,
boolean standalone);
/**
* Creates a new instance of a StartDocument event
*
* @param encoding the encoding style
* @param version the XML version
* @return a StartDocument event
*/
public abstract StartDocument createStartDocument(String encoding,
String version);
/**
* Creates a new instance of a StartDocument event
*
* @param encoding the encoding style
* @return a StartDocument event
*/
public abstract StartDocument createStartDocument(String encoding);
/**
* Creates a new instance of an EndDocument event
* @return an EndDocument event
*/
public abstract EndDocument createEndDocument();
/** Creates a new instance of a EntityReference event
*
* @param name The name of the reference
* @param declaration the declaration for the event
* @return an EntityReference event
*/
public abstract EntityReference createEntityReference(String name,
EntityDeclaration declaration);
/**
* Create a comment
* @param text The text of the comment
* a Comment event
*/
public abstract Comment createComment(String text);
/**
* Create a processing instruction
* @param target The target of the processing instruction
* @param data The text of the processing instruction
* @return a ProcessingInstruction event
*/
public abstract ProcessingInstruction createProcessingInstruction(String target,
String data);
/**
* Create a document type definition event
* This string contains the entire document type declaration that matches
* the doctypedecl in the XML 1.0 specification
* @param dtd the text of the document type definition
* @return a DTD event
*/
public abstract DTD createDTD(String dtd);
}

View file

@ -0,0 +1,102 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
import javax.xml.stream.events.XMLEvent;
import java.util.Iterator;
/**
*
* This is the top level interface for parsing XML Events. It provides
* the ability to peek at the next event and returns configuration
* information through the property interface.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see XMLInputFactory
* @see XMLEventWriter
* @since 1.6
*/
public interface XMLEventReader extends Iterator {
/**
* Get the next XMLEvent
* @see XMLEvent
* @throws XMLStreamException if there is an error with the underlying XML.
* @throws NoSuchElementException iteration has no more elements.
*/
public XMLEvent nextEvent() throws XMLStreamException;
/**
* Check if there are more events.
* Returns true if there are more events and false otherwise.
* @return true if the event reader has more events, false otherwise
*/
public boolean hasNext();
/**
* Check the next XMLEvent without reading it from the stream.
* Returns null if the stream is at EOF or has no more XMLEvents.
* A call to peek() will be equal to the next return of next().
* @see XMLEvent
* @throws XMLStreamException
*/
public XMLEvent peek() throws XMLStreamException;
/**
* Reads the content of a text-only element. Precondition:
* the current event is START_ELEMENT. Postcondition:
* The current event is the corresponding END_ELEMENT.
* @throws XMLStreamException if the current event is not a START_ELEMENT
* or if a non text element is encountered
*/
public String getElementText() throws XMLStreamException;
/**
* Skips any insignificant space events until a START_ELEMENT or
* END_ELEMENT is reached. If anything other than space characters are
* encountered, an exception is thrown. This method should
* be used when processing element-only content because
* the parser is not able to recognize ignorable whitespace if
* the DTD is missing or not interpreted.
* @throws XMLStreamException if anything other than space characters are encountered
*/
public XMLEvent nextTag() throws XMLStreamException;
/**
* Get the value of a feature/property from the underlying implementation
* @param name The name of the property
* @return The value of the property
* @throws IllegalArgumentException if the property is not supported
*/
public Object getProperty(java.lang.String name) throws java.lang.IllegalArgumentException;
/**
* Frees any resources associated with this Reader. This method does not close the
* underlying input source.
* @throws XMLStreamException if there are errors freeing associated resources
*/
public void close() throws XMLStreamException;
}

View file

@ -0,0 +1,255 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
import javax.xml.stream.events.*;
import javax.xml.stream.util.XMLEventConsumer;
import javax.xml.namespace.NamespaceContext;
/**
*
* This is the top level interface for writing XML documents.
*
* Instances of this interface are not required to validate the
* form of the XML.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see XMLEventReader
* @see javax.xml.stream.events.XMLEvent
* @see javax.xml.stream.events.Characters
* @see javax.xml.stream.events.ProcessingInstruction
* @see javax.xml.stream.events.StartElement
* @see javax.xml.stream.events.EndElement
* @since 1.6
*/
public interface XMLEventWriter extends XMLEventConsumer {
/**
* Writes any cached events to the underlying output mechanism
* @throws XMLStreamException
*/
public void flush() throws XMLStreamException;
/**
* Frees any resources associated with this stream
* @throws XMLStreamException
*/
public void close() throws XMLStreamException;
/**
* Add an event to the output stream
* Adding a START_ELEMENT will open a new namespace scope that
* will be closed when the corresponding END_ELEMENT is written.
* <table border="2" rules="all" cellpadding="4">
* <thead>
* <tr>
* <th align="center" colspan="2">
* Required and optional fields for events added to the writer
* </th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <th>Event Type</th>
* <th>Required Fields</th>
* <th>Optional Fields</th>
* <th>Required Behavior</th>
* </tr>
* <tr>
* <td> START_ELEMENT </td>
* <td> QName name </td>
* <td> namespaces , attributes </td>
* <td> A START_ELEMENT will be written by writing the name,
* namespaces, and attributes of the event in XML 1.0 valid
* syntax for START_ELEMENTs.
* The name is written by looking up the prefix for
* the namespace uri. The writer can be configured to
* respect prefixes of QNames. If the writer is respecting
* prefixes it must use the prefix set on the QName. The
* default behavior is to lookup the value for the prefix
* on the EventWriter's internal namespace context.
* Each attribute (if any)
* is written using the behavior specified in the attribute
* section of this table. Each namespace (if any) is written
* using the behavior specified in the namespace section of this
* table.
* </td>
* </tr>
* <tr>
* <td> END_ELEMENT </td>
* <td> Qname name </td>
* <td> None </td>
* <td> A well formed END_ELEMENT tag is written.
* The name is written by looking up the prefix for
* the namespace uri. The writer can be configured to
* respect prefixes of QNames. If the writer is respecting
* prefixes it must use the prefix set on the QName. The
* default behavior is to lookup the value for the prefix
* on the EventWriter's internal namespace context.
* If the END_ELEMENT name does not match the START_ELEMENT
* name an XMLStreamException is thrown.
* </td>
* </tr>
* <tr>
* <td> ATTRIBUTE </td>
* <td> QName name , String value </td>
* <td> QName type </td>
* <td> An attribute is written using the same algorithm
* to find the lexical form as used in START_ELEMENT.
* The default is to use double quotes to wrap attribute
* values and to escape any double quotes found in the
* value. The type value is ignored.
* </td>
* </tr>
* <tr>
* <td> NAMESPACE </td>
* <td> String prefix, String namespaceURI,
* boolean isDefaultNamespaceDeclaration
* </td>
* <td> None </td>
* <td> A namespace declaration is written. If the
* namespace is a default namespace declaration
* (isDefault is true) then xmlns="$namespaceURI"
* is written and the prefix is optional. If
* isDefault is false, the prefix must be declared
* and the writer must prepend xmlns to the prefix
* and write out a standard prefix declaration.
* </td>
* </tr>
* <tr>
* <td> PROCESSING_INSTRUCTION </td>
* <td> None</td>
* <td> String target, String data</td>
* <td> The data does not need to be present and may be
* null. Target is required and many not be null.
* The writer
* will write data section
* directly after the target,
* enclosed in appropriate XML 1.0 syntax
* </td>
* </tr>
* <tr>
* <td> COMMENT </td>
* <td> None </td>
* <td> String comment </td>
* <td> If the comment is present (not null) it is written, otherwise an
* an empty comment is written
* </td>
* </tr>
* <tr>
* <td> START_DOCUMENT </td>
* <td> None </td>
* <td> String encoding , boolean standalone, String version </td>
* <td> A START_DOCUMENT event is not required to be written to the
* stream. If present the attributes are written inside
* the appropriate XML declaration syntax
* </td>
* </tr>
* <tr>
* <td> END_DOCUMENT </td>
* <td> None </td>
* <td> None </td>
* <td> Nothing is written to the output </td>
* </tr>
* <tr>
* <td> DTD </td>
* <td> String DocumentTypeDefinition </td>
* <td> None </td>
* <td> The DocumentTypeDefinition is written to the output </td>
* </tr>
* </tbody>
* </table>
* @param event the event to be added
* @throws XMLStreamException
*/
public void add(XMLEvent event) throws XMLStreamException;
/**
* Adds an entire stream to an output stream,
* calls next() on the inputStream argument until hasNext() returns false
* This should be treated as a convenience method that will
* perform the following loop over all the events in an
* event reader and call add on each event.
*
* @param reader the event stream to add to the output
* @throws XMLStreamException
*/
public void add(XMLEventReader reader) throws XMLStreamException;
/**
* Gets the prefix the uri is bound to
* @param uri the uri to look up
* @throws XMLStreamException
*/
public String getPrefix(String uri) throws XMLStreamException;
/**
* Sets the prefix the uri is bound to. This prefix is bound
* in the scope of the current START_ELEMENT / END_ELEMENT pair.
* If this method is called before a START_ELEMENT has been written
* the prefix is bound in the root scope.
* @param prefix the prefix to bind to the uri
* @param uri the uri to bind to the prefix
* @throws XMLStreamException
*/
public void setPrefix(String prefix, String uri) throws XMLStreamException;
/**
* Binds a URI to the default namespace
* This URI is bound
* in the scope of the current START_ELEMENT / END_ELEMENT pair.
* If this method is called before a START_ELEMENT has been written
* the uri is bound in the root scope.
* @param uri the uri to bind to the default namespace
* @throws XMLStreamException
*/
public void setDefaultNamespace(String uri) throws XMLStreamException;
/**
* Sets the current namespace context for prefix and uri bindings.
* This context becomes the root namespace context for writing and
* will replace the current root namespace context. Subsequent calls
* to setPrefix and setDefaultNamespace will bind namespaces using
* the context passed to the method as the root context for resolving
* namespaces.
* @param context the namespace context to use for this writer
* @throws XMLStreamException
*/
public void setNamespaceContext(NamespaceContext context)
throws XMLStreamException;
/**
* Returns the current namespace context.
* @return the current namespace context
*/
public NamespaceContext getNamespaceContext();
}

View file

@ -0,0 +1,389 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
import javax.xml.transform.Source;
import javax.xml.stream.util.XMLEventAllocator;
/**
* Defines an abstract implementation of a factory for getting streams.
*
* The following table defines the standard properties of this specification.
* Each property varies in the level of support required by each implementation.
* The level of support required is described in the 'Required' column.
*
* <table border="2" rules="all" cellpadding="4">
* <thead>
* <tr>
* <th align="center" colspan="5">
* Configuration parameters
* </th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <th>Property Name</th>
* <th>Behavior</th>
* <th>Return type</th>
* <th>Default Value</th>
* <th>Required</th>
* </tr>
* <tr><td>javax.xml.stream.isValidating</td><td>Turns on/off implementation specific DTD validation</td><td>Boolean</td><td>False</td><td>No</td></tr>
* <tr><td>javax.xml.stream.isNamespaceAware</td><td>Turns on/off namespace processing for XML 1.0 support</td><td>Boolean</td><td>True</td><td>True (required) / False (optional)</td></tr>
* <tr><td>javax.xml.stream.isCoalescing</td><td>Requires the processor to coalesce adjacent character data</td><td>Boolean</td><td>False</td><td>Yes</td></tr>
* <tr><td>javax.xml.stream.isReplacingEntityReferences</td><td>replace internal entity references with their replacement text and report them as characters</td><td>Boolean</td><td>True</td><td>Yes</td></tr>
*<tr><td>javax.xml.stream.isSupportingExternalEntities</td><td>Resolve external parsed entities</td><td>Boolean</td><td>Unspecified</td><td>Yes</td></tr>
*<tr><td>javax.xml.stream.supportDTD</td><td>Use this property to request processors that do not support DTDs</td><td>Boolean</td><td>True</td><td>Yes</td></tr>
*<tr><td>javax.xml.stream.reporter</td><td>sets/gets the impl of the XMLReporter </td><td>javax.xml.stream.XMLReporter</td><td>Null</td><td>Yes</td></tr>
*<tr><td>javax.xml.stream.resolver</td><td>sets/gets the impl of the XMLResolver interface</td><td>javax.xml.stream.XMLResolver</td><td>Null</td><td>Yes</td></tr>
*<tr><td>javax.xml.stream.allocator</td><td>sets/gets the impl of the XMLEventAllocator interface</td><td>javax.xml.stream.util.XMLEventAllocator</td><td>Null</td><td>Yes</td></tr>
* </tbody>
* </table>
*
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see XMLOutputFactory
* @see XMLEventReader
* @see XMLStreamReader
* @see EventFilter
* @see XMLReporter
* @see XMLResolver
* @see javax.xml.stream.util.XMLEventAllocator
* @since 1.6
*/
public abstract class XMLInputFactory {
/**
* The property used to turn on/off namespace support,
* this is to support XML 1.0 documents,
* only the true setting must be supported
*/
public static final String IS_NAMESPACE_AWARE=
"javax.xml.stream.isNamespaceAware";
/**
* The property used to turn on/off implementation specific validation
*/
public static final String IS_VALIDATING=
"javax.xml.stream.isValidating";
/**
* The property that requires the parser to coalesce adjacent character data sections
*/
public static final String IS_COALESCING=
"javax.xml.stream.isCoalescing";
/**
* Requires the parser to replace internal
* entity references with their replacement
* text and report them as characters
*/
public static final String IS_REPLACING_ENTITY_REFERENCES=
"javax.xml.stream.isReplacingEntityReferences";
/**
* The property that requires the parser to resolve external parsed entities
*/
public static final String IS_SUPPORTING_EXTERNAL_ENTITIES=
"javax.xml.stream.isSupportingExternalEntities";
/**
* The property that requires the parser to support DTDs
*/
public static final String SUPPORT_DTD=
"javax.xml.stream.supportDTD";
/**
* The property used to
* set/get the implementation of the XMLReporter interface
*/
public static final String REPORTER=
"javax.xml.stream.reporter";
/**
* The property used to set/get the implementation of the XMLResolver
*/
public static final String RESOLVER=
"javax.xml.stream.resolver";
/**
* The property used to set/get the implementation of the allocator
*/
public static final String ALLOCATOR=
"javax.xml.stream.allocator";
protected XMLInputFactory(){}
/**
* Create a new instance of the factory.
* This static method creates a new factory instance.
* This method uses the following ordered lookup procedure to determine
* the XMLInputFactory implementation class to load:
* Use the javax.xml.stream.XMLInputFactory system property.
* Use the properties file "lib/stax.properties" in the JRE directory.
* This configuration file is in standard java.util.Properties format and contains
* the fully qualified name of the implementation class with the key being the system property defined above.
* Use the Services API (as detailed in the JAR specification), if available, to determine the classname.
* The Services API will look for a classname in the file META-INF/services/javax.xml.stream.XMLInputFactory
* in jars available to the runtime.
* Platform default XMLInputFactory instance.
* Once an application has obtained a reference to a XMLInputFactory
* it can use the factory to configure and obtain stream instances.
*
* @throws FactoryConfigurationError if an instance of this factory cannot be loaded
*/
public static XMLInputFactory newInstance()
throws FactoryConfigurationError
{
return (XMLInputFactory) FactoryFinder.find(
"javax.xml.stream.XMLInputFactory",
"com.sun.xml.internal.stream.XMLInputFactoryImpl");
}
/**
* Create a new instance of the factory
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param classLoader classLoader to use
* @return the factory implementation
* @throws FactoryConfigurationError if an instance of this factory cannot be loaded
*/
public static XMLInputFactory newInstance(String factoryId,
ClassLoader classLoader)
throws FactoryConfigurationError {
try {
//do not fallback if given classloader can't find the class, throw exception
return (XMLInputFactory) FactoryFinder.newInstance(factoryId, classLoader, false);
} catch (FactoryFinder.ConfigurationError e) {
throw new FactoryConfigurationError(e.getException(),
e.getMessage());
}
}
/**
* Create a new XMLStreamReader from a reader
* @param reader the XML data to read from
* @throws XMLStreamException
*/
public abstract XMLStreamReader createXMLStreamReader(java.io.Reader reader)
throws XMLStreamException;
/**
* Create a new XMLStreamReader from a JAXP source. This method is optional.
* @param source the source to read from
* @throws UnsupportedOperationException if this method is not
* supported by this XMLInputFactory
* @throws XMLStreamException
*/
public abstract XMLStreamReader createXMLStreamReader(Source source)
throws XMLStreamException;
/**
* Create a new XMLStreamReader from a java.io.InputStream
* @param stream the InputStream to read from
* @throws XMLStreamException
*/
public abstract XMLStreamReader createXMLStreamReader(java.io.InputStream stream)
throws XMLStreamException;
/**
* Create a new XMLStreamReader from a java.io.InputStream
* @param stream the InputStream to read from
* @param encoding the character encoding of the stream
* @throws XMLStreamException
*/
public abstract XMLStreamReader createXMLStreamReader(java.io.InputStream stream, String encoding)
throws XMLStreamException;
/**
* Create a new XMLStreamReader from a java.io.InputStream
* @param systemId the system ID of the stream
* @param stream the InputStream to read from
*/
public abstract XMLStreamReader createXMLStreamReader(String systemId, java.io.InputStream stream)
throws XMLStreamException;
/**
* Create a new XMLStreamReader from a java.io.InputStream
* @param systemId the system ID of the stream
* @param reader the InputStream to read from
*/
public abstract XMLStreamReader createXMLStreamReader(String systemId, java.io.Reader reader)
throws XMLStreamException;
/**
* Create a new XMLEventReader from a reader
* @param reader the XML data to read from
* @throws XMLStreamException
*/
public abstract XMLEventReader createXMLEventReader(java.io.Reader reader)
throws XMLStreamException;
/**
* Create a new XMLEventReader from a reader
* @param systemId the system ID of the input
* @param reader the XML data to read from
* @throws XMLStreamException
*/
public abstract XMLEventReader createXMLEventReader(String systemId, java.io.Reader reader)
throws XMLStreamException;
/**
* Create a new XMLEventReader from an XMLStreamReader. After being used
* to construct the XMLEventReader instance returned from this method
* the XMLStreamReader must not be used.
* @param reader the XMLStreamReader to read from (may not be modified)
* @return a new XMLEventReader
* @throws XMLStreamException
*/
public abstract XMLEventReader createXMLEventReader(XMLStreamReader reader)
throws XMLStreamException;
/**
* Create a new XMLEventReader from a JAXP source.
* Support of this method is optional.
* @param source the source to read from
* @throws UnsupportedOperationException if this method is not
* supported by this XMLInputFactory
*/
public abstract XMLEventReader createXMLEventReader(Source source)
throws XMLStreamException;
/**
* Create a new XMLEventReader from a java.io.InputStream
* @param stream the InputStream to read from
* @throws XMLStreamException
*/
public abstract XMLEventReader createXMLEventReader(java.io.InputStream stream)
throws XMLStreamException;
/**
* Create a new XMLEventReader from a java.io.InputStream
* @param stream the InputStream to read from
* @param encoding the character encoding of the stream
* @throws XMLStreamException
*/
public abstract XMLEventReader createXMLEventReader(java.io.InputStream stream, String encoding)
throws XMLStreamException;
/**
* Create a new XMLEventReader from a java.io.InputStream
* @param systemId the system ID of the stream
* @param stream the InputStream to read from
* @throws XMLStreamException
*/
public abstract XMLEventReader createXMLEventReader(String systemId, java.io.InputStream stream)
throws XMLStreamException;
/**
* Create a filtered reader that wraps the filter around the reader
* @param reader the reader to filter
* @param filter the filter to apply to the reader
* @throws XMLStreamException
*/
public abstract XMLStreamReader createFilteredReader(XMLStreamReader reader, StreamFilter filter)
throws XMLStreamException;
/**
* Create a filtered event reader that wraps the filter around the event reader
* @param reader the event reader to wrap
* @param filter the filter to apply to the event reader
* @throws XMLStreamException
*/
public abstract XMLEventReader createFilteredReader(XMLEventReader reader, EventFilter filter)
throws XMLStreamException;
/**
* The resolver that will be set on any XMLStreamReader or XMLEventReader created
* by this factory instance.
*/
public abstract XMLResolver getXMLResolver();
/**
* The resolver that will be set on any XMLStreamReader or XMLEventReader created
* by this factory instance.
* @param resolver the resolver to use to resolve references
*/
public abstract void setXMLResolver(XMLResolver resolver);
/**
* The reporter that will be set on any XMLStreamReader or XMLEventReader created
* by this factory instance.
*/
public abstract XMLReporter getXMLReporter();
/**
* The reporter that will be set on any XMLStreamReader or XMLEventReader created
* by this factory instance.
* @param reporter the resolver to use to report non fatal errors
*/
public abstract void setXMLReporter(XMLReporter reporter);
/**
* Allows the user to set specific feature/property on the underlying implementation. The underlying implementation
* is not required to support every setting of every property in the specification and may use IllegalArgumentException
* to signal that an unsupported property may not be set with the specified value.
* @param name The name of the property (may not be null)
* @param value The value of the property
* @throws java.lang.IllegalArgumentException if the property is not supported
*/
public abstract void setProperty(java.lang.String name, Object value)
throws java.lang.IllegalArgumentException;
/**
* Get the value of a feature/property from the underlying implementation
* @param name The name of the property (may not be null)
* @return The value of the property
* @throws IllegalArgumentException if the property is not supported
*/
public abstract Object getProperty(java.lang.String name)
throws java.lang.IllegalArgumentException;
/**
* Query the set of properties that this factory supports.
*
* @param name The name of the property (may not be null)
* @return true if the property is supported and false otherwise
*/
public abstract boolean isPropertySupported(String name);
/**
* Set a user defined event allocator for events
* @param allocator the user defined allocator
*/
public abstract void setEventAllocator(XMLEventAllocator allocator);
/**
* Gets the allocator used by streams created with this factory
*/
public abstract XMLEventAllocator getEventAllocator();
}

View file

@ -0,0 +1,244 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
import javax.xml.transform.Result;
/**
* Defines an abstract implementation of a factory for
* getting XMLEventWriters and XMLStreamWriters.
*
* The following table defines the standard properties of this specification.
* Each property varies in the level of support required by each implementation.
* The level of support required is described in the 'Required' column.
*
* <table border="2" rules="all" cellpadding="4">
* <thead>
* <tr>
* <th align="center" colspan="2">
* Configuration parameters
* </th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <th>Property Name</th>
* <th>Behavior</th>
* <th>Return type</th>
* <th>Default Value</th>
* <th>Required</th>
* </tr>
* <tr><td>javax.xml.stream.isRepairingNamespaces</td><td>defaults prefixes on the output side</td><td>Boolean</td><td>False</td><td>Yes</td></tr>
* </tbody>
* </table>
*
* <p>The following paragraphs describe the namespace and prefix repair algorithm:</p>
*
* <p>The property can be set with the following code line:
* <code>setProperty("javax.xml.stream.isRepairingNamespaces",new Boolean(true|false));</code></p>
*
* <p>This property specifies that the writer default namespace prefix declarations.
* The default value is false. </p>
*
* <p>If a writer isRepairingNamespaces it will create a namespace declaration
* on the current StartElement for
* any attribute that does not
* currently have a namespace declaration in scope. If the StartElement
* has a uri but no prefix specified a prefix will be assigned, if the prefix
* has not been declared in a parent of the current StartElement it will be declared
* on the current StartElement. If the defaultNamespace is bound and in scope
* and the default namespace matches the URI of the attribute or StartElement
* QName no prefix will be assigned.</p>
*
* <p>If an element or attribute name has a prefix, but is not
* bound to any namespace URI, then the prefix will be removed
* during serialization.</p>
*
* <p>If element and/or attribute names in the same start or
* empty-element tag are bound to different namespace URIs and
* are using the same prefix then the element or the first
* occurring attribute retains the original prefix and the
* following attributes have their prefixes replaced with a
* new prefix that is bound to the namespace URIs of those
* attributes. </p>
*
* <p>If an element or attribute name uses a prefix that is
* bound to a different URI than that inherited from the
* namespace context of the parent of that element and there
* is no namespace declaration in the context of the current
* element then such a namespace declaration is added. </p>
*
* <p>If an element or attribute name is bound to a prefix and
* there is a namespace declaration that binds that prefix
* to a different URI then that namespace declaration is
* either removed if the correct mapping is inherited from
* the parent context of that element, or changed to the
* namespace URI of the element or attribute using that prefix.</p>
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see XMLInputFactory
* @see XMLEventWriter
* @see XMLStreamWriter
* @since 1.6
*/
public abstract class XMLOutputFactory {
/**
* Property used to set prefix defaulting on the output side
*/
public static final String IS_REPAIRING_NAMESPACES=
"javax.xml.stream.isRepairingNamespaces";
protected XMLOutputFactory(){}
/**
* Create a new instance of the factory.
* @throws FactoryConfigurationError if an instance of this factory cannot be loaded
*/
public static XMLOutputFactory newInstance()
throws FactoryConfigurationError
{
return (XMLOutputFactory) FactoryFinder.find("javax.xml.stream.XMLOutputFactory",
"com.sun.xml.internal.stream.XMLOutputFactoryImpl");
}
/**
* Create a new instance of the factory.
*
* @param factoryId Name of the factory to find, same as
* a property name
* @param classLoader classLoader to use
* @return the factory implementation
* @throws FactoryConfigurationError if an instance of this factory cannot be loaded
*/
public static XMLInputFactory newInstance(String factoryId,
ClassLoader classLoader)
throws FactoryConfigurationError {
try {
//do not fallback if given classloader can't find the class, throw exception
return (XMLInputFactory) FactoryFinder.newInstance(factoryId, classLoader, false);
} catch (FactoryFinder.ConfigurationError e) {
throw new FactoryConfigurationError(e.getException(),
e.getMessage());
}
}
/**
* Create a new XMLStreamWriter that writes to a writer
* @param stream the writer to write to
* @throws XMLStreamException
*/
public abstract XMLStreamWriter createXMLStreamWriter(java.io.Writer stream) throws XMLStreamException;
/**
* Create a new XMLStreamWriter that writes to a stream
* @param stream the stream to write to
* @throws XMLStreamException
*/
public abstract XMLStreamWriter createXMLStreamWriter(java.io.OutputStream stream) throws XMLStreamException;
/**
* Create a new XMLStreamWriter that writes to a stream
* @param stream the stream to write to
* @param encoding the encoding to use
* @throws XMLStreamException
*/
public abstract XMLStreamWriter createXMLStreamWriter(java.io.OutputStream stream,
String encoding) throws XMLStreamException;
/**
* Create a new XMLStreamWriter that writes to a JAXP result. This method is optional.
* @param result the result to write to
* @throws UnsupportedOperationException if this method is not
* supported by this XMLOutputFactory
* @throws XMLStreamException
*/
public abstract XMLStreamWriter createXMLStreamWriter(Result result) throws XMLStreamException;
/**
* Create a new XMLEventWriter that writes to a JAXP result. This method is optional.
* @param result the result to write to
* @throws UnsupportedOperationException if this method is not
* supported by this XMLOutputFactory
* @throws XMLStreamException
*/
public abstract XMLEventWriter createXMLEventWriter(Result result) throws XMLStreamException;
/**
* Create a new XMLEventWriter that writes to a stream
* @param stream the stream to write to
* @throws XMLStreamException
*/
public abstract XMLEventWriter createXMLEventWriter(java.io.OutputStream stream) throws XMLStreamException;
/**
* Create a new XMLEventWriter that writes to a stream
* @param stream the stream to write to
* @param encoding the encoding to use
* @throws XMLStreamException
*/
public abstract XMLEventWriter createXMLEventWriter(java.io.OutputStream stream,
String encoding) throws XMLStreamException;
/**
* Create a new XMLEventWriter that writes to a writer
* @param stream the stream to write to
* @throws XMLStreamException
*/
public abstract XMLEventWriter createXMLEventWriter(java.io.Writer stream) throws XMLStreamException;
/**
* Allows the user to set specific features/properties on the underlying implementation.
* @param name The name of the property
* @param value The value of the property
* @throws java.lang.IllegalArgumentException if the property is not supported
*/
public abstract void setProperty(java.lang.String name,
Object value)
throws IllegalArgumentException;
/**
* Get a feature/property on the underlying implementation
* @param name The name of the property
* @return The value of the property
* @throws java.lang.IllegalArgumentException if the property is not supported
*/
public abstract Object getProperty(java.lang.String name)
throws IllegalArgumentException;
/**
* Query the set of properties that this factory supports.
*
* @param name The name of the property (may not be null)
* @return true if the property is supported and false otherwise
*/
public abstract boolean isPropertySupported(String name);
}

View file

@ -0,0 +1,53 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
/**
* This interface is used to report non-fatal errors.
* Only warnings should be echoed through this interface.
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface XMLReporter {
/**
* Report the desired message in an application specific format.
* Only warnings and non-fatal errors should be reported through
* this interface.
* Fatal errors should be thrown as XMLStreamException.
*
* @param message the error message
* @param errorType an implementation defined error type
* @param relatedInformation information related to the error, if available
* @param location the location of the error, if available
* @throws XMLStreamException
*/
public void report(String message, String errorType, Object relatedInformation, Location location)
throws XMLStreamException;
}

View file

@ -0,0 +1,59 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
/**
* This interface is used to resolve resources during an XML parse. If an application wishes to
* perform custom entity resolution it must register an instance of this interface with
* the XMLInputFactory using the setXMLResolver method.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface XMLResolver {
/**
* Retrieves a resource. This resource can be of the following three return types:
* (1) java.io.InputStream (2) javax.xml.stream.XMLStreamReader (3) java.xml.stream.XMLEventReader.
* If this method returns null the processor will attempt to resolve the entity using its
* default mechanism.
*
* @param publicID The public identifier of the external entity being referenced, or null if none was supplied.
* @param systemID The system identifier of the external entity being referenced.
* @param baseURI Absolute base URI associated with systemId.
* @param namespace The namespace of the entity to resolve.
* @return The resource requested or null.
* @throws XMLStreamException if there was a failure attempting to resolve the resource.
*/
public Object resolveEntity(String publicID,
String systemID,
String baseURI,
String namespace)
throws XMLStreamException;
}

View file

@ -0,0 +1,127 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.stream;
/**
* This interface declares the constants used in this API.
* Numbers in the range 0 to 256 are reserved for the specification,
* user defined events must use event codes outside that range.
*
* @since 1.6
*/
public interface XMLStreamConstants {
/**
* Indicates an event is a start element
* @see javax.xml.stream.events.StartElement
*/
public static final int START_ELEMENT=1;
/**
* Indicates an event is an end element
* @see javax.xml.stream.events.EndElement
*/
public static final int END_ELEMENT=2;
/**
* Indicates an event is a processing instruction
* @see javax.xml.stream.events.ProcessingInstruction
*/
public static final int PROCESSING_INSTRUCTION=3;
/**
* Indicates an event is characters
* @see javax.xml.stream.events.Characters
*/
public static final int CHARACTERS=4;
/**
* Indicates an event is a comment
* @see javax.xml.stream.events.Comment
*/
public static final int COMMENT=5;
/**
* The characters are white space
* (see [XML], 2.10 "White Space Handling").
* Events are only reported as SPACE if they are ignorable white
* space. Otherwise they are reported as CHARACTERS.
* @see javax.xml.stream.events.Characters
*/
public static final int SPACE=6;
/**
* Indicates an event is a start document
* @see javax.xml.stream.events.StartDocument
*/
public static final int START_DOCUMENT=7;
/**
* Indicates an event is an end document
* @see javax.xml.stream.events.EndDocument
*/
public static final int END_DOCUMENT=8;
/**
* Indicates an event is an entity reference
* @see javax.xml.stream.events.EntityReference
*/
public static final int ENTITY_REFERENCE=9;
/**
* Indicates an event is an attribute
* @see javax.xml.stream.events.Attribute
*/
public static final int ATTRIBUTE=10;
/**
* Indicates an event is a DTD
* @see javax.xml.stream.events.DTD
*/
public static final int DTD=11;
/**
* Indicates an event is a CDATA section
* @see javax.xml.stream.events.Characters
*/
public static final int CDATA=12;
/**
* Indicates the event is a namespace declaration
*
* @see javax.xml.stream.events.Namespace
*/
public static final int NAMESPACE=13;
/**
* Indicates a Notation
* @see javax.xml.stream.events.NotationDeclaration
*/
public static final int NOTATION_DECLARATION=14;
/**
* Indicates a Entity Declaration
* @see javax.xml.stream.events.NotationDeclaration
*/
public static final int ENTITY_DECLARATION=15;
}

View file

@ -0,0 +1,128 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
/**
* The base exception for unexpected processing errors. This Exception
* class is used to report well-formedness errors as well as unexpected
* processing conditions.
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public class XMLStreamException extends Exception {
protected Throwable nested;
protected Location location;
/**
* Default constructor
*/
public XMLStreamException(){
super();
}
/**
* Construct an exception with the assocated message.
*
* @param msg the message to report
*/
public XMLStreamException(String msg) {
super(msg);
}
/**
* Construct an exception with the assocated exception
*
* @param th a nested exception
*/
public XMLStreamException(Throwable th) {
super(th);
nested = th;
}
/**
* Construct an exception with the assocated message and exception
*
* @param th a nested exception
* @param msg the message to report
*/
public XMLStreamException(String msg, Throwable th) {
super(msg, th);
nested = th;
}
/**
* Construct an exception with the assocated message, exception and location.
*
* @param th a nested exception
* @param msg the message to report
* @param location the location of the error
*/
public XMLStreamException(String msg, Location location, Throwable th) {
super("ParseError at [row,col]:["+location.getLineNumber()+","+
location.getColumnNumber()+"]\n"+
"Message: "+msg);
nested = th;
this.location = location;
}
/**
* Construct an exception with the assocated message, exception and location.
*
* @param msg the message to report
* @param location the location of the error
*/
public XMLStreamException(String msg,
Location location) {
super("ParseError at [row,col]:["+location.getLineNumber()+","+
location.getColumnNumber()+"]\n"+
"Message: "+msg);
this.location = location;
}
/**
* Gets the nested exception.
*
* @return Nested exception
*/
public Throwable getNestedException() {
return nested;
}
/**
* Gets the location of the exception
*
* @return the location of the exception, may be null if none is available
*/
public Location getLocation() {
return location;
}
}

View file

@ -0,0 +1,703 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
import java.io.Reader;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
/**
* The XMLStreamReader interface allows forward, read-only access to XML.
* It is designed to be the lowest level and most efficient way to
* read XML data.
*
* <p> The XMLStreamReader is designed to iterate over XML using
* next() and hasNext(). The data can be accessed using methods such as getEventType(),
* getNamespaceURI(), getLocalName() and getText();
*
* <p> The <a href="#next()">next()</a> method causes the reader to read the next parse event.
* The next() method returns an integer which identifies the type of event just read.
* <p> The event type can be determined using <a href="#getEventType()">getEventType()</a>.
* <p> Parsing events are defined as the XML Declaration, a DTD,
* start tag, character data, white space, end tag, comment,
* or processing instruction. An attribute or namespace event may be encountered
* at the root level of a document as the result of a query operation.
*
* <p>For XML 1.0 compliance an XML processor must pass the
* identifiers of declared unparsed entities, notation declarations and their
* associated identifiers to the application. This information is
* provided through the property API on this interface.
* The following two properties allow access to this information:
* javax.xml.stream.notations and javax.xml.stream.entities.
* When the current event is a DTD the following call will return a
* list of Notations
* <code>List l = (List) getProperty("javax.xml.stream.notations");</code>
* The following call will return a list of entity declarations:
* <code>List l = (List) getProperty("javax.xml.stream.entities");</code>
* These properties can only be accessed during a DTD event and
* are defined to return null if the information is not available.
*
* <p>The following table describes which methods are valid in what state.
* If a method is called in an invalid state the method will throw a
* java.lang.IllegalStateException.
*
* <table border="2" rules="all" cellpadding="4">
* <thead>
* <tr>
* <th align="center" colspan="2">
* Valid methods for each state
* </th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <th>Event Type</th>
* <th>Valid Methods</th>
* </tr>
* <tr>
* <td> All States </td>
* <td> getProperty(), hasNext(), require(), close(),
* getNamespaceURI(), isStartElement(),
* isEndElement(), isCharacters(), isWhiteSpace(),
* getNamespaceContext(), getEventType(),getLocation(),
* hasText(), hasName()
* </td>
* </tr>
* <tr>
* <td> START_ELEMENT </td>
* <td> next(), getName(), getLocalName(), hasName(), getPrefix(),
* getAttributeXXX(), isAttributeSpecified(),
* getNamespaceXXX(),
* getElementText(), nextTag()
* </td>
* </tr>
* <td> ATTRIBUTE </td>
* <td> next(), nextTag()
* getAttributeXXX(), isAttributeSpecified(),
* </td>
* </tr>
* </tr>
* <td> NAMESPACE </td>
* <td> next(), nextTag()
* getNamespaceXXX()
* </td>
* </tr>
* <tr>
* <td> END_ELEMENT </td>
* <td> next(), getName(), getLocalName(), hasName(), getPrefix(),
* getNamespaceXXX(), nextTag()
* </td>
* </tr>
* <tr>
* <td> CHARACTERS </td>
* <td> next(), getTextXXX(), nextTag() </td>
* </tr>
* <tr>
* <td> CDATA </td>
* <td> next(), getTextXXX(), nextTag() </td>
* </tr>
* <tr>
* <td> COMMENT </td>
* <td> next(), getTextXXX(), nextTag() </td>
* </tr>
* <tr>
* <td> SPACE </td>
* <td> next(), getTextXXX(), nextTag() </td>
* </tr>
* <tr>
* <td> START_DOCUMENT </td>
* <td> next(), getEncoding(), getVersion(), isStandalone(), standaloneSet(),
* getCharacterEncodingScheme(), nextTag()</td>
* </tr>
* <tr>
* <td> END_DOCUMENT </td>
* <td> close()</td>
* </tr>
* <tr>
* <td> PROCESSING_INSTRUCTION </td>
* <td> next(), getPITarget(), getPIData(), nextTag() </td>
* </tr>
* <tr>
* <td> ENTITY_REFERENCE </td>
* <td> next(), getLocalName(), getText(), nextTag() </td>
* </tr>
* <tr>
* <td> DTD </td>
* <td> next(), getText(), nextTag() </td>
* </tr>
* </tbody>
* </table>
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see javax.xml.stream.events.XMLEvent
* @see XMLInputFactory
* @see XMLStreamWriter
* @since 1.6
*/
public interface XMLStreamReader extends XMLStreamConstants {
/**
* Get the value of a feature/property from the underlying implementation
* @param name The name of the property, may not be null
* @return The value of the property
* @throws IllegalArgumentException if name is null
*/
public Object getProperty(java.lang.String name) throws java.lang.IllegalArgumentException;
/**
* Get next parsing event - a processor may return all contiguous
* character data in a single chunk, or it may split it into several chunks.
* If the property javax.xml.stream.isCoalescing is set to true
* element content must be coalesced and only one CHARACTERS event
* must be returned for contiguous element content or
* CDATA Sections.
*
* By default entity references must be
* expanded and reported transparently to the application.
* An exception will be thrown if an entity reference cannot be expanded.
* If element content is empty (i.e. content is "") then no CHARACTERS event will be reported.
*
* <p>Given the following XML:<br>
* &lt;foo>&lt;!--description-->content text&lt;![CDATA[&lt;greeting>Hello&lt;/greeting>]]>other content&lt;/foo><br>
* The behavior of calling next() when being on foo will be:<br>
* 1- the comment (COMMENT)<br>
* 2- then the characters section (CHARACTERS)<br>
* 3- then the CDATA section (another CHARACTERS)<br>
* 4- then the next characters section (another CHARACTERS)<br>
* 5- then the END_ELEMENT<br>
*
* <p><b>NOTE:</b> empty element (such as &lt;tag/>) will be reported
* with two separate events: START_ELEMENT, END_ELEMENT - This preserves
* parsing equivalency of empty element to &lt;tag>&lt;/tag>.
*
* This method will throw an IllegalStateException if it is called after hasNext() returns false.
* @see javax.xml.stream.events.XMLEvent
* @return the integer code corresponding to the current parse event
* @throws NoSuchElementException if this is called when hasNext() returns false
* @throws XMLStreamException if there is an error processing the underlying XML source
*/
public int next() throws XMLStreamException;
/**
* Test if the current event is of the given type and if the namespace and name match the current
* namespace and name of the current event. If the namespaceURI is null it is not checked for equality,
* if the localName is null it is not checked for equality.
* @param type the event type
* @param namespaceURI the uri of the event, may be null
* @param localName the localName of the event, may be null
* @throws XMLStreamException if the required values are not matched.
*/
public void require(int type, String namespaceURI, String localName) throws XMLStreamException;
/**
* Reads the content of a text-only element, an exception is thrown if this is
* not a text-only element.
* Regardless of value of javax.xml.stream.isCoalescing this method always returns coalesced content.
* <br /> Precondition: the current event is START_ELEMENT.
* <br /> Postcondition: the current event is the corresponding END_ELEMENT.
*
* <br />The method does the following (implementations are free to optimized
* but must do equivalent processing):
* <pre>
* if(getEventType() != XMLStreamConstants.START_ELEMENT) {
* throw new XMLStreamException(
* "parser must be on START_ELEMENT to read next text", getLocation());
* }
* int eventType = next();
* StringBuffer content = new StringBuffer();
* while(eventType != XMLStreamConstants.END_ELEMENT ) {
* if(eventType == XMLStreamConstants.CHARACTERS
* || eventType == XMLStreamConstants.CDATA
* || eventType == XMLStreamConstants.SPACE
* || eventType == XMLStreamConstants.ENTITY_REFERENCE) {
* buf.append(getText());
* } else if(eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
* || eventType == XMLStreamConstants.COMMENT) {
* // skipping
* } else if(eventType == XMLStreamConstants.END_DOCUMENT) {
* throw new XMLStreamException(
* "unexpected end of document when reading element text content", this);
* } else if(eventType == XMLStreamConstants.START_ELEMENT) {
* throw new XMLStreamException(
* "element text content may not contain START_ELEMENT", getLocation());
* } else {
* throw new XMLStreamException(
* "Unexpected event type "+eventType, getLocation());
* }
* eventType = next();
* }
* return buf.toString();
* </pre>
*
* @throws XMLStreamException if the current event is not a START_ELEMENT
* or if a non text element is encountered
*/
public String getElementText() throws XMLStreamException;
/**
* Skips any white space (isWhiteSpace() returns true), COMMENT,
* or PROCESSING_INSTRUCTION,
* until a START_ELEMENT or END_ELEMENT is reached.
* If other than white space characters, COMMENT, PROCESSING_INSTRUCTION, START_ELEMENT, END_ELEMENT
* are encountered, an exception is thrown. This method should
* be used when processing element-only content seperated by white space.
*
* <br /> Precondition: none
* <br /> Postcondition: the current event is START_ELEMENT or END_ELEMENT
* and cursor may have moved over any whitespace event.
*
* <br />Essentially it does the following (implementations are free to optimized
* but must do equivalent processing):
* <pre>
* int eventType = next();
* while((eventType == XMLStreamConstants.CHARACTERS &amp;&amp; isWhiteSpace()) // skip whitespace
* || (eventType == XMLStreamConstants.CDATA &amp;&amp; isWhiteSpace())
* // skip whitespace
* || eventType == XMLStreamConstants.SPACE
* || eventType == XMLStreamConstants.PROCESSING_INSTRUCTION
* || eventType == XMLStreamConstants.COMMENT
* ) {
* eventType = next();
* }
* if (eventType != XMLStreamConstants.START_ELEMENT &amp;&amp; eventType != XMLStreamConstants.END_ELEMENT) {
* throw new String XMLStreamException("expected start or end tag", getLocation());
* }
* return eventType;
* </pre>
*
* @return the event type of the element read (START_ELEMENT or END_ELEMENT)
* @throws XMLStreamException if the current event is not white space, PROCESSING_INSTRUCTION,
* START_ELEMENT or END_ELEMENT
* @throws NoSuchElementException if this is called when hasNext() returns false
*/
public int nextTag() throws XMLStreamException;
/**
* Returns true if there are more parsing events and false
* if there are no more events. This method will return
* false if the current state of the XMLStreamReader is
* END_DOCUMENT
* @return true if there are more events, false otherwise
* @throws XMLStreamException if there is a fatal error detecting the next state
*/
public boolean hasNext() throws XMLStreamException;
/**
* Frees any resources associated with this Reader. This method does not close the
* underlying input source.
* @throws XMLStreamException if there are errors freeing associated resources
*/
public void close() throws XMLStreamException;
/**
* Return the uri for the given prefix.
* The uri returned depends on the current state of the processor.
*
* <p><strong>NOTE:</strong>The 'xml' prefix is bound as defined in
* <a href="http://www.w3.org/TR/REC-xml-names/#ns-using">Namespaces in XML</a>
* specification to "http://www.w3.org/XML/1998/namespace".
*
* <p><strong>NOTE:</strong> The 'xmlns' prefix must be resolved to following namespace
* <a href="http://www.w3.org/2000/xmlns/">http://www.w3.org/2000/xmlns/</a>
* @param prefix The prefix to lookup, may not be null
* @return the uri bound to the given prefix or null if it is not bound
* @throws IllegalArgumentException if the prefix is null
*/
public String getNamespaceURI(String prefix);
/**
* Returns true if the cursor points to a start tag (otherwise false)
* @return true if the cursor points to a start tag, false otherwise
*/
public boolean isStartElement();
/**
* Returns true if the cursor points to an end tag (otherwise false)
* @return true if the cursor points to an end tag, false otherwise
*/
public boolean isEndElement();
/**
* Returns true if the cursor points to a character data event
* @return true if the cursor points to character data, false otherwise
*/
public boolean isCharacters();
/**
* Returns true if the cursor points to a character data event
* that consists of all whitespace
* @return true if the cursor points to all whitespace, false otherwise
*/
public boolean isWhiteSpace();
/**
* Returns the normalized attribute value of the
* attribute with the namespace and localName
* If the namespaceURI is null the namespace
* is not checked for equality
* @param namespaceURI the namespace of the attribute
* @param localName the local name of the attribute, cannot be null
* @return returns the value of the attribute , returns null if not found
* @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE
*/
public String getAttributeValue(String namespaceURI,
String localName);
/**
* Returns the count of attributes on this START_ELEMENT,
* this method is only valid on a START_ELEMENT or ATTRIBUTE. This
* count excludes namespace definitions. Attribute indices are
* zero-based.
* @return returns the number of attributes
* @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE
*/
public int getAttributeCount();
/** Returns the qname of the attribute at the provided index
*
* @param index the position of the attribute
* @return the QName of the attribute
* @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE
*/
public QName getAttributeName(int index);
/**
* Returns the namespace of the attribute at the provided
* index
* @param index the position of the attribute
* @return the namespace URI (can be null)
* @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE
*/
public String getAttributeNamespace(int index);
/**
* Returns the localName of the attribute at the provided
* index
* @param index the position of the attribute
* @return the localName of the attribute
* @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE
*/
public String getAttributeLocalName(int index);
/**
* Returns the prefix of this attribute at the
* provided index
* @param index the position of the attribute
* @return the prefix of the attribute
* @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE
*/
public String getAttributePrefix(int index);
/**
* Returns the XML type of the attribute at the provided
* index
* @param index the position of the attribute
* @return the XML type of the attribute
* @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE
*/
public String getAttributeType(int index);
/**
* Returns the value of the attribute at the
* index
* @param index the position of the attribute
* @return the attribute value
* @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE
*/
public String getAttributeValue(int index);
/**
* Returns a boolean which indicates if this
* attribute was created by default
* @param index the position of the attribute
* @return true if this is a default attribute
* @throws IllegalStateException if this is not a START_ELEMENT or ATTRIBUTE
*/
public boolean isAttributeSpecified(int index);
/**
* Returns the count of namespaces declared on this START_ELEMENT or END_ELEMENT,
* this method is only valid on a START_ELEMENT, END_ELEMENT or NAMESPACE. On
* an END_ELEMENT the count is of the namespaces that are about to go
* out of scope. This is the equivalent of the information reported
* by SAX callback for an end element event.
* @return returns the number of namespace declarations on this specific element
* @throws IllegalStateException if this is not a START_ELEMENT, END_ELEMENT or NAMESPACE
*/
public int getNamespaceCount();
/**
* Returns the prefix for the namespace declared at the
* index. Returns null if this is the default namespace
* declaration
*
* @param index the position of the namespace declaration
* @return returns the namespace prefix
* @throws IllegalStateException if this is not a START_ELEMENT, END_ELEMENT or NAMESPACE
*/
public String getNamespacePrefix(int index);
/**
* Returns the uri for the namespace declared at the
* index.
*
* @param index the position of the namespace declaration
* @return returns the namespace uri
* @throws IllegalStateException if this is not a START_ELEMENT, END_ELEMENT or NAMESPACE
*/
public String getNamespaceURI(int index);
/**
* Returns a read only namespace context for the current
* position. The context is transient and only valid until
* a call to next() changes the state of the reader.
* @return return a namespace context
*/
public NamespaceContext getNamespaceContext();
/**
* Returns a reader that points to the current start element
* and all of its contents. Throws an XMLStreamException if the
* cursor does not point to a START_ELEMENT.<p>
* The sub stream is read from it MUST be read before the parent stream is
* moved on, if not any call on the sub stream will cause an XMLStreamException to be
* thrown. The parent stream will always return the same result from next()
* whatever is done to the sub stream.
* @return an XMLStreamReader which points to the next element
*/
// public XMLStreamReader subReader() throws XMLStreamException;
/**
* Allows the implementation to reset and reuse any underlying tables
*/
// public void recycle() throws XMLStreamException;
/**
* Returns an integer code that indicates the type
* of the event the cursor is pointing to.
*/
public int getEventType();
/**
* Returns the current value of the parse event as a string,
* this returns the string value of a CHARACTERS event,
* returns the value of a COMMENT, the replacement value
* for an ENTITY_REFERENCE, the string value of a CDATA section,
* the string value for a SPACE event,
* or the String value of the internal subset of the DTD.
* If an ENTITY_REFERENCE has been resolved, any character data
* will be reported as CHARACTERS events.
* @return the current text or null
* @throws java.lang.IllegalStateException if this state is not
* a valid text state.
*/
public String getText();
/**
* Returns an array which contains the characters from this event.
* This array should be treated as read-only and transient. I.e. the array will
* contain the text characters until the XMLStreamReader moves on to the next event.
* Attempts to hold onto the character array beyond that time or modify the
* contents of the array are breaches of the contract for this interface.
* @return the current text or an empty array
* @throws java.lang.IllegalStateException if this state is not
* a valid text state.
*/
public char[] getTextCharacters();
/**
* Gets the the text associated with a CHARACTERS, SPACE or CDATA event.
* Text starting a "sourceStart" is copied into "target" starting at "targetStart".
* Up to "length" characters are copied. The number of characters actually copied is returned.
*
* The "sourceStart" argument must be greater or equal to 0 and less than or equal to
* the number of characters associated with the event. Usually, one requests text starting at a "sourceStart" of 0.
* If the number of characters actually copied is less than the "length", then there is no more text.
* Otherwise, subsequent calls need to be made until all text has been retrieved. For example:
*
*<code>
* int length = 1024;
* char[] myBuffer = new char[ length ];
*
* for ( int sourceStart = 0 ; ; sourceStart += length )
* {
* int nCopied = stream.getTextCharacters( sourceStart, myBuffer, 0, length );
*
* if (nCopied < length)
* break;
* }
* </code>
* XMLStreamException may be thrown if there are any XML errors in the underlying source.
* The "targetStart" argument must be greater than or equal to 0 and less than the length of "target",
* Length must be greater than 0 and "targetStart + length" must be less than or equal to length of "target".
*
* @param sourceStart the index of the first character in the source array to copy
* @param target the destination array
* @param targetStart the start offset in the target array
* @param length the number of characters to copy
* @return the number of characters actually copied
* @throws XMLStreamException if the underlying XML source is not well-formed
* @throws IndexOutOfBoundsException if targetStart < 0 or > than the length of target
* @throws IndexOutOfBoundsException if length < 0 or targetStart + length > length of target
* @throws UnsupportedOperationException if this method is not supported
* @throws NullPointerException is if target is null
*/
public int getTextCharacters(int sourceStart, char[] target, int targetStart, int length)
throws XMLStreamException;
/**
* Gets the text associated with a CHARACTERS, SPACE or CDATA event. Allows the underlying
* implementation to return the text as a stream of characters. The reference to the
* Reader returned by this method is only valid until next() is called.
*
* All characters must have been checked for well-formedness.
*
* <p> This method is optional and will throw UnsupportedOperationException if it is not supported.
* @throws UnsupportedOperationException if this method is not supported
* @throws IllegalStateException if this is not a valid text state
*/
//public Reader getTextStream();
/**
* Returns the offset into the text character array where the first
* character (of this text event) is stored.
* @throws java.lang.IllegalStateException if this state is not
* a valid text state.
*/
public int getTextStart();
/**
* Returns the length of the sequence of characters for this
* Text event within the text character array.
* @throws java.lang.IllegalStateException if this state is not
* a valid text state.
*/
public int getTextLength();
/**
* Return input encoding if known or null if unknown.
* @return the encoding of this instance or null
*/
public String getEncoding();
/**
* Return true if the current event has text, false otherwise
* The following events have text:
* CHARACTERS,DTD ,ENTITY_REFERENCE, COMMENT, SPACE
*/
public boolean hasText();
/**
* Return the current location of the processor.
* If the Location is unknown the processor should return
* an implementation of Location that returns -1 for the
* location and null for the publicId and systemId.
* The location information is only valid until next() is
* called.
*/
public Location getLocation();
/**
* Returns a QName for the current START_ELEMENT or END_ELEMENT event
* @return the QName for the current START_ELEMENT or END_ELEMENT event
* @throws IllegalStateException if this is not a START_ELEMENT or
* END_ELEMENT
*/
public QName getName();
/**
* Returns the (local) name of the current event.
* For START_ELEMENT or END_ELEMENT returns the (local) name of the current element.
* For ENTITY_REFERENCE it returns entity name.
* The current event must be START_ELEMENT or END_ELEMENT,
* or ENTITY_REFERENCE
* @return the localName
* @throws IllegalStateException if this not a START_ELEMENT,
* END_ELEMENT or ENTITY_REFERENCE
*/
public String getLocalName();
/**
* returns true if the current event has a name (is a START_ELEMENT or END_ELEMENT)
* returns false otherwise
*/
public boolean hasName();
/**
* If the current event is a START_ELEMENT or END_ELEMENT this method
* returns the URI of the prefix or the default namespace.
* Returns null if the event does not have a prefix.
* @return the URI bound to this elements prefix, the default namespace, or null
*/
public String getNamespaceURI();
/**
* Returns the prefix of the current event or null if the event does not have a prefix
* @return the prefix or null
*/
public String getPrefix();
/**
* Get the xml version declared on the xml declaration
* Returns null if none was declared
* @return the XML version or null
*/
public String getVersion();
/**
* Get the standalone declaration from the xml declaration
* @return true if this is standalone, or false otherwise
*/
public boolean isStandalone();
/**
* Checks if standalone was set in the document
* @return true if standalone was set in the document, or false otherwise
*/
public boolean standaloneSet();
/**
* Returns the character encoding declared on the xml declaration
* Returns null if none was declared
* @return the encoding declared in the document or null
*/
public String getCharacterEncodingScheme();
/**
* Get the target of a processing instruction
* @return the target or null
*/
public String getPITarget();
/**
* Get the data section of a processing instruction
* @return the data or null
*/
public String getPIData();
}

View file

@ -0,0 +1,527 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream;
import javax.xml.namespace.NamespaceContext;
/**
* The XMLStreamWriter interface specifies how to write XML. The XMLStreamWriter does
* not perform well formedness checking on its input. However
* the writeCharacters method is required to escape &amp; , &lt; and &gt;
* For attribute values the writeAttribute method will escape the
* above characters plus &quot; to ensure that all character content
* and attribute values are well formed.
*
* Each NAMESPACE
* and ATTRIBUTE must be individually written.
*
* <table border="1" cellpadding="2" cellspacing="0">
* <thead>
* <tr>
* <th colspan="5">XML Namespaces, <code>javax.xml.stream.isRepairingNamespaces</code> and write method behaviour</th>
* </tr>
* <tr>
* <th>Method</th> <!-- method -->
* <th colspan="2"><code>isRepairingNamespaces</code> == true</th>
* <th colspan="2"><code>isRepairingNamespaces</code> == false</th>
* </tr>
* <tr>
* <th></th> <!-- method -->
* <th>namespaceURI bound</th>
* <th>namespaceURI unbound</th>
* <th>namespaceURI bound</th>
* <th>namespaceURI unbound</th>
* </tr>
* </thead>
*
* <tbody>
* <tr>
* <th><code>writeAttribute(namespaceURI, localName, value)</code></th>
* <!-- isRepairingNamespaces == true -->
* <td>
* <!-- namespaceURI bound -->
* prefix:localName="value"&nbsp;<sup>[1]</sup>
* </td>
* <td>
* <!-- namespaceURI unbound -->
* xmlns:{generated}="namespaceURI" {generated}:localName="value"
* </td>
* <!-- isRepairingNamespaces == false -->
* <td>
* <!-- namespaceURI bound -->
* prefix:localName="value"&nbsp;<sup>[1]</sup>
* </td>
* <td>
* <!-- namespaceURI unbound -->
* <code>XMLStreamException</code>
* </td>
* </tr>
*
* <tr>
* <th><code>writeAttribute(prefix, namespaceURI, localName, value)</code></th>
* <!-- isRepairingNamespaces == true -->
* <td>
* <!-- namespaceURI bound -->
* bound to same prefix:<br />
* prefix:localName="value"&nbsp;<sup>[1]</sup><br />
* <br />
* bound to different prefix:<br />
* xmlns:{generated}="namespaceURI" {generated}:localName="value"
* </td>
* <td>
* <!-- namespaceURI unbound -->
* xmlns:prefix="namespaceURI" prefix:localName="value"&nbsp;<sup>[3]</sup>
* </td>
* <!-- isRepairingNamespaces == false -->
* <td>
* <!-- namespaceURI bound -->
* bound to same prefix:<br />
* prefix:localName="value"&nbsp;<sup>[1][2]</sup><br />
* <br />
* bound to different prefix:<br />
* <code>XMLStreamException</code><sup>[2]</sup>
* </td>
* <td>
* <!-- namespaceURI unbound -->
* xmlns:prefix="namespaceURI" prefix:localName="value"&nbsp;<sup>[2][5]</sup>
* </td>
* </tr>
*
* <tr>
* <th><code>writeStartElement(namespaceURI, localName)</code><br />
* <br />
* <code>writeEmptyElement(namespaceURI, localName)</code></th>
* <!-- isRepairingNamespaces == true -->
* <td >
* <!-- namespaceURI bound -->
* &lt;prefix:localName&gt;&nbsp;<sup>[1]</sup>
* </td>
* <td>
* <!-- namespaceURI unbound -->
* &lt;{generated}:localName xmlns:{generated}="namespaceURI"&gt;
* </td>
* <!-- isRepairingNamespaces == false -->
* <td>
* <!-- namespaceURI bound -->
* &lt;prefix:localName&gt;&nbsp;<sup>[1]</sup>
* </td>
* <td>
* <!-- namespaceURI unbound -->
* <code>XMLStreamException</code>
* </td>
* </tr>
*
* <tr>
* <th><code>writeStartElement(prefix, localName, namespaceURI)</code><br />
* <br />
* <code>writeEmptyElement(prefix, localName, namespaceURI)</code></th>
* <!-- isRepairingNamespaces == true -->
* <td>
* <!-- namespaceURI bound -->
* bound to same prefix:<br />
* &lt;prefix:localName&gt;&nbsp;<sup>[1]</sup><br />
* <br />
* bound to different prefix:<br />
* &lt;{generated}:localName xmlns:{generated}="namespaceURI"&gt;
* </td>
* <td>
* <!-- namespaceURI unbound -->
* &lt;prefix:localName xmlns:prefix="namespaceURI"&gt;&nbsp;<sup>[4]</sup>
* </td>
* <!-- isRepairingNamespaces == false -->
* <td>
* <!-- namespaceURI bound -->
* bound to same prefix:<br />
* &lt;prefix:localName&gt;&nbsp;<sup>[1]</sup><br />
* <br />
* bound to different prefix:<br />
* <code>XMLStreamException</code>
* </td>
* <td>
* <!-- namespaceURI unbound -->
* &lt;prefix:localName&gt;&nbsp;
* </td>
* </tr>
* </tbody>
* <tfoot>
* <tr>
* <td colspan="5">
* Notes:
* <ul>
* <li>[1] if namespaceURI == default Namespace URI, then no prefix is written</li>
* <li>[2] if prefix == "" || null && namespaceURI == "", then no prefix or Namespace declaration is generated or written</li>
* <li>[3] if prefix == "" || null, then a prefix is randomly generated</li>
* <li>[4] if prefix == "" || null, then it is treated as the default Namespace and no prefix is generated or written, an xmlns declaration is generated and written if the namespaceURI is unbound</li>
* <li>[5] if prefix == "" || null, then it is treated as an invalid attempt to define the default Namespace and an XMLStreamException is thrown</li>
* </ul>
* </td>
* </tr>
* </tfoot>
* </table>
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see XMLOutputFactory
* @see XMLStreamReader
* @since 1.6
*/
public interface XMLStreamWriter {
/**
* Writes a start tag to the output. All writeStartElement methods
* open a new scope in the internal namespace context. Writing the
* corresponding EndElement causes the scope to be closed.
* @param localName local name of the tag, may not be null
* @throws XMLStreamException
*/
public void writeStartElement(String localName)
throws XMLStreamException;
/**
* Writes a start tag to the output
* @param namespaceURI the namespaceURI of the prefix to use, may not be null
* @param localName local name of the tag, may not be null
* @throws XMLStreamException if the namespace URI has not been bound to a prefix and
* javax.xml.stream.isRepairingNamespaces has not been set to true
*/
public void writeStartElement(String namespaceURI, String localName)
throws XMLStreamException;
/**
* Writes a start tag to the output
* @param localName local name of the tag, may not be null
* @param prefix the prefix of the tag, may not be null
* @param namespaceURI the uri to bind the prefix to, may not be null
* @throws XMLStreamException
*/
public void writeStartElement(String prefix,
String localName,
String namespaceURI)
throws XMLStreamException;
/**
* Writes an empty element tag to the output
* @param namespaceURI the uri to bind the tag to, may not be null
* @param localName local name of the tag, may not be null
* @throws XMLStreamException if the namespace URI has not been bound to a prefix and
* javax.xml.stream.isRepairingNamespaces has not been set to true
*/
public void writeEmptyElement(String namespaceURI, String localName)
throws XMLStreamException;
/**
* Writes an empty element tag to the output
* @param prefix the prefix of the tag, may not be null
* @param localName local name of the tag, may not be null
* @param namespaceURI the uri to bind the tag to, may not be null
* @throws XMLStreamException
*/
public void writeEmptyElement(String prefix, String localName, String namespaceURI)
throws XMLStreamException;
/**
* Writes an empty element tag to the output
* @param localName local name of the tag, may not be null
* @throws XMLStreamException
*/
public void writeEmptyElement(String localName)
throws XMLStreamException;
/**
* Writes string data to the output without checking for well formedness.
* The data is opaque to the XMLStreamWriter, i.e. the characters are written
* blindly to the underlying output. If the method cannot be supported
* in the currrent writing context the implementation may throw a
* UnsupportedOperationException. For example note that any
* namespace declarations, end tags, etc. will be ignored and could
* interfere with proper maintanence of the writers internal state.
*
* @param data the data to write
*/
// public void writeRaw(String data) throws XMLStreamException;
/**
* Writes an end tag to the output relying on the internal
* state of the writer to determine the prefix and local name
* of the event.
* @throws XMLStreamException
*/
public void writeEndElement()
throws XMLStreamException;
/**
* Closes any start tags and writes corresponding end tags.
* @throws XMLStreamException
*/
public void writeEndDocument()
throws XMLStreamException;
/**
* Close this writer and free any resources associated with the
* writer. This must not close the underlying output stream.
* @throws XMLStreamException
*/
public void close()
throws XMLStreamException;
/**
* Write any cached data to the underlying output mechanism.
* @throws XMLStreamException
*/
public void flush()
throws XMLStreamException;
/**
* Writes an attribute to the output stream without
* a prefix.
* @param localName the local name of the attribute
* @param value the value of the attribute
* @throws IllegalStateException if the current state does not allow Attribute writing
* @throws XMLStreamException
*/
public void writeAttribute(String localName, String value)
throws XMLStreamException;
/**
* Writes an attribute to the output stream
* @param prefix the prefix for this attribute
* @param namespaceURI the uri of the prefix for this attribute
* @param localName the local name of the attribute
* @param value the value of the attribute
* @throws IllegalStateException if the current state does not allow Attribute writing
* @throws XMLStreamException if the namespace URI has not been bound to a prefix and
* javax.xml.stream.isRepairingNamespaces has not been set to true
*/
public void writeAttribute(String prefix,
String namespaceURI,
String localName,
String value)
throws XMLStreamException;
/**
* Writes an attribute to the output stream
* @param namespaceURI the uri of the prefix for this attribute
* @param localName the local name of the attribute
* @param value the value of the attribute
* @throws IllegalStateException if the current state does not allow Attribute writing
* @throws XMLStreamException if the namespace URI has not been bound to a prefix and
* javax.xml.stream.isRepairingNamespaces has not been set to true
*/
public void writeAttribute(String namespaceURI,
String localName,
String value)
throws XMLStreamException;
/**
* Writes a namespace to the output stream
* If the prefix argument to this method is the empty string,
* "xmlns", or null this method will delegate to writeDefaultNamespace
*
* @param prefix the prefix to bind this namespace to
* @param namespaceURI the uri to bind the prefix to
* @throws IllegalStateException if the current state does not allow Namespace writing
* @throws XMLStreamException
*/
public void writeNamespace(String prefix, String namespaceURI)
throws XMLStreamException;
/**
* Writes the default namespace to the stream
* @param namespaceURI the uri to bind the default namespace to
* @throws IllegalStateException if the current state does not allow Namespace writing
* @throws XMLStreamException
*/
public void writeDefaultNamespace(String namespaceURI)
throws XMLStreamException;
/**
* Writes an xml comment with the data enclosed
* @param data the data contained in the comment, may be null
* @throws XMLStreamException
*/
public void writeComment(String data)
throws XMLStreamException;
/**
* Writes a processing instruction
* @param target the target of the processing instruction, may not be null
* @throws XMLStreamException
*/
public void writeProcessingInstruction(String target)
throws XMLStreamException;
/**
* Writes a processing instruction
* @param target the target of the processing instruction, may not be null
* @param data the data contained in the processing instruction, may not be null
* @throws XMLStreamException
*/
public void writeProcessingInstruction(String target,
String data)
throws XMLStreamException;
/**
* Writes a CData section
* @param data the data contained in the CData Section, may not be null
* @throws XMLStreamException
*/
public void writeCData(String data)
throws XMLStreamException;
/**
* Write a DTD section. This string represents the entire doctypedecl production
* from the XML 1.0 specification.
*
* @param dtd the DTD to be written
* @throws XMLStreamException
*/
public void writeDTD(String dtd)
throws XMLStreamException;
/**
* Writes an entity reference
* @param name the name of the entity
* @throws XMLStreamException
*/
public void writeEntityRef(String name)
throws XMLStreamException;
/**
* Write the XML Declaration. Defaults the XML version to 1.0, and the encoding to utf-8
* @throws XMLStreamException
*/
public void writeStartDocument()
throws XMLStreamException;
/**
* Write the XML Declaration. Defaults the XML version to 1.0
* @param version version of the xml document
* @throws XMLStreamException
*/
public void writeStartDocument(String version)
throws XMLStreamException;
/**
* Write the XML Declaration. Note that the encoding parameter does
* not set the actual encoding of the underlying output. That must
* be set when the instance of the XMLStreamWriter is created using the
* XMLOutputFactory
* @param encoding encoding of the xml declaration
* @param version version of the xml document
* @throws XMLStreamException If given encoding does not match encoding
* of the underlying stream
*/
public void writeStartDocument(String encoding,
String version)
throws XMLStreamException;
/**
* Write text to the output
* @param text the value to write
* @throws XMLStreamException
*/
public void writeCharacters(String text)
throws XMLStreamException;
/**
* Write text to the output
* @param text the value to write
* @param start the starting position in the array
* @param len the number of characters to write
* @throws XMLStreamException
*/
public void writeCharacters(char[] text, int start, int len)
throws XMLStreamException;
/**
* Gets the prefix the uri is bound to
* @return the prefix or null
* @throws XMLStreamException
*/
public String getPrefix(String uri)
throws XMLStreamException;
/**
* Sets the prefix the uri is bound to. This prefix is bound
* in the scope of the current START_ELEMENT / END_ELEMENT pair.
* If this method is called before a START_ELEMENT has been written
* the prefix is bound in the root scope.
* @param prefix the prefix to bind to the uri, may not be null
* @param uri the uri to bind to the prefix, may be null
* @throws XMLStreamException
*/
public void setPrefix(String prefix, String uri)
throws XMLStreamException;
/**
* Binds a URI to the default namespace
* This URI is bound
* in the scope of the current START_ELEMENT / END_ELEMENT pair.
* If this method is called before a START_ELEMENT has been written
* the uri is bound in the root scope.
* @param uri the uri to bind to the default namespace, may be null
* @throws XMLStreamException
*/
public void setDefaultNamespace(String uri)
throws XMLStreamException;
/**
* Sets the current namespace context for prefix and uri bindings.
* This context becomes the root namespace context for writing and
* will replace the current root namespace context. Subsequent calls
* to setPrefix and setDefaultNamespace will bind namespaces using
* the context passed to the method as the root context for resolving
* namespaces. This method may only be called once at the start of
* the document. It does not cause the namespaces to be declared.
* If a namespace URI to prefix mapping is found in the namespace
* context it is treated as declared and the prefix may be used
* by the StreamWriter.
* @param context the namespace context to use for this writer, may not be null
* @throws XMLStreamException
*/
public void setNamespaceContext(NamespaceContext context)
throws XMLStreamException;
/**
* Returns the current namespace context.
* @return the current NamespaceContext
*/
public NamespaceContext getNamespaceContext();
/**
* Get the value of a feature/property from the underlying implementation
* @param name The name of the property, may not be null
* @return The value of the property
* @throws IllegalArgumentException if the property is not supported
* @throws NullPointerException if the name is null
*/
public Object getProperty(java.lang.String name) throws IllegalArgumentException;
}

View file

@ -0,0 +1,68 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
import javax.xml.namespace.QName;
/**
* An interface that contains information about an attribute. Attributes are reported
* as a set of events accessible from a StartElement. Other applications may report
* Attributes as first-order events, for example as the results of an XPath expression.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see StartElement
* @since 1.6
*/
public interface Attribute extends XMLEvent {
/**
* Returns the QName for this attribute
*/
QName getName();
/**
* Gets the normalized value of this attribute
*/
public String getValue();
/**
* Gets the type of this attribute, default is
* the String "CDATA"
* @return the type as a String, default is "CDATA"
*/
public String getDTDType();
/**
* A flag indicating whether this attribute was actually
* specified in the start-tag of its element, or was defaulted from the schema.
* @return returns true if this was specified in the start element
*/
public boolean isSpecified();
}

View file

@ -0,0 +1,75 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
/**
* This describes the interface to Characters events.
* All text events get reported as Characters events.
* Content, CData and whitespace are all reported as
* Characters events. IgnorableWhitespace, in most cases,
* will be set to false unless an element declaration of element
* content is present for the current element.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface Characters extends XMLEvent {
/**
* Get the character data of this event
*/
public String getData();
/**
* Returns true if this set of Characters
* is all whitespace. Whitespace inside a document
* is reported as CHARACTERS. This method allows
* checking of CHARACTERS events to see if they
* are composed of only whitespace characters
*/
public boolean isWhiteSpace();
/**
* Returns true if this is a CData section. If this
* event is CData its event type will be CDATA
*
* If javax.xml.stream.isCoalescing is set to true CDATA Sections
* that are surrounded by non CDATA characters will be reported
* as a single Characters event. This method will return false
* in this case.
*/
public boolean isCData();
/**
* Return true if this is ignorableWhiteSpace. If
* this event is ignorableWhiteSpace its event type will
* be SPACE.
*/
public boolean isIgnorableWhiteSpace();
}

View file

@ -0,0 +1,44 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
/**
* An interface for comment events
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface Comment extends XMLEvent {
/**
* Return the string data of the comment, returns empty string if it
* does not exist
*/
public String getText();
}

View file

@ -0,0 +1,73 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
import java.util.List;
/**
* This is the top level interface for events dealing with DTDs
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface DTD extends XMLEvent {
/**
* Returns the entire Document Type Declaration as a string, including
* the internal DTD subset.
* This may be null if there is not an internal subset.
* If it is not null it must return the entire
* Document Type Declaration which matches the doctypedecl
* production in the XML 1.0 specification
*/
String getDocumentTypeDeclaration();
/**
* Returns an implementation defined representation of the DTD.
* This method may return null if no representation is available.
*/
Object getProcessedDTD();
/**
* Return a List containing the notations declared in the DTD.
* This list must contain NotationDeclaration events.
* @see NotationDeclaration
* @return an unordered list of NotationDeclaration events
*/
List getNotations();
/**
* Return a List containing the general entities,
* both external and internal, declared in the DTD.
* This list must contain EntityDeclaration events.
* @see EntityDeclaration
* @return an unordered list of EntityDeclaration events
*/
List getEntities();
}

View file

@ -0,0 +1,41 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
/**
* A marker interface for the end of the document
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface EndDocument extends XMLEvent {
/**
* No methods are defined in this interface.
*/
}

View file

@ -0,0 +1,58 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
import java.util.Iterator;
import javax.xml.namespace.QName;
/**
* An interface for the end element event. An EndElement is reported
* for each End Tag in the document.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see XMLEvent
* @since 1.6
*/
public interface EndElement extends XMLEvent {
/**
* Get the name of this event
* @return the qualified name of this event
*/
public QName getName();
/**
* Returns an Iterator of namespaces that have gone out
* of scope. Returns an empty iterator if no namespaces have gone
* out of scope.
* @return an Iterator over Namespace interfaces, or an
* empty iterator
*/
public Iterator getNamespaces();
}

View file

@ -0,0 +1,79 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
/**
* An interface for handling Entity Declarations
*
* This interface is used to record and report unparsed entity declarations.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface EntityDeclaration extends XMLEvent {
/**
* The entity's public identifier, or null if none was given
* @return the public ID for this declaration or null
*/
String getPublicId();
/**
* The entity's system identifier.
* @return the system ID for this declaration or null
*/
String getSystemId();
/**
* The entity's name
* @return the name, may not be null
*/
String getName();
/**
* The name of the associated notation.
* @return the notation name
*/
String getNotationName();
/**
* The replacement text of the entity.
* This method will only return non-null
* if this is an internal entity.
* @return null or the replacment text
*/
String getReplacementText();
/**
* Get the base URI for this reference
* or null if this information is not available
* @return the base URI or null
*/
String getBaseURI();
}

View file

@ -0,0 +1,61 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
/**
* An interface for handling Entity events.
*
* This event reports entities that have not been resolved
* and reports their replacement text unprocessed (if
* available). This event will be reported if javax.xml.stream.isReplacingEntityReferences
* is set to false. If javax.xml.stream.isReplacingEntityReferences is set to true
* entity references will be resolved transparently.
*
* Entities are handled in two possible ways:
*
* (1) If javax.xml.stream.isReplacingEntityReferences is set to true
* all entity references are resolved and reported as markup transparently.
* (2) If javax.xml.stream.isReplacingEntityReferences is set to false
* Entity references are reported as an EntityReference Event.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface EntityReference extends XMLEvent {
/**
* Return the declaration of this entity.
*/
EntityDeclaration getDeclaration();
/**
* The name of the entity
* @return the entity's name, may not be null
*/
String getName();
}

View file

@ -0,0 +1,58 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
import javax.xml.namespace.QName;
/**
* An interface that contains information about a namespace.
* Namespaces are accessed from a StartElement.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see StartElement
* @since 1.6
*/
public interface Namespace extends Attribute {
/**
* Gets the prefix, returns "" if this is a default
* namespace declaration.
*/
public String getPrefix();
/**
* Gets the uri bound to the prefix of this namespace
*/
public String getNamespaceURI();
/**
* returns true if this attribute declares the default namespace
*/
public boolean isDefaultNamespaceDeclaration();
}

View file

@ -0,0 +1,57 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
/**
* An interface for handling Notation Declarations
*
* Receive notification of a notation declaration event.
* It is up to the application to record the notation for later reference,
* At least one of publicId and systemId must be non-null.
* There is no guarantee that the notation declaration
* will be reported before any unparsed entities that use it.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface NotationDeclaration extends XMLEvent {
/**
* The notation name.
*/
String getName();
/**
* The notation's public identifier, or null if none was given.
*/
String getPublicId();
/**
* The notation's system identifier, or null if none was given.
*/
String getSystemId();
}

View file

@ -0,0 +1,51 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
/**
* An interface that describes the data found in processing instructions
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface ProcessingInstruction extends XMLEvent {
/**
* The target section of the processing instruction
*
* @return the String value of the PI or null
*/
public String getTarget();
/**
* The data section of the processing instruction
*
* @return the String value of the PI's data or null
*/
public String getData();
}

View file

@ -0,0 +1,73 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
/**
* An interface for the start document event
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface StartDocument extends XMLEvent {
/**
* Returns the system ID of the XML data
* @return the system ID, defaults to ""
*/
public String getSystemId();
/**
* Returns the encoding style of the XML data
* @return the character encoding, defaults to "UTF-8"
*/
public String getCharacterEncodingScheme();
/**
* Returns true if CharacterEncodingScheme was set in
* the encoding declaration of the document
*/
public boolean encodingSet();
/**
* Returns if this XML is standalone
* @return the standalone state of XML, defaults to "no"
*/
public boolean isStandalone();
/**
* Returns true if the standalone attribute was set in
* the encoding declaration of the document.
*/
public boolean standaloneSet();
/**
* Returns the version of XML of this XML stream
* @return the version of XML, defaults to "1.0"
*/
public String getVersion();
}

View file

@ -0,0 +1,116 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
import javax.xml.namespace.QName;
import javax.xml.namespace.NamespaceContext;
import java.util.Map;
import java.util.Iterator;
/**
* The StartElement interface provides access to information about
* start elements. A StartElement is reported for each Start Tag
* in the document.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface StartElement extends XMLEvent {
/**
* Get the name of this event
* @return the qualified name of this event
*/
public QName getName();
/**
* Returns an Iterator of non-namespace declared attributes declared on
* this START_ELEMENT,
* returns an empty iterator if there are no attributes. The
* iterator must contain only implementations of the javax.xml.stream.Attribute
* interface. Attributes are fundamentally unordered and may not be reported
* in any order.
*
* @return a readonly Iterator over Attribute interfaces, or an
* empty iterator
*/
public Iterator getAttributes();
/**
* Returns an Iterator of namespaces declared on this element.
* This Iterator does not contain previously declared namespaces
* unless they appear on the current START_ELEMENT.
* Therefore this list may contain redeclared namespaces and duplicate namespace
* declarations. Use the getNamespaceContext() method to get the
* current context of namespace declarations.
*
* <p>The iterator must contain only implementations of the
* javax.xml.stream.Namespace interface.
*
* <p>A Namespace isA Attribute. One
* can iterate over a list of namespaces as a list of attributes.
* However this method returns only the list of namespaces
* declared on this START_ELEMENT and does not
* include the attributes declared on this START_ELEMENT.
*
* Returns an empty iterator if there are no namespaces.
*
* @return a readonly Iterator over Namespace interfaces, or an
* empty iterator
*
*/
public Iterator getNamespaces();
/**
* Returns the attribute referred to by this name
* @param name the qname of the desired name
* @return the attribute corresponding to the name value or null
*/
public Attribute getAttributeByName(QName name);
/**
* Gets a read-only namespace context. If no context is
* available this method will return an empty namespace context.
* The NamespaceContext contains information about all namespaces
* in scope for this StartElement.
*
* @return the current namespace context
*/
public NamespaceContext getNamespaceContext();
/**
* Gets the value that the prefix is bound to in the
* context of this element. Returns null if
* the prefix is not bound in this context
* @param prefix the prefix to lookup
* @return the uri bound to the prefix or null
*/
public String getNamespaceURI(String prefix);
}

View file

@ -0,0 +1,177 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.events;
import java.io.Writer;
import javax.xml.namespace.QName;
/**
* This is the base event interface for handling markup events.
* Events are value objects that are used to communicate the
* XML 1.0 InfoSet to the Application. Events may be cached
* and referenced after the parse has completed.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see javax.xml.stream.XMLEventReader
* @see Characters
* @see ProcessingInstruction
* @see StartElement
* @see EndElement
* @see StartDocument
* @see EndDocument
* @see EntityReference
* @see EntityDeclaration
* @see NotationDeclaration
* @since 1.6
*/
public interface XMLEvent extends javax.xml.stream.XMLStreamConstants {
/**
* Returns an integer code for this event.
* @see #START_ELEMENT
* @see #END_ELEMENT
* @see #CHARACTERS
* @see #ATTRIBUTE
* @see #NAMESPACE
* @see #PROCESSING_INSTRUCTION
* @see #COMMENT
* @see #START_DOCUMENT
* @see #END_DOCUMENT
* @see #DTD
*/
public int getEventType();
/**
* Return the location of this event. The Location
* returned from this method is non-volatile and
* will retain its information.
* @see javax.xml.stream.Location
*/
javax.xml.stream.Location getLocation();
/**
* A utility function to check if this event is a StartElement.
* @see StartElement
*/
public boolean isStartElement();
/**
* A utility function to check if this event is an Attribute.
* @see Attribute
*/
public boolean isAttribute();
/**
* A utility function to check if this event is a Namespace.
* @see Namespace
*/
public boolean isNamespace();
/**
* A utility function to check if this event is a EndElement.
* @see EndElement
*/
public boolean isEndElement();
/**
* A utility function to check if this event is an EntityReference.
* @see EntityReference
*/
public boolean isEntityReference();
/**
* A utility function to check if this event is a ProcessingInstruction.
* @see ProcessingInstruction
*/
public boolean isProcessingInstruction();
/**
* A utility function to check if this event is Characters.
* @see Characters
*/
public boolean isCharacters();
/**
* A utility function to check if this event is a StartDocument.
* @see StartDocument
*/
public boolean isStartDocument();
/**
* A utility function to check if this event is an EndDocument.
* @see EndDocument
*/
public boolean isEndDocument();
/**
* Returns this event as a start element event, may result in
* a class cast exception if this event is not a start element.
*/
public StartElement asStartElement();
/**
* Returns this event as an end element event, may result in
* a class cast exception if this event is not a end element.
*/
public EndElement asEndElement();
/**
* Returns this event as Characters, may result in
* a class cast exception if this event is not Characters.
*/
public Characters asCharacters();
/**
* This method is provided for implementations to provide
* optional type information about the associated event.
* It is optional and will return null if no information
* is available.
*/
public QName getSchemaType();
/**
* This method will write the XMLEvent as per the XML 1.0 specification as Unicode characters.
* No indentation or whitespace should be outputted.
*
* Any user defined event type SHALL have this method
* called when being written to on an output stream.
* Built in Event types MUST implement this method,
* but implementations MAY choose not call these methods
* for optimizations reasons when writing out built in
* Events to an output stream.
* The output generated MUST be equivalent in terms of the
* infoset expressed.
*
* @param writer The writer that will output the data
* @throws XMLStreamException if there is a fatal error writing the event
*/
public void writeAsEncodedUnicode(Writer writer)
throws javax.xml.stream.XMLStreamException;
}

View file

@ -0,0 +1,133 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.util;
import javax.xml.namespace.QName;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.events.XMLEvent;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamException;
/**
* This is the base class for deriving an XMLEventReader
* filter.
*
* This class is designed to sit between an XMLEventReader and an
* application's XMLEventReader. By default each method
* does nothing but call the corresponding method on the
* parent interface.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see javax.xml.stream.XMLEventReader
* @see StreamReaderDelegate
* @since 1.6
*/
public class EventReaderDelegate implements XMLEventReader {
private XMLEventReader reader;
/**
* Construct an empty filter with no parent.
*/
public EventReaderDelegate(){}
/**
* Construct an filter with the specified parent.
* @param reader the parent
*/
public EventReaderDelegate(XMLEventReader reader) {
this.reader = reader;
}
/**
* Set the parent of this instance.
* @param reader the new parent
*/
public void setParent(XMLEventReader reader) {
this.reader = reader;
}
/**
* Get the parent of this instance.
* @return the parent or null if none is set
*/
public XMLEventReader getParent() {
return reader;
}
public XMLEvent nextEvent()
throws XMLStreamException
{
return reader.nextEvent();
}
public Object next() {
return reader.next();
}
public boolean hasNext()
{
return reader.hasNext();
}
public XMLEvent peek()
throws XMLStreamException
{
return reader.peek();
}
public void close()
throws XMLStreamException
{
reader.close();
}
public String getElementText()
throws XMLStreamException
{
return reader.getElementText();
}
public XMLEvent nextTag()
throws XMLStreamException
{
return reader.nextTag();
}
public Object getProperty(java.lang.String name)
throws java.lang.IllegalArgumentException
{
return reader.getProperty(name);
}
public void remove() {
reader.remove();
}
}

View file

@ -0,0 +1,286 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.util;
import java.io.Reader;
import javax.xml.namespace.QName;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamException;
/**
* This is the base class for deriving an XMLStreamReader filter
*
* This class is designed to sit between an XMLStreamReader and an
* application's XMLStreamReader. By default each method
* does nothing but call the corresponding method on the
* parent interface.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see javax.xml.stream.XMLStreamReader
* @see EventReaderDelegate
* @since 1.6
*/
public class StreamReaderDelegate implements XMLStreamReader {
private XMLStreamReader reader;
/**
* Construct an empty filter with no parent.
*/
public StreamReaderDelegate(){}
/**
* Construct an filter with the specified parent.
* @param reader the parent
*/
public StreamReaderDelegate(XMLStreamReader reader) {
this.reader = reader;
}
/**
* Set the parent of this instance.
* @param reader the new parent
*/
public void setParent(XMLStreamReader reader) {
this.reader = reader;
}
/**
* Get the parent of this instance.
* @return the parent or null if none is set
*/
public XMLStreamReader getParent() {
return reader;
}
public int next()
throws XMLStreamException
{
return reader.next();
}
public int nextTag()
throws XMLStreamException
{
return reader.nextTag();
}
public String getElementText()
throws XMLStreamException
{
return reader.getElementText();
}
public void require(int type, String namespaceURI, String localName)
throws XMLStreamException
{
reader.require(type,namespaceURI,localName);
}
public boolean hasNext()
throws XMLStreamException
{
return reader.hasNext();
}
public void close()
throws XMLStreamException
{
reader.close();
}
public String getNamespaceURI(String prefix)
{
return reader.getNamespaceURI(prefix);
}
public NamespaceContext getNamespaceContext() {
return reader.getNamespaceContext();
}
public boolean isStartElement() {
return reader.isStartElement();
}
public boolean isEndElement() {
return reader.isEndElement();
}
public boolean isCharacters() {
return reader.isCharacters();
}
public boolean isWhiteSpace() {
return reader.isWhiteSpace();
}
public String getAttributeValue(String namespaceUri,
String localName)
{
return reader.getAttributeValue(namespaceUri,localName);
}
public int getAttributeCount() {
return reader.getAttributeCount();
}
public QName getAttributeName(int index) {
return reader.getAttributeName(index);
}
public String getAttributePrefix(int index) {
return reader.getAttributePrefix(index);
}
public String getAttributeNamespace(int index) {
return reader.getAttributeNamespace(index);
}
public String getAttributeLocalName(int index) {
return reader.getAttributeLocalName(index);
}
public String getAttributeType(int index) {
return reader.getAttributeType(index);
}
public String getAttributeValue(int index) {
return reader.getAttributeValue(index);
}
public boolean isAttributeSpecified(int index) {
return reader.isAttributeSpecified(index);
}
public int getNamespaceCount() {
return reader.getNamespaceCount();
}
public String getNamespacePrefix(int index) {
return reader.getNamespacePrefix(index);
}
public String getNamespaceURI(int index) {
return reader.getNamespaceURI(index);
}
public int getEventType() {
return reader.getEventType();
}
public String getText() {
return reader.getText();
}
public int getTextCharacters(int sourceStart,
char[] target,
int targetStart,
int length)
throws XMLStreamException {
return reader.getTextCharacters(sourceStart,
target,
targetStart,
length);
}
public char[] getTextCharacters() {
return reader.getTextCharacters();
}
public int getTextStart() {
return reader.getTextStart();
}
public int getTextLength() {
return reader.getTextLength();
}
public String getEncoding() {
return reader.getEncoding();
}
public boolean hasText() {
return reader.hasText();
}
public Location getLocation() {
return reader.getLocation();
}
public QName getName() {
return reader.getName();
}
public String getLocalName() {
return reader.getLocalName();
}
public boolean hasName() {
return reader.hasName();
}
public String getNamespaceURI() {
return reader.getNamespaceURI();
}
public String getPrefix() {
return reader.getPrefix();
}
public String getVersion() {
return reader.getVersion();
}
public boolean isStandalone() {
return reader.isStandalone();
}
public boolean standaloneSet() {
return reader.standaloneSet();
}
public String getCharacterEncodingScheme() {
return reader.getCharacterEncodingScheme();
}
public String getPITarget() {
return reader.getPITarget();
}
public String getPIData() {
return reader.getPIData();
}
public Object getProperty(String name) {
return reader.getProperty(name);
}
}

View file

@ -0,0 +1,81 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.util;
import javax.xml.stream.events.XMLEvent;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamException;
/**
* This interface defines a class that allows a user to register
* a way to allocate events given an XMLStreamReader. An implementation
* is not required to use the XMLEventFactory implementation but this
* is recommended. The XMLEventAllocator can be set on an XMLInputFactory
* using the property "javax.xml.stream.allocator"
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @see javax.xml.stream.XMLInputFactory
* @see javax.xml.stream.XMLEventFactory
* @since 1.6
*/
public interface XMLEventAllocator {
/**
* This method creates an instance of the XMLEventAllocator. This
* allows the XMLInputFactory to allocate a new instance per reader.
*/
public XMLEventAllocator newInstance();
/**
* This method allocates an event given the current
* state of the XMLStreamReader. If this XMLEventAllocator
* does not have a one-to-one mapping between reader states
* and events this method will return null. This method
* must not modify the state of the XMLStreamReader.
* @param reader The XMLStreamReader to allocate from
* @return the event corresponding to the current reader state
*/
public XMLEvent allocate(XMLStreamReader reader)
throws XMLStreamException;
/**
* This method allocates an event or set of events
* given the current
* state of the XMLStreamReader and adds the event
* or set of events to the
* consumer that was passed in. This method can be used
* to expand or contract reader states into event states.
* This method may modify the state of the XMLStreamReader.
* @param reader The XMLStreamReader to allocate from
* @param consumer The XMLEventConsumer to add to.
*/
public void allocate(XMLStreamReader reader, XMLEventConsumer consumer)
throws XMLStreamException;
}

View file

@ -0,0 +1,57 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
/*
* Copyright (c) 2003 by BEA Systems, Inc. All Rights Reserved.
*/
package javax.xml.stream.util;
import javax.xml.stream.events.XMLEvent;
import javax.xml.stream.XMLStreamException;
/**
* This interface defines an event consumer interface. The contract of the
* of a consumer is to accept the event. This interface can be used to
* mark an object as able to receive events. Add may be called several
* times in immediate succession so a consumer must be able to cache
* events it hasn't processed yet.
*
* @author Copyright (c) 2003 by BEA Systems. All Rights Reserved.
* @since 1.6
*/
public interface XMLEventConsumer {
/**
* This method adds an event to the consumer. Calling this method
* invalidates the event parameter. The client application should
* discard all references to this event upon calling add.
* The behavior of an application that continues to use such references
* is undefined.
*
* @param event the event to add, may not be null
*/
public void add(XMLEvent event)
throws XMLStreamException;
}

View file

@ -0,0 +1,117 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
/**
* <p>To provide customized error handling, implement this interface and
* use the <code>setErrorListener</code> method to register an instance of the
* implmentation with the {@link javax.xml.transform.Transformer}. The
* <code>Transformer</code> then reports all errors and warnings through this
* interface.</p>
*
* <p>If an application does <em>not</em> register its own custom
* <code>ErrorListener</code>, the default <code>ErrorListener</code>
* is used which reports all warnings and errors to <code>System.err</code>
* and does not throw any <code>Exception</code>s.
* Applications are <em>strongly</em> encouraged to register and use
* <code>ErrorListener</code>s that insure proper behavior for warnings and
* errors.</p>
*
* <p>For transformation errors, a <code>Transformer</code> must use this
* interface instead of throwing an <code>Exception</code>: it is up to the
* application to decide whether to throw an <code>Exception</code> for
* different types of errors and warnings. Note however that the
* <code>Transformer</code> is not required to continue with the transformation
* after a call to {@link #fatalError(TransformerException exception)}.</p>
*
* <p><code>Transformer</code>s may use this mechanism to report XML parsing
* errors as well as transformation errors.</p>
*/
public interface ErrorListener {
/**
* Receive notification of a warning.
*
* <p>{@link javax.xml.transform.Transformer} can use this method to report
* conditions that are not errors or fatal errors. The default behaviour
* is to take no action.</p>
*
* <p>After invoking this method, the Transformer must continue with
* the transformation. It should still be possible for the
* application to process the document through to the end.</p>
*
* @param exception The warning information encapsulated in a
* transformer exception.
*
* @throws javax.xml.transform.TransformerException if the application
* chooses to discontinue the transformation.
*
* @see javax.xml.transform.TransformerException
*/
public abstract void warning(TransformerException exception)
throws TransformerException;
/**
* Receive notification of a recoverable error.
*
* <p>The transformer must continue to try and provide normal transformation
* after invoking this method. It should still be possible for the
* application to process the document through to the end if no other errors
* are encountered.</p>
*
* @param exception The error information encapsulated in a
* transformer exception.
*
* @throws javax.xml.transform.TransformerException if the application
* chooses to discontinue the transformation.
*
* @see javax.xml.transform.TransformerException
*/
public abstract void error(TransformerException exception)
throws TransformerException;
/**
* <p>Receive notification of a non-recoverable error.</p>
*
* <p>The processor may choose to continue, but will not normally
* proceed to a successful completion.</p>
*
* <p>The method should throw an exception if it is unable to
* process the error, or if it wishes execution to terminate
* immediately. The processor will not necessarily honor this
* request.</p>
*
* @param exception The error information encapsulated in a
* <code>TransformerException</code>.
*
* @throws javax.xml.transform.TransformerException if the application
* chooses to discontinue the transformation.
*
* @see javax.xml.transform.TransformerException
*/
public abstract void fatalError(TransformerException exception)
throws TransformerException;
}

View file

@ -0,0 +1,320 @@
/*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
/**
* <p>Implements pluggable Datatypes.</p>
*
* <p>This class is duplicated for each JAXP subpackage so keep it in
* sync. It is package private for secure class loading.</p>
*
* @author Santiago.PericasGeertsen@sun.com
*/
class FactoryFinder {
/**
* Internal debug flag.
*/
private static boolean debug = false;
/**
* Cache for properties in java.home/lib/jaxp.properties
*/
static Properties cacheProps = new Properties();
/**
* Flag indicating if properties from java.home/lib/jaxp.properties
* have been cached.
*/
static boolean firstTime = true;
/**
* Security support class use to check access control before
* getting certain system resources.
*/
static SecuritySupport ss = new SecuritySupport();
// Define system property "jaxp.debug" to get output
static {
// Use try/catch block to support applets, which throws
// SecurityException out of this code.
try {
String val = ss.getSystemProperty("jaxp.debug");
// Allow simply setting the prop to turn on debug
debug = val != null && !"false".equals(val);
}
catch (SecurityException se) {
debug = false;
}
}
private static void dPrint(String msg) {
if (debug) {
System.err.println("JAXP: " + msg);
}
}
/**
* Attempt to load a class using the class loader supplied. If that fails
* and fall back is enabled, the current (i.e. bootstrap) class loader is
* tried.
*
* If the class loader supplied is <code>null</code>, first try using the
* context class loader followed by the current (i.e. bootstrap) class
* loader.
*/
static private Class getProviderClass(String className, ClassLoader cl,
boolean doFallback) throws ClassNotFoundException
{
try {
if (cl == null) {
cl = ss.getContextClassLoader();
if (cl == null) {
throw new ClassNotFoundException();
}
else {
return cl.loadClass(className);
}
}
else {
return cl.loadClass(className);
}
}
catch (ClassNotFoundException e1) {
if (doFallback) {
// Use current class loader - should always be bootstrap CL
return Class.forName(className, true, FactoryFinder.class.getClassLoader());
}
else {
throw e1;
}
}
}
/**
* Create an instance of a class. Delegates to method
* <code>getProviderClass()</code> in order to load the class.
*
* @param className Name of the concrete class corresponding to the
* service provider
*
* @param cl ClassLoader to use to load the class, null means to use
* the bootstrap ClassLoader
*
* @param doFallback True if the current ClassLoader should be tried as
* a fallback if the class is not found using cl
*/
static Object newInstance(String className, ClassLoader cl, boolean doFallback)
throws ConfigurationError
{
try {
Class providerClass = getProviderClass(className, cl, doFallback);
Object instance = providerClass.newInstance();
if (debug) { // Extra check to avoid computing cl strings
dPrint("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);
}
}
/**
* Finds the implementation Class object in the specified order. Main
* entry point.
* @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.
*
* Package private so this code can be shared.
*/
static Object find(String factoryId, String fallbackClassName)
throws ConfigurationError
{
dPrint("find factoryId =" + factoryId);
// Use the system property first
try {
String systemProp = ss.getSystemProperty(factoryId);
if (systemProp != null) {
dPrint("found system property, value=" + systemProp);
return newInstance(systemProp, null, true);
}
}
catch (SecurityException se) {
if (debug) se.printStackTrace();
}
// try to read from $java.home/lib/jaxp.properties
try {
String factoryClassName = null;
if (firstTime) {
synchronized (cacheProps) {
if (firstTime) {
String configFile = ss.getSystemProperty("java.home") + File.separator +
"lib" + File.separator + "jaxp.properties";
File f = new File(configFile);
firstTime = false;
if (ss.doesFileExist(f)) {
dPrint("Read properties file "+f);
cacheProps.load(ss.getFileInputStream(f));
}
}
}
}
factoryClassName = cacheProps.getProperty(factoryId);
if (factoryClassName != null) {
dPrint("found in $java.home/jaxp.properties, value=" + factoryClassName);
return newInstance(factoryClassName, null, true);
}
}
catch (Exception ex) {
if (debug) ex.printStackTrace();
}
// 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);
}
dPrint("loaded from fallback value: " + fallbackClassName);
return newInstance(fallbackClassName, null, true);
}
/*
* 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
{
String serviceId = "META-INF/services/" + factoryId;
InputStream is = null;
// First try the Context ClassLoader
ClassLoader cl = ss.getContextClassLoader();
if (cl != null) {
is = ss.getResourceAsStream(cl, serviceId);
// If no provider found then try the current ClassLoader
if (is == null) {
cl = FactoryFinder.class.getClassLoader();
is = ss.getResourceAsStream(cl, serviceId);
}
} else {
// No Context ClassLoader, try the current ClassLoader
cl = FactoryFinder.class.getClassLoader();
is = ss.getResourceAsStream(cl, serviceId);
}
if (is == null) {
// No provider found
return null;
}
if (debug) { // Extra check to avoid computing cl strings
dPrint("found jar resource=" + serviceId + " using ClassLoader: " + cl);
}
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
}
catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is));
}
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)) {
dPrint("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;
}
static class ConfigurationError extends Error {
private Exception exception;
/**
* Construct a new instance with the specified detail string and
* exception.
*/
ConfigurationError(String msg, Exception x) {
super(msg);
this.exception = x;
}
Exception getException() {
return exception;
}
}
}

View file

@ -0,0 +1,200 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
/**
* Provides string constants that can be used to set
* output properties for a Transformer, or to retrieve
* output properties from a Transformer or Templates object.
* <p>All the fields in this class are read-only.</p>
*
* @see <a href="http://www.w3.org/TR/xslt#output">
* section 16 of the XSL Transformations (XSLT) W3C Recommendation</a>
*/
public class OutputKeys {
/**
* Default constructor is private on purpose. This class is
* only for static variable access, and should never be constructed.
*/
private OutputKeys() { }
/**
* method = "xml" | "html" | "text" | <var>expanded name</var>.
*
* <p>The value of the method property identifies the overall method that
* should be used for outputting the result tree. Other non-namespaced
* values may be used, such as "xhtml", but, if accepted, the handling
* of such values is implementation defined. If any of the method values
* are not accepted and are not namespace qualified,
* then {@link javax.xml.transform.Transformer#setOutputProperty}
* or {@link javax.xml.transform.Transformer#setOutputProperties} will
* throw a {@link java.lang.IllegalArgumentException}.</p>
*
* @see <a href="http://www.w3.org/TR/xslt#output">
* section 16 of the XSL Transformations (XSLT) W3C Recommendation</a>
*/
public static final String METHOD = "method";
/**
* version = <var>nmtoken</var>.
*
* <p><code>version</code> specifies the version of the output
* method.</p>
* <p>When the output method is "xml", the version value specifies the
* version of XML to be used for outputting the result tree. The default
* value for the xml output method is 1.0. When the output method is
* "html", the version value indicates the version of the HTML.
* The default value for the xml output method is 4.0, which specifies
* that the result should be output as HTML conforming to the HTML 4.0
* Recommendation [HTML]. If the output method is "text", the version
* property is ignored.</p>
* @see <a href="http://www.w3.org/TR/xslt#output">
* section 16 of the XSL Transformations (XSLT) W3C Recommendation</a>
*/
public static final String VERSION = "version";
/**
* encoding = <var>string</var>.
*
* <p><code>encoding</code> specifies the preferred character
* encoding that the Transformer should use to encode sequences of
* characters as sequences of bytes. The value of the encoding property should be
* treated case-insensitively. The value must only contain characters in
* the range #x21 to #x7E (i.e., printable ASCII characters). The value
* should either be a <code>charset</code> registered with the Internet
* Assigned Numbers Authority <a href="http://www.iana.org/">[IANA]</a>,
* <a href="http://www.ietf.org/rfc/rfc2278.txt">[RFC2278]</a>
* or start with <code>X-</code>.</p>
* @see <a href="http://www.w3.org/TR/xslt#output">
* section 16 of the XSL Transformations (XSLT) W3C Recommendation</a>
*/
public static final String ENCODING = "encoding";
/**
* omit-xml-declaration = "yes" | "no".
*
* <p><code>omit-xml-declaration</code> specifies whether the XSLT
* processor should output an XML declaration; the value must be
* <code>yes</code> or <code>no</code>.</p>
* @see <a href="http://www.w3.org/TR/xslt#output">
* section 16 of the XSL Transformations (XSLT) W3C Recommendation</a>
*/
public static final String OMIT_XML_DECLARATION = "omit-xml-declaration";
/**
* standalone = "yes" | "no".
*
* <p><code>standalone</code> specifies whether the Transformer
* should output a standalone document declaration; the value must be
* <code>yes</code> or <code>no</code>.</p>
* @see <a href="http://www.w3.org/TR/xslt#output">
* section 16 of the XSL Transformations (XSLT) W3C Recommendation</a>
*/
public static final String STANDALONE = "standalone";
/**
* doctype-public = <var>string</var>.
* <p>See the documentation for the {@link #DOCTYPE_SYSTEM} property
* for a description of what the value of the key should be.</p>
*
* @see <a href="http://www.w3.org/TR/xslt#output">
* section 16 of the XSL Transformations (XSLT) W3C Recommendation</a>
*/
public static final String DOCTYPE_PUBLIC = "doctype-public";
/**
* doctype-system = <var>string</var>.
* <p><code>doctype-system</code> specifies the system identifier
* to be used in the document type declaration.</p>
* <p>If the doctype-system property is specified, the xml output method
* should output a document type declaration immediately before the first
* element. The name following &lt;!DOCTYPE should be the name of the first
* element. If doctype-public property is also specified, then the xml
* output method should output PUBLIC followed by the public identifier
* and then the system identifier; otherwise, it should output SYSTEM
* followed by the system identifier. The internal subset should be empty.
* The value of the doctype-public property should be ignored unless the doctype-system
* property is specified.</p>
* <p>If the doctype-public or doctype-system properties are specified,
* then the html output method should output a document type declaration
* immediately before the first element. The name following &lt;!DOCTYPE
* should be HTML or html. If the doctype-public property is specified,
* then the output method should output PUBLIC followed by the specified
* public identifier; if the doctype-system property is also specified,
* it should also output the specified system identifier following the
* public identifier. If the doctype-system property is specified but
* the doctype-public property is not specified, then the output method
* should output SYSTEM followed by the specified system identifier.</p>
*
* <p><code>doctype-system</code> specifies the system identifier
* to be used in the document type declaration.</p>
* @see <a href="http://www.w3.org/TR/xslt#output">
* section 16 of the XSL Transformations (XSLT) W3C Recommendation</a>
*/
public static final String DOCTYPE_SYSTEM = "doctype-system";
/**
* cdata-section-elements = <var>expanded names</var>.
*
* <p><code>cdata-section-elements</code> specifies a whitespace delimited
* list of the names of elements whose text node children should be output
* using CDATA sections. Note that these names must use the format
* described in the section Qualfied Name Representation in
* {@link javax.xml.transform}.</p>
*
* @see <a href="http://www.w3.org/TR/xslt#output">
* section 16 of the XSL Transformations (XSLT) W3C Recommendation.</a>
*/
public static final String CDATA_SECTION_ELEMENTS =
"cdata-section-elements";
/**
* indent = "yes" | "no".
*
* <p><code>indent</code> specifies whether the Transformer may
* add additional whitespace when outputting the result tree; the value
* must be <code>yes</code> or <code>no</code>. </p>
* @see <a href="http://www.w3.org/TR/xslt#output">
* section 16 of the XSL Transformations (XSLT) W3C Recommendation</a>
*/
public static final String INDENT = "indent";
/**
* media-type = <var>string</var>.
*
* <p><code>media-type</code> specifies the media type (MIME
* content type) of the data that results from outputting the result
* tree. The <code>charset</code> parameter should not be specified
* explicitly; instead, when the top-level media type is
* <code>text</code>, a <code>charset</code> parameter should be added
* according to the character encoding actually used by the output
* method. </p>
* @see <a href="http://www.w3.org/TR/xslt#output">s
* ection 16 of the XSL Transformations (XSLT) W3C Recommendation</a>
*/
public static final String MEDIA_TYPE = "media-type";
}

View file

@ -0,0 +1,86 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
/**
* <p>An object that implements this interface contains the information
* needed to build a transformation result tree.</p>
*
* @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
*/
public interface Result {
/**
* The name of the processing instruction that is sent if the
* result tree disables output escaping.
*
* <p>Normally, result tree serialization escapes & and < (and
* possibly other characters) when outputting text nodes.
* This ensures that the output is well-formed XML. However,
* it is sometimes convenient to be able to produce output that is
* almost, but not quite well-formed XML; for example,
* the output may include ill-formed sections that will
* be transformed into well-formed XML by a subsequent non-XML aware
* process. If a processing instruction is sent with this name,
* serialization should be output without any escaping. </p>
*
* <p>Result DOM trees may also have PI_DISABLE_OUTPUT_ESCAPING and
* PI_ENABLE_OUTPUT_ESCAPING inserted into the tree.</p>
*
* @see <a href="http://www.w3.org/TR/xslt#disable-output-escaping">disable-output-escaping in XSLT Specification</a>
*/
public static final String PI_DISABLE_OUTPUT_ESCAPING =
"javax.xml.transform.disable-output-escaping";
/**
* The name of the processing instruction that is sent
* if the result tree enables output escaping at some point after having
* received a PI_DISABLE_OUTPUT_ESCAPING processing instruction.
*
* @see <a href="http://www.w3.org/TR/xslt#disable-output-escaping">disable-output-escaping in XSLT Specification</a>
*/
public static final String PI_ENABLE_OUTPUT_ESCAPING =
"javax.xml.transform.enable-output-escaping";
/**
* Set the system identifier for this Result.
*
* <p>If the Result is not to be written to a file, the system identifier is optional.
* The application may still want to provide one, however, for use in error messages
* and warnings, or to resolve relative output identifiers.</p>
*
* @param systemId The system identifier as a URI string.
*/
public void setSystemId(String systemId);
/**
* Get the system identifier that was set with setSystemId.
*
* @return The system identifier that was set with setSystemId,
* or null if setSystemId was not called.
*/
public String getSystemId();
}

View file

@ -0,0 +1,108 @@
/*
* Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
import java.security.*;
import java.net.*;
import java.io.*;
import java.util.*;
/**
* 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 SecuritySupport {
ClassLoader getContextClassLoader() throws SecurityException{
return (ClassLoader)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ClassLoader cl = null;
//try {
cl = Thread.currentThread().getContextClassLoader();
//} catch (SecurityException ex) { }
if (cl == null)
cl = ClassLoader.getSystemClassLoader();
return cl;
}
});
}
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 doesFileExist(final File f) {
return ((Boolean)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return new Boolean(f.exists());
}
})).booleanValue();
}
}

View file

@ -0,0 +1,53 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
/**
* An object that implements this interface contains the information
* needed to act as source input (XML source or transformation instructions).
*/
public interface Source {
/**
* Set the system identifier for this Source.
*
* <p>The system identifier is optional if the source does not
* get its data from a URL, but it may still be useful to provide one.
* The application can use a system identifier, for example, to resolve
* relative URIs and to include in error messages and warnings.</p>
*
* @param systemId The system identifier as a URL string.
*/
public void setSystemId(String systemId);
/**
* Get the system identifier that was set with setSystemId.
*
* @return The system identifier that was set with setSystemId, or null
* if setSystemId was not called.
*/
public String getSystemId();
}

View file

@ -0,0 +1,96 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
/**
* This interface is primarily for the purposes of reporting where
* an error occurred in the XML source or transformation instructions.
*/
public interface SourceLocator {
/**
* Return the public identifier for the current document event.
*
* <p>The return value is the public identifier of the document
* entity or of the external parsed entity in which the markup that
* triggered the event appears.</p>
*
* @return A string containing the public identifier, or
* null if none is available.
* @see #getSystemId
*/
public String getPublicId();
/**
* Return the system identifier for the current document event.
*
* <p>The return value is the system identifier of the document
* entity or of the external parsed entity in which the markup that
* triggered the event appears.</p>
*
* <p>If the system identifier is a URL, the parser must resolve it
* fully before passing it to the application.</p>
*
* @return A string containing the system identifier, or null
* if none is available.
* @see #getPublicId
*/
public String getSystemId();
/**
* Return the line number where the current document event ends.
*
* <p><strong>Warning:</strong> The return value from the method
* is intended only as an approximation for the sake of error
* reporting; it is not intended to provide sufficient information
* to edit the character content of the original XML document.</p>
*
* <p>The return value is an approximation of the line number
* in the document entity or external parsed entity where the
* markup that triggered the event appears.</p>
*
* @return The line number, or -1 if none is available.
* @see #getColumnNumber
*/
public int getLineNumber();
/**
* Return the character position where the current document event ends.
*
* <p><strong>Warning:</strong> The return value from the method
* is intended only as an approximation for the sake of error
* reporting; it is not intended to provide sufficient information
* to edit the character content of the original XML document.</p>
*
* <p>The return value is an approximation of the column number
* in the document entity or external parsed entity where the
* markup that triggered the event appears.</p>
*
* @return The column number, or -1 if none is available.
* @see #getLineNumber
*/
public int getColumnNumber();
}

View file

@ -0,0 +1,82 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
import java.util.Properties;
/**
* An object that implements this interface is the runtime representation of processed
* transformation instructions.
*
* <p>Templates must be threadsafe for a given instance
* over multiple threads running concurrently, and may
* be used multiple times in a given session.</p>
*/
public interface Templates {
/**
* Create a new transformation context for this Templates object.
*
* @return A valid non-null instance of a Transformer.
*
* @throws TransformerConfigurationException if a Transformer can not be created.
*/
Transformer newTransformer() throws TransformerConfigurationException;
/**
* Get the properties corresponding to the effective xsl:output element.
* The object returned will
* be a clone of the internal values. Accordingly, it can be mutated
* without mutating the Templates object, and then handed in to
* {@link javax.xml.transform.Transformer#setOutputProperties}.
*
* <p>The properties returned should contain properties set by the stylesheet,
* and these properties are "defaulted" by default properties specified by
* <a href="http://www.w3.org/TR/xslt#output">section 16 of the
* XSL Transformations (XSLT) W3C Recommendation</a>. The properties that
* were specifically set by the stylesheet should be in the base
* Properties list, while the XSLT default properties that were not
* specifically set should be in the "default" Properties list. Thus,
* getOutputProperties().getProperty(String key) will obtain any
* property in that was set by the stylesheet, <em>or</em> the default
* properties, while
* getOutputProperties().get(String key) will only retrieve properties
* that were explicitly set in the stylesheet.</p>
*
* <p>For XSLT,
* <a href="http://www.w3.org/TR/xslt#attribute-value-templates">Attribute
* Value Templates</a> attribute values will
* be returned unexpanded (since there is no context at this point). The
* namespace prefixes inside Attribute Value Templates will be unexpanded,
* so that they remain valid XPath values.</p>
*
* @return A Properties object, never null.
*/
Properties getOutputProperties();
}

View file

@ -0,0 +1,339 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
import java.util.Properties;
/**
* An instance of this abstract class can transform a
* source tree into a result tree.
*
* <p>An instance of this class can be obtained with the
* {@link TransformerFactory#newTransformer TransformerFactory.newTransformer}
* method. This instance may then be used to process XML from a
* variety of sources and write the transformation output to a
* variety of sinks.</p>
*
* <p>An object of this class may not be used in multiple threads
* running concurrently. Different Transformers may be used
* concurrently by different threads.</p>
*
* <p>A <code>Transformer</code> may be used multiple times. Parameters and
* output properties are preserved across transformations.</p>
*
* @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
*/
public abstract class Transformer {
/**
* Default constructor is protected on purpose.
*/
protected Transformer() { }
/**
* <p>Reset this <code>Transformer</code> to its original configuration.</p>
*
* <p><code>Transformer</code> is reset to the same state as when it was created with
* {@link TransformerFactory#newTransformer()},
* {@link TransformerFactory#newTransformer(Source source)} or
* {@link Templates#newTransformer()}.
* <code>reset()</code> is designed to allow the reuse of existing <code>Transformer</code>s
* thus saving resources associated with the creation of new <code>Transformer</code>s.</p>
*
* <p>The reset <code>Transformer</code> is not guaranteed to have the same {@link URIResolver}
* or {@link ErrorListener} <code>Object</code>s, e.g. {@link Object#equals(Object obj)}.
* It is guaranteed to have a functionally equal <code>URIResolver</code>
* and <code>ErrorListener</code>.</p>
*
* @throws UnsupportedOperationException When implementation does not
* override this method.
*
* @since 1.5
*/
public void reset() {
// implementors should override this method
throw new UnsupportedOperationException(
"This Transformer, \"" + this.getClass().getName() + "\", does not support the reset functionality."
+ " Specification \"" + this.getClass().getPackage().getSpecificationTitle() + "\""
+ " version \"" + this.getClass().getPackage().getSpecificationVersion() + "\""
);
}
/**
* <p>Transform the XML <code>Source</code> to a <code>Result</code>.
* Specific transformation behavior is determined by the settings of the
* <code>TransformerFactory</code> in effect when the
* <code>Transformer</code> was instantiated and any modifications made to
* the <code>Transformer</code> instance.</p>
*
* <p>An empty <code>Source</code> is represented as an empty document
* as constructed by {@link javax.xml.parsers.DocumentBuilder#newDocument()}.
* The result of transforming an empty <code>Source</code> depends on
* the transformation behavior; it is not always an empty
* <code>Result</code>.</p>
*
* @param xmlSource The XML input to transform.
* @param outputTarget The <code>Result</code> of transforming the
* <code>xmlSource</code>.
*
* @throws TransformerException If an unrecoverable error occurs
* during the course of the transformation.
*/
public abstract void transform(Source xmlSource, Result outputTarget)
throws TransformerException;
/**
* Add a parameter for the transformation.
*
* <p>Pass a qualified name as a two-part string, the namespace URI
* enclosed in curly braces ({}), followed by the local name. If the
* name has a null URL, the String only contain the local name. An
* application can safely check for a non-null URI by testing to see if the
* first character of the name is a '{' character.</p>
* <p>For example, if a URI and local name were obtained from an element
* defined with &lt;xyz:foo
* xmlns:xyz="http://xyz.foo.com/yada/baz.html"/&gt;,
* then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo".
* Note that no prefix is used.</p>
*
* @param name The name of the parameter, which may begin with a
* namespace URI in curly braces ({}).
* @param value The value object. This can be any valid Java object. It is
* up to the processor to provide the proper object coersion or to simply
* pass the object on for use in an extension.
*
* @throws NullPointerException If value is null.
*/
public abstract void setParameter(String name, Object value);
/**
* Get a parameter that was explicitly set with setParameter.
*
* <p>This method does not return a default parameter value, which
* cannot be determined until the node context is evaluated during
* the transformation process.
*
* @param name of <code>Object</code> to get
*
* @return A parameter that has been set with setParameter.
*/
public abstract Object getParameter(String name);
/**
* <p>Set a list of parameters.</p>
*
* <p>Note that the list of parameters is specified as a
* <code>Properties</code> <code>Object</code> which limits the parameter
* values to <code>String</code>s. Multiple calls to
* {@link #setParameter(String name, Object value)} should be used when the
* desired values are non-<code>String</code> <code>Object</code>s.
* The parameter names should conform as specified in
* {@link #setParameter(String name, Object value)}.
* An <code>IllegalArgumentException</code> is thrown if any names do not
* conform.</p>
*
* <p>New parameters in the list are added to any existing parameters.
* If the name of a new parameter is equal to the name of an existing
* parameter as determined by {@link java.lang.Object#equals(Object obj)},
* the existing parameter is set to the new value.</p>
*
* @param params Parameters to set.
*
* @throws IllegalArgumentException If any parameter names do not conform
* to the naming rules.
*/
/**
* Clear all parameters set with setParameter.
*/
public abstract void clearParameters();
/**
* Set an object that will be used to resolve URIs used in
* document().
*
* <p>If the resolver argument is null, the URIResolver value will
* be cleared and the transformer will no longer have a resolver.</p>
*
* @param resolver An object that implements the URIResolver interface,
* or null.
*/
public abstract void setURIResolver(URIResolver resolver);
/**
* Get an object that will be used to resolve URIs used in
* document().
*
* @return An object that implements the URIResolver interface,
* or null.
*/
public abstract URIResolver getURIResolver();
/**
* Set the output properties for the transformation. These
* properties will override properties set in the Templates
* with xsl:output.
*
* <p>If argument to this function is null, any properties
* previously set are removed, and the value will revert to the value
* defined in the templates object.</p>
*
* <p>Pass a qualified property key name as a two-part string, the namespace
* URI enclosed in curly braces ({}), followed by the local name. If the
* name has a null URL, the String only contain the local name. An
* application can safely check for a non-null URI by testing to see if the
* first character of the name is a '{' character.</p>
* <p>For example, if a URI and local name were obtained from an element
* defined with &lt;xyz:foo
* xmlns:xyz="http://xyz.foo.com/yada/baz.html"/&gt;,
* then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo".
* Note that no prefix is used.</p>
* An <code>IllegalArgumentException</code> is thrown if any of the
* argument keys are not recognized and are not namespace qualified.
*
* @param oformat A set of output properties that will be
* used to override any of the same properties in affect
* for the transformation.
*
* @throws IllegalArgumentException When keys are not recognized and
* are not namespace qualified.
*
* @see javax.xml.transform.OutputKeys
* @see java.util.Properties
*
*/
public abstract void setOutputProperties(Properties oformat);
/**
* <p>Get a copy of the output properties for the transformation.</p>
*
* <p>The properties returned should contain properties set by the user,
* and properties set by the stylesheet, and these properties
* are "defaulted" by default properties specified by
* <a href="http://www.w3.org/TR/xslt#output">section 16 of the
* XSL Transformations (XSLT) W3C Recommendation</a>. The properties that
* were specifically set by the user or the stylesheet should be in the base
* Properties list, while the XSLT default properties that were not
* specifically set should be the default Properties list. Thus,
* getOutputProperties().getProperty(String key) will obtain any
* property in that was set by {@link #setOutputProperty},
* {@link #setOutputProperties}, in the stylesheet, <em>or</em> the default
* properties, while
* getOutputProperties().get(String key) will only retrieve properties
* that were explicitly set by {@link #setOutputProperty},
* {@link #setOutputProperties}, or in the stylesheet.</p>
*
* <p>Note that mutation of the Properties object returned will not
* effect the properties that the transformer contains.</p>
*
* <p>If any of the argument keys are not recognized and are not
* namespace qualified, the property will be ignored and not returned.
* In other words the behaviour is not orthogonal with
* {@link #setOutputProperties setOutputProperties}.</p>
*
* @return A copy of the set of output properties in effect for
* the next transformation.
*
* @see javax.xml.transform.OutputKeys
* @see java.util.Properties
* @see <a href="http://www.w3.org/TR/xslt#output">
* XSL Transformations (XSLT) Version 1.0</a>
*/
public abstract Properties getOutputProperties();
/**
* Set an output property that will be in effect for the
* transformation.
*
* <p>Pass a qualified property name as a two-part string, the namespace URI
* enclosed in curly braces ({}), followed by the local name. If the
* name has a null URL, the String only contain the local name. An
* application can safely check for a non-null URI by testing to see if the
* first character of the name is a '{' character.</p>
* <p>For example, if a URI and local name were obtained from an element
* defined with &lt;xyz:foo
* xmlns:xyz="http://xyz.foo.com/yada/baz.html"/&gt;,
* then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo".
* Note that no prefix is used.</p>
*
* <p>The Properties object that was passed to {@link #setOutputProperties}
* won't be effected by calling this method.</p>
*
* @param name A non-null String that specifies an output
* property name, which may be namespace qualified.
* @param value The non-null string value of the output property.
*
* @throws IllegalArgumentException If the property is not supported, and is
* not qualified with a namespace.
*
* @see javax.xml.transform.OutputKeys
*/
public abstract void setOutputProperty(String name, String value)
throws IllegalArgumentException;
/**
* <p>Get an output property that is in effect for the transformer.</p>
*
* <p>If a property has been set using {@link #setOutputProperty},
* that value will be returned. Otherwise, if a property is explicitly
* specified in the stylesheet, that value will be returned. If
* the value of the property has been defaulted, that is, if no
* value has been set explicitly either with {@link #setOutputProperty} or
* in the stylesheet, the result may vary depending on
* implementation and input stylesheet.</p>
*
* @param name A non-null String that specifies an output
* property name, which may be namespace qualified.
*
* @return The string value of the output property, or null
* if no property was found.
*
* @throws IllegalArgumentException If the property is not supported.
*
* @see javax.xml.transform.OutputKeys
*/
public abstract String getOutputProperty(String name)
throws IllegalArgumentException;
/**
* Set the error event listener in effect for the transformation.
*
* @param listener The new error listener.
*
* @throws IllegalArgumentException if listener is null.
*/
public abstract void setErrorListener(ErrorListener listener)
throws IllegalArgumentException;
/**
* Get the error event handler in effect for the transformation.
* Implementations must provide a default error listener.
*
* @return The current error handler, which should never be null.
*/
public abstract ErrorListener getErrorListener();
}

View file

@ -0,0 +1,102 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
/**
* Indicates a serious configuration error.
*/
public class TransformerConfigurationException extends TransformerException {
/**
* Create a new <code>TransformerConfigurationException</code> with no
* detail mesage.
*/
public TransformerConfigurationException() {
super("Configuration Error");
}
/**
* Create a new <code>TransformerConfigurationException</code> with
* the <code>String </code> specified as an error message.
*
* @param msg The error message for the exception.
*/
public TransformerConfigurationException(String msg) {
super(msg);
}
/**
* Create a new <code>TransformerConfigurationException</code> with a
* given <code>Exception</code> base cause of the error.
*
* @param e The exception to be encapsulated in a
* TransformerConfigurationException.
*/
public TransformerConfigurationException(Throwable e) {
super(e);
}
/**
* Create a new <code>TransformerConfigurationException</code> with the
* given <code>Exception</code> base cause and detail message.
*
* @param e The exception to be encapsulated in a
* TransformerConfigurationException
* @param msg The detail message.
*/
public TransformerConfigurationException(String msg, Throwable e) {
super(msg, e);
}
/**
* Create a new TransformerConfigurationException from a message and a Locator.
*
* <p>This constructor is especially useful when an application is
* creating its own exception from within a DocumentHandler
* callback.</p>
*
* @param message The error or warning message.
* @param locator The locator object for the error or warning.
*/
public TransformerConfigurationException(String message,
SourceLocator locator) {
super(message, locator);
}
/**
* Wrap an existing exception in a TransformerConfigurationException.
*
* @param message The error or warning message, or null to
* use the message from the embedded exception.
* @param locator The locator object for the error or warning.
* @param e Any exception.
*/
public TransformerConfigurationException(String message,
SourceLocator locator,
Throwable e) {
super(message, locator, e);
}
}

View file

@ -0,0 +1,370 @@
/*
* Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
/**
* This class specifies an exceptional condition that occured
* during the transformation process.
*/
public class TransformerException extends Exception {
/** Field locator specifies where the error occured */
SourceLocator locator;
/**
* Method getLocator retrieves an instance of a SourceLocator
* object that specifies where an error occured.
*
* @return A SourceLocator object, or null if none was specified.
*/
public SourceLocator getLocator() {
return locator;
}
/**
* Method setLocator sets an instance of a SourceLocator
* object that specifies where an error occured.
*
* @param location A SourceLocator object, or null to clear the location.
*/
public void setLocator(SourceLocator location) {
locator = location;
}
/** Field containedException specifies a wrapped exception. May be null. */
Throwable containedException;
/**
* This method retrieves an exception that this exception wraps.
*
* @return An Throwable object, or null.
* @see #getCause
*/
public Throwable getException() {
return containedException;
}
/**
* Returns the cause of this throwable or <code>null</code> if the
* cause is nonexistent or unknown. (The cause is the throwable that
* caused this throwable to get thrown.)
*/
public Throwable getCause() {
return ((containedException == this)
? null
: containedException);
}
/**
* Initializes the <i>cause</i> of this throwable to the specified value.
* (The cause is the throwable that caused this throwable to get thrown.)
*
* <p>This method can be called at most once. It is generally called from
* within the constructor, or immediately after creating the
* throwable. If this throwable was created
* with {@link #TransformerException(Throwable)} or
* {@link #TransformerException(String,Throwable)}, this method cannot be called
* even once.
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A <code>null</code> value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @return a reference to this <code>Throwable</code> instance.
* @throws IllegalArgumentException if <code>cause</code> is this
* throwable. (A throwable cannot
* be its own cause.)
* @throws IllegalStateException if this throwable was
* created with {@link #TransformerException(Throwable)} or
* {@link #TransformerException(String,Throwable)}, or this method has already
* been called on this throwable.
*/
public synchronized Throwable initCause(Throwable cause) {
if (this.containedException != null) {
throw new IllegalStateException("Can't overwrite cause");
}
if (cause == this) {
throw new IllegalArgumentException(
"Self-causation not permitted");
}
this.containedException = cause;
return this;
}
/**
* Create a new TransformerException.
*
* @param message The error or warning message.
*/
public TransformerException(String message) {
super(message);
this.containedException = null;
this.locator = null;
}
/**
* Create a new TransformerException wrapping an existing exception.
*
* @param e The exception to be wrapped.
*/
public TransformerException(Throwable e) {
super(e.toString());
this.containedException = e;
this.locator = null;
}
/**
* Wrap an existing exception in a TransformerException.
*
* <p>This is used for throwing processor exceptions before
* the processing has started.</p>
*
* @param message The error or warning message, or null to
* use the message from the embedded exception.
* @param e Any exception
*/
public TransformerException(String message, Throwable e) {
super(((message == null) || (message.length() == 0))
? e.toString()
: message);
this.containedException = e;
this.locator = null;
}
/**
* Create a new TransformerException from a message and a Locator.
*
* <p>This constructor is especially useful when an application is
* creating its own exception from within a DocumentHandler
* callback.</p>
*
* @param message The error or warning message.
* @param locator The locator object for the error or warning.
*/
public TransformerException(String message, SourceLocator locator) {
super(message);
this.containedException = null;
this.locator = locator;
}
/**
* Wrap an existing exception in a TransformerException.
*
* @param message The error or warning message, or null to
* use the message from the embedded exception.
* @param locator The locator object for the error or warning.
* @param e Any exception
*/
public TransformerException(String message, SourceLocator locator,
Throwable e) {
super(message);
this.containedException = e;
this.locator = locator;
}
/**
* Get the error message with location information
* appended.
*
* @return A <code>String</code> representing the error message with
* location information appended.
*/
public String getMessageAndLocation() {
StringBuffer sbuffer = new StringBuffer();
String message = super.getMessage();
if (null != message) {
sbuffer.append(message);
}
if (null != locator) {
String systemID = locator.getSystemId();
int line = locator.getLineNumber();
int column = locator.getColumnNumber();
if (null != systemID) {
sbuffer.append("; SystemID: ");
sbuffer.append(systemID);
}
if (0 != line) {
sbuffer.append("; Line#: ");
sbuffer.append(line);
}
if (0 != column) {
sbuffer.append("; Column#: ");
sbuffer.append(column);
}
}
return sbuffer.toString();
}
/**
* Get the location information as a string.
*
* @return A string with location info, or null
* if there is no location information.
*/
public String getLocationAsString() {
if (null != locator) {
StringBuffer sbuffer = new StringBuffer();
String systemID = locator.getSystemId();
int line = locator.getLineNumber();
int column = locator.getColumnNumber();
if (null != systemID) {
sbuffer.append("; SystemID: ");
sbuffer.append(systemID);
}
if (0 != line) {
sbuffer.append("; Line#: ");
sbuffer.append(line);
}
if (0 != column) {
sbuffer.append("; Column#: ");
sbuffer.append(column);
}
return sbuffer.toString();
} else {
return null;
}
}
/**
* Print the the trace of methods from where the error
* originated. This will trace all nested exception
* objects, as well as this object.
*/
public void printStackTrace() {
printStackTrace(new java.io.PrintWriter(System.err, true));
}
/**
* Print the the trace of methods from where the error
* originated. This will trace all nested exception
* objects, as well as this object.
* @param s The stream where the dump will be sent to.
*/
public void printStackTrace(java.io.PrintStream s) {
printStackTrace(new java.io.PrintWriter(s));
}
/**
* Print the the trace of methods from where the error
* originated. This will trace all nested exception
* objects, as well as this object.
* @param s The writer where the dump will be sent to.
*/
public void printStackTrace(java.io.PrintWriter s) {
if (s == null) {
s = new java.io.PrintWriter(System.err, true);
}
try {
String locInfo = getLocationAsString();
if (null != locInfo) {
s.println(locInfo);
}
super.printStackTrace(s);
} catch (Throwable e) {}
Throwable exception = getException();
for (int i = 0; (i < 10) && (null != exception); i++) {
s.println("---------");
try {
if (exception instanceof TransformerException) {
String locInfo =
((TransformerException) exception)
.getLocationAsString();
if (null != locInfo) {
s.println(locInfo);
}
}
exception.printStackTrace(s);
} catch (Throwable e) {
s.println("Could not print stack trace...");
}
try {
Method meth =
((Object) exception).getClass().getMethod("getException",
(Class[]) null);
if (null != meth) {
Throwable prev = exception;
exception = (Throwable) meth.invoke(exception, (Object[]) null);
if (prev == exception) {
break;
}
} else {
exception = null;
}
} catch (InvocationTargetException ite) {
exception = null;
} catch (IllegalAccessException iae) {
exception = null;
} catch (NoSuchMethodException nsme) {
exception = null;
}
}
// insure output is written
s.flush();
}
}

View file

@ -0,0 +1,382 @@
/*
* Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
/**
* <p>A TransformerFactory instance can be used to create
* {@link javax.xml.transform.Transformer} and
* {@link javax.xml.transform.Templates} objects.</p>
*
* <p>The system property that determines which Factory implementation
* to create is named <code>"javax.xml.transform.TransformerFactory"</code>.
* This property names a concrete subclass of the
* <code>TransformerFactory</code> abstract class. If the property is not
* defined, a platform default is be used.</p>
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @author <a href="mailto:Neeraj.Bajaj@sun.com">Neeraj Bajaj</a>
*
*/
public abstract class TransformerFactory {
/**
* Default constructor is protected on purpose.
*/
protected TransformerFactory() { }
/**
* <p>Obtain a new instance of a <code>TransformerFactory</code>.
* This static method creates a new factory instance
* This method uses the following ordered lookup procedure to determine
* the <code>TransformerFactory</code> implementation class to
* load:</p>
* <ul>
* <li>
* Use the <code>javax.xml.transform.TransformerFactory</code> system
* property.
* </li>
* <li>
* Use the properties file "lib/jaxp.properties" in the JRE directory.
* This configuration file is in standard <code>java.util.Properties
* </code> format and contains the fully qualified name of the
* implementation class with the key being the system property defined
* above.
*
* The jaxp.properties file is read only once by the JAXP implementation
* and it's values are then cached for future use. If the file does not exist
* when the first attempt is made to read from it, no further attempts are
* made to check for its existence. It is not possible to change the value
* of any property in jaxp.properties after it has been read for the first time.
* </li>
* <li>
* Use the Services API (as detailed in the JAR specification), if
* available, to determine the classname. The Services API will look
* for a classname in the file
* <code>META-INF/services/javax.xml.transform.TransformerFactory</code>
* in jars available to the runtime.
* </li>
* <li>
* Platform default <code>TransformerFactory</code> instance.
* </li>
* </ul>
*
* <p>Once an application has obtained a reference to a <code>
* TransformerFactory</code> it can use the factory to configure
* and obtain transformer instances.</p>
*
* @return new TransformerFactory instance, never null.
*
* @throws TransformerFactoryConfigurationError Thrown if the implementation
* is not available or cannot be instantiated.
*/
public static TransformerFactory newInstance()
throws TransformerFactoryConfigurationError {
try {
return (TransformerFactory) FactoryFinder.find(
/* The default property name according to the JAXP spec */
"javax.xml.transform.TransformerFactory",
/* The fallback implementation class name, XSLTC */
"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
} catch (FactoryFinder.ConfigurationError e) {
throw new TransformerFactoryConfigurationError(
e.getException(),
e.getMessage());
}
}
/**
* <p>Obtain a new instance of a <code>TransformerFactory</code> from factory class name.
* This function is useful when there are multiple providers in the classpath.
* It gives more control to the application as it can specify which provider
* should be loaded.</p>
*
* <p>Once an application has obtained a reference to a <code>
* TransformerFactory</code> it can use the factory to configure
* and obtain transformer instances.</p>
*
* <h2>Tip for Trouble-shooting</h2>
* <p>Setting the <code>jaxp.debug</code> system property will cause
* this method to print a lot of debug messages
* to <code>System.err</code> about what it is doing and where it is looking at.</p>
*
* <p> If you have problems try:</p>
* <pre>
* java -Djaxp.debug=1 YourProgram ....
* </pre>
*
* @param factoryClassName fully qualified factory class name that provides implementation of <code>javax.xml.transform.TransformerFactory</code>.
*
* @param classLoader <code>ClassLoader</code> used to load the factory class. If <code>null</code>
* current <code>Thread</code>'s context classLoader is used to load the factory class.
*
* @return new TransformerFactory instance, never null.
*
* @throws TransformerFactoryConfigurationError
* if <code>factoryClassName</code> is <code>null</code>, or
* the factory class cannot be loaded, instantiated.
*
* @see #newInstance()
*
* @since 1.6
*/
public static TransformerFactory newInstance(String factoryClassName, ClassLoader classLoader)
throws TransformerFactoryConfigurationError{
try {
//do not fallback if given classloader can't find the class, throw exception
return (TransformerFactory) FactoryFinder.newInstance(factoryClassName, classLoader, false);
} catch (FactoryFinder.ConfigurationError e) {
throw new TransformerFactoryConfigurationError(
e.getException(),
e.getMessage());
}
}
/**
* <p>Process the <code>Source</code> into a <code>Transformer</code>
* <code>Object</code>. The <code>Source</code> is an XSLT document that
* conforms to <a href="http://www.w3.org/TR/xslt">
* XSL Transformations (XSLT) Version 1.0</a>. Care must
* be taken not to use this <code>Transformer</code> in multiple
* <code>Thread</code>s running concurrently.
* Different <code>TransformerFactories</code> can be used concurrently by
* different <code>Thread</code>s.</p>
*
* @param source <code>Source </code> of XSLT document used to create
* <code>Transformer</code>.
* Examples of XML <code>Source</code>s include
* {@link javax.xml.transform.dom.DOMSource DOMSource},
* {@link javax.xml.transform.sax.SAXSource SAXSource}, and
* {@link javax.xml.transform.stream.StreamSource StreamSource}.
*
* @return A <code>Transformer</code> object that may be used to perform
* a transformation in a single <code>Thread</code>, never
* <code>null</code>.
*
* @throws TransformerConfigurationException Thrown if there are errors when
* parsing the <code>Source</code> or it is not possible to create a
* <code>Transformer</code> instance.
*
* @see <a href="http://www.w3.org/TR/xslt">
* XSL Transformations (XSLT) Version 1.0</a>
*/
public abstract Transformer newTransformer(Source source)
throws TransformerConfigurationException;
/**
* <p>Create a new <code>Transformer</code> that performs a copy
* of the <code>Source</code> to the <code>Result</code>.
* i.e. the "<em>identity transform</em>".</p>
*
* @return A Transformer object that may be used to perform a transformation
* in a single thread, never null.
*
* @throws TransformerConfigurationException When it is not
* possible to create a <code>Transformer</code> instance.
*/
public abstract Transformer newTransformer()
throws TransformerConfigurationException;
/**
* Process the Source into a Templates object, which is a
* a compiled representation of the source. This Templates object
* may then be used concurrently across multiple threads. Creating
* a Templates object allows the TransformerFactory to do detailed
* performance optimization of transformation instructions, without
* penalizing runtime transformation.
*
* @param source An object that holds a URL, input stream, etc.
*
* @return A Templates object capable of being used for transformation
* purposes, never <code>null</code>.
*
* @throws TransformerConfigurationException When parsing to
* construct the Templates object fails.
*/
public abstract Templates newTemplates(Source source)
throws TransformerConfigurationException;
/**
* <p>Get the stylesheet specification(s) associated with the
* XML <code>Source</code> document via the
* <a href="http://www.w3.org/TR/xml-stylesheet/">
* xml-stylesheet processing instruction</a> that match the given criteria.
* Note that it is possible to return several stylesheets, in which case
* they are applied as if they were a list of imports or cascades in a
* single stylesheet.</p>
*
* @param source The XML source document.
* @param media The media attribute to be matched. May be null, in which
* case the prefered templates will be used (i.e. alternate = no).
* @param title The value of the title attribute to match. May be null.
* @param charset The value of the charset attribute to match. May be null.
*
* @return A <code>Source</code> <code>Object</code> suitable for passing
* to the <code>TransformerFactory</code>.
*
* @throws TransformerConfigurationException An <code>Exception</code>
* is thrown if an error occurings during parsing of the
* <code>source</code>.
*
* @see <a href="http://www.w3.org/TR/xml-stylesheet/">
* Associating Style Sheets with XML documents Version 1.0</a>
*/
public abstract Source getAssociatedStylesheet(
Source source,
String media,
String title,
String charset)
throws TransformerConfigurationException;
/**
* Set an object that is used by default during the transformation
* to resolve URIs used in document(), xsl:import, or xsl:include.
*
* @param resolver An object that implements the URIResolver interface,
* or null.
*/
public abstract void setURIResolver(URIResolver resolver);
/**
* Get the object that is used by default during the transformation
* to resolve URIs used in document(), xsl:import, or xsl:include.
*
* @return The URIResolver that was set with setURIResolver.
*/
public abstract URIResolver getURIResolver();
//======= CONFIGURATION METHODS =======
/**
* <p>Set a feature for this <code>TransformerFactory</code> and <code>Transformer</code>s
* or <code>Template</code>s created by this factory.</p>
*
* <p>
* Feature names are fully qualified {@link java.net.URI}s.
* Implementations may define their own features.
* An {@link TransformerConfigurationException} is thrown if this <code>TransformerFactory</code> or the
* <code>Transformer</code>s or <code>Template</code>s it creates cannot support the feature.
* It is possible for an <code>TransformerFactory</code> to expose a feature value but be unable to change its state.
* </p>
*
* <p>All implementations are required to support the {@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} feature.
* When the feature is:</p>
* <ul>
* <li>
* <code>true</code>: the implementation will limit XML processing to conform to implementation limits
* and behave in a secure fashion as defined by the implementation.
* Examples include resolving user defined style sheets and functions.
* If XML processing is limited for security reasons, it will be reported via a call to the registered
* {@link ErrorListener#fatalError(TransformerException exception)}.
* See {@link #setErrorListener(ErrorListener listener)}.
* </li>
* <li>
* <code>false</code>: the implementation will processing XML according to the XML specifications without
* regard to possible implementation limits.
* </li>
* </ul>
*
* @param name Feature name.
* @param value Is feature state <code>true</code> or <code>false</code>.
*
* @throws TransformerConfigurationException if this <code>TransformerFactory</code>
* or the <code>Transformer</code>s or <code>Template</code>s it creates cannot support this feature.
* @throws NullPointerException If the <code>name</code> parameter is null.
*/
public abstract void setFeature(String name, boolean value)
throws TransformerConfigurationException;
/**
* Look up the value of a feature.
*
* <p>
* Feature names are fully qualified {@link java.net.URI}s.
* Implementations may define their own features.
* <code>false</code> is returned if this <code>TransformerFactory</code> or the
* <code>Transformer</code>s or <code>Template</code>s it creates cannot support the feature.
* It is possible for an <code>TransformerFactory</code> to expose a feature value but be unable to change its state.
* </p>
*
* @param name Feature name.
*
* @return The current state of the feature, <code>true</code> or <code>false</code>.
*
* @throws NullPointerException If the <code>name</code> parameter is null.
*/
public abstract boolean getFeature(String name);
/**
* Allows the user to set specific attributes on the underlying
* implementation. An attribute in this context is defined to
* be an option that the implementation provides.
* An <code>IllegalArgumentException</code> is thrown if the underlying
* implementation doesn't recognize the attribute.
*
* @param name The name of the attribute.
* @param value The value of the attribute.
*
* @throws IllegalArgumentException When implementation does not
* recognize the attribute.
*/
public abstract void setAttribute(String name, Object value);
/**
* Allows the user to retrieve specific attributes on the underlying
* implementation.
* An <code>IllegalArgumentException</code> is thrown if the underlying
* implementation doesn't recognize the attribute.
*
* @param name The name of the attribute.
*
* @return value The value of the attribute.
*
* @throws IllegalArgumentException When implementation does not
* recognize the attribute.
*/
public abstract Object getAttribute(String name);
/**
* Set the error event listener for the TransformerFactory, which
* is used for the processing of transformation instructions,
* and not for the transformation itself.
* An <code>IllegalArgumentException</code> is thrown if the
* <code>ErrorListener</code> listener is <code>null</code>.
*
* @param listener The new error listener.
*
* @throws IllegalArgumentException When <code>listener</code> is
* <code>null</code>
*/
public abstract void setErrorListener(ErrorListener listener);
/**
* Get the error event handler for the TransformerFactory.
*
* @return The current error handler, which should never be null.
*/
public abstract ErrorListener getErrorListener();
}

View file

@ -0,0 +1,122 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
/**
* Thrown when a problem with configuration with the Transformer Factories
* exists. This error will typically be thrown when the class of a
* transformation factory specified in the system properties cannot be found
* or instantiated.
*/
public class TransformerFactoryConfigurationError extends Error {
/**
* <code>Exception</code> for the
* <code>TransformerFactoryConfigurationError</code>.
*/
private Exception exception;
/**
* Create a new <code>TransformerFactoryConfigurationError</code> with no
* detail mesage.
*/
public TransformerFactoryConfigurationError() {
super();
this.exception = null;
}
/**
* Create a new <code>TransformerFactoryConfigurationError</code> with
* the <code>String</code> specified as an error message.
*
* @param msg The error message for the exception.
*/
public TransformerFactoryConfigurationError(String msg) {
super(msg);
this.exception = null;
}
/**
* Create a new <code>TransformerFactoryConfigurationError</code> with a
* given <code>Exception</code> base cause of the error.
*
* @param e The exception to be encapsulated in a
* TransformerFactoryConfigurationError.
*/
public TransformerFactoryConfigurationError(Exception e) {
super(e.toString());
this.exception = e;
}
/**
* Create a new <code>TransformerFactoryConfigurationError</code> with the
* given <code>Exception</code> base cause and detail message.
*
* @param e The exception to be encapsulated in a
* TransformerFactoryConfigurationError
* @param msg The detail message.
*/
public TransformerFactoryConfigurationError(Exception e, String msg) {
super(msg);
this.exception = e;
}
/**
* Return the message (if any) for this error . If there is no
* message for the exception and there is an encapsulated
* exception then the message of that exception will be returned.
*
* @return The error message.
*/
public String getMessage() {
String message = super.getMessage();
if ((message == null) && (exception != null)) {
return exception.getMessage();
}
return message;
}
/**
* Return the actual exception (if any) that caused this exception to
* be raised.
*
* @return The encapsulated exception, or null if there is none.
*/
public Exception getException() {
return exception;
}
}

View file

@ -0,0 +1,50 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform;
/**
* <p>An object that implements this interface that can be called by the processor
* to turn a URI used in document(), xsl:import, or xsl:include into a Source object.
*/
public interface URIResolver {
/**
* Called by the processor when it encounters
* an xsl:include, xsl:import, or document() function.
*
* @param href An href attribute, which may be relative or absolute.
* @param base The base URI against which the first argument will be made
* absolute if the absolute URI is required.
*
* @return A Source object, or null if the href cannot be resolved,
* and the processor should try to resolve the URI itself.
*
* @throws TransformerException if an error occurs when trying to
* resolve the URI.
*/
public Source resolve(String href, String base)
throws TransformerException;
}

View file

@ -0,0 +1,49 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform.dom;
import javax.xml.transform.SourceLocator;
import org.w3c.dom.Node;
/**
* Indicates the position of a node in a source DOM, intended
* primarily for error reporting. To use a DOMLocator, the receiver of an
* error must downcast the {@link javax.xml.transform.SourceLocator}
* object returned by an exception. A {@link javax.xml.transform.Transformer}
* may use this object for purposes other than error reporting, for instance,
* to indicate the source node that originated a result node.
*/
public interface DOMLocator extends SourceLocator {
/**
* Return the node where the event occurred.
*
* @return The node that is the location for the event.
*/
public Node getOriginatingNode();
}

View file

@ -0,0 +1,362 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform.dom;
import javax.xml.transform.Result;
import org.w3c.dom.Node;
/**
* <p>Acts as a holder for a transformation result tree in the form of a Document Object Model (DOM) tree.</p>
*
* <p>If no output DOM source is set, the transformation will create a Document node as the holder for the result of the transformation,
* which may be retrieved with {@link #getNode()}.</p>
*
* @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
*/
public class DOMResult implements Result {
/** <p>If {@link javax.xml.transform.TransformerFactory#getFeature}
* returns <code>true</code> when passed this value as an argument,
* the <code>Transformer</code> supports <code>Result</code> output of this type.</p>
*/
public static final String FEATURE = "http://javax.xml.transform.dom.DOMResult/feature";
/**
* <p>Zero-argument default constructor.</p>
*
* <p><code>node</code>,
* <code>siblingNode</code> and
* <code>systemId</code>
* will be set to <code>null</code>.</p>
*/
public DOMResult() {
setNode(null);
setNextSibling(null);
setSystemId(null);
}
/**
* <p>Use a DOM node to create a new output target.</p>
*
* <p>In practice, the node should be
* a {@link org.w3c.dom.Document} node,
* a {@link org.w3c.dom.DocumentFragment} node, or
* a {@link org.w3c.dom.Element} node.
* In other words, a node that accepts children.</p>
*
* <p><code>siblingNode</code> and
* <code>systemId</code>
* will be set to <code>null</code>.</p>
*
* @param node The DOM node that will contain the result tree.
*/
public DOMResult(Node node) {
setNode(node);
setNextSibling(null);
setSystemId(null);
}
/**
* <p>Use a DOM node to create a new output target with the specified System ID.<p>
*
* <p>In practice, the node should be
* a {@link org.w3c.dom.Document} node,
* a {@link org.w3c.dom.DocumentFragment} node, or
* a {@link org.w3c.dom.Element} node.
* In other words, a node that accepts children.</p>
*
* <p><code>siblingNode</code> will be set to <code>null</code>.</p>
*
* @param node The DOM node that will contain the result tree.
* @param systemId The system identifier which may be used in association with this node.
*/
public DOMResult(Node node, String systemId) {
setNode(node);
setNextSibling(null);
setSystemId(systemId);
}
/**
* <p>Use a DOM node to create a new output target specifying the child node where the result nodes should be inserted before.</p>
*
* <p>In practice, <code>node</code> and <code>nextSibling</code> should be
* a {@link org.w3c.dom.Document} node,
* a {@link org.w3c.dom.DocumentFragment} node, or
* a {@link org.w3c.dom.Element} node.
* In other words, a node that accepts children.</p>
*
* <p>Use <code>nextSibling</code> to specify the child node
* where the result nodes should be inserted before.
* If <code>nextSibling</code> is not a sibling of <code>node</code>,
* then an <code>IllegalArgumentException</code> is thrown.
* If <code>node</code> is <code>null</code> and <code>nextSibling</code> is not <code>null</code>,
* then an <code>IllegalArgumentException</code> is thrown.
* If <code>nextSibling</code> is <code>null</code>,
* then the behavior is the same as calling {@link #DOMResult(Node node)},
* i.e. append the result nodes as the last child of the specified <code>node</code>.</p>
*
* <p><code>systemId</code> will be set to <code>null</code>.</p>
*
* @param node The DOM node that will contain the result tree.
* @param nextSibling The child node where the result nodes should be inserted before.
*
* @throws IllegalArgumentException If <code>nextSibling</code> is not a sibling of <code>node</code> or
* <code>node</code> is <code>null</code> and <code>nextSibling</code>
* is not <code>null</code>.
*
* @since 1.5
*/
public DOMResult(Node node, Node nextSibling) {
// does the corrent parent/child relationship exist?
if (nextSibling != null) {
// cannot be a sibling of a null node
if (node == null) {
throw new IllegalArgumentException("Cannot create a DOMResult when the nextSibling is contained by the \"null\" node.");
}
// nextSibling contained by node?
if ((node.compareDocumentPosition(nextSibling)&Node.DOCUMENT_POSITION_CONTAINED_BY)==0) {
throw new IllegalArgumentException("Cannot create a DOMResult when the nextSibling is not contained by the node.");
}
}
setNode(node);
setNextSibling(nextSibling);
setSystemId(null);
}
/**
* <p>Use a DOM node to create a new output target specifying the child node where the result nodes should be inserted before and
* the specified System ID.</p>
*
* <p>In practice, <code>node</code> and <code>nextSibling</code> should be
* a {@link org.w3c.dom.Document} node,
* a {@link org.w3c.dom.DocumentFragment} node, or a
* {@link org.w3c.dom.Element} node.
* In other words, a node that accepts children.</p>
*
* <p>Use <code>nextSibling</code> to specify the child node
* where the result nodes should be inserted before.
* If <code>nextSibling</code> is not a sibling of <code>node</code>,
* then an <code>IllegalArgumentException</code> is thrown.
* If <code>node</code> is <code>null</code> and <code>nextSibling</code> is not <code>null</code>,
* then an <code>IllegalArgumentException</code> is thrown.
* If <code>nextSibling</code> is <code>null</code>,
* then the behavior is the same as calling {@link #DOMResult(Node node, String systemId)},
* i.e. append the result nodes as the last child of the specified node and use the specified System ID.</p>
*
* @param node The DOM node that will contain the result tree.
* @param nextSibling The child node where the result nodes should be inserted before.
* @param systemId The system identifier which may be used in association with this node.
*
* @throws IllegalArgumentException If <code>nextSibling</code> is not a
* sibling of <code>node</code> or
* <code>node</code> is <code>null</code> and <code>nextSibling</code>
* is not <code>null</code>.
*
* @since 1.5
*/
public DOMResult(Node node, Node nextSibling, String systemId) {
// does the corrent parent/child relationship exist?
if (nextSibling != null) {
// cannot be a sibling of a null node
if (node == null) {
throw new IllegalArgumentException("Cannot create a DOMResult when the nextSibling is contained by the \"null\" node.");
}
// nextSibling contained by node?
if ((node.compareDocumentPosition(nextSibling)&Node.DOCUMENT_POSITION_CONTAINED_BY)==0) {
throw new IllegalArgumentException("Cannot create a DOMResult when the nextSibling is not contained by the node.");
}
}
setNode(node);
setNextSibling(nextSibling);
setSystemId(systemId);
}
/**
* <p>Set the node that will contain the result DOM tree.<p>
*
* <p>In practice, the node should be
* a {@link org.w3c.dom.Document} node,
* a {@link org.w3c.dom.DocumentFragment} node, or
* a {@link org.w3c.dom.Element} node.
* In other words, a node that accepts children.</p>
*
* <p>An <code>IllegalStateException</code> is thrown if
* <code>nextSibling</code> is not <code>null</code> and
* <code>node</code> is not a parent of <code>nextSibling</code>.
* An <code>IllegalStateException</code> is thrown if <code>node</code> is <code>null</code> and
* <code>nextSibling</code> is not <code>null</code>.</p>
*
* @param node The node to which the transformation will be appended.
*
* @throws IllegalStateException If <code>nextSibling</code> is not
* <code>null</code> and
* <code>nextSibling</code> is not a child of <code>node</code> or
* <code>node</code> is <code>null</code> and
* <code>nextSibling</code> is not <code>null</code>.
*/
public void setNode(Node node) {
// does the corrent parent/child relationship exist?
if (nextSibling != null) {
// cannot be a sibling of a null node
if (node == null) {
throw new IllegalStateException("Cannot create a DOMResult when the nextSibling is contained by the \"null\" node.");
}
// nextSibling contained by node?
if ((node.compareDocumentPosition(nextSibling)&Node.DOCUMENT_POSITION_CONTAINED_BY)==0) {
throw new IllegalArgumentException("Cannot create a DOMResult when the nextSibling is not contained by the node.");
}
}
this.node = node;
}
/**
* <p>Get the node that will contain the result DOM tree.</p>
*
* <p>If no node was set via
* {@link #DOMResult(Node node)},
* {@link #DOMResult(Node node, String systeId)},
* {@link #DOMResult(Node node, Node nextSibling)},
* {@link #DOMResult(Node node, Node nextSibling, String systemId)} or
* {@link #setNode(Node node)},
* then the node will be set by the transformation, and may be obtained from this method once the transformation is complete.
* Calling this method before the transformation will return <code>null</code>.</p>
*
* @return The node to which the transformation will be appended.
*/
public Node getNode() {
return node;
}
/**
* <p>Set the child node before which the result nodes will be inserted.</p>
*
* <p>Use <code>nextSibling</code> to specify the child node
* before which the result nodes should be inserted.
* If <code>nextSibling</code> is not a descendant of <code>node</code>,
* then an <code>IllegalArgumentException</code> is thrown.
* If <code>node</code> is <code>null</code> and <code>nextSibling</code> is not <code>null</code>,
* then an <code>IllegalStateException</code> is thrown.
* If <code>nextSibling</code> is <code>null</code>,
* then the behavior is the same as calling {@link #DOMResult(Node node)},
* i.e. append the result nodes as the last child of the specified <code>node</code>.</p>
*
* @param nextSibling The child node before which the result nodes will be inserted.
*
* @throws IllegalArgumentException If <code>nextSibling</code> is not a
* descendant of <code>node</code>.
* @throws IllegalStateException If <code>node</code> is <code>null</code>
* and <code>nextSibling</code> is not <code>null</code>.
*
* @since 1.5
*/
public void setNextSibling(Node nextSibling) {
// does the corrent parent/child relationship exist?
if (nextSibling != null) {
// cannot be a sibling of a null node
if (node == null) {
throw new IllegalStateException("Cannot create a DOMResult when the nextSibling is contained by the \"null\" node.");
}
// nextSibling contained by node?
if ((node.compareDocumentPosition(nextSibling)&Node.DOCUMENT_POSITION_CONTAINED_BY)==0) {
throw new IllegalArgumentException("Cannot create a DOMResult when the nextSibling is not contained by the node.");
}
}
this.nextSibling = nextSibling;
}
/**
* <p>Get the child node before which the result nodes will be inserted.</p>
*
* <p>If no node was set via
* {@link #DOMResult(Node node, Node nextSibling)},
* {@link #DOMResult(Node node, Node nextSibling, String systemId)} or
* {@link #setNextSibling(Node nextSibling)},
* then <code>null</code> will be returned.</p>
*
* @return The child node before which the result nodes will be inserted.
*
* @since 1.5
*/
public Node getNextSibling() {
return nextSibling;
}
/**
* <p>Set the systemId that may be used in association with the node.</p>
*
* @param systemId The system identifier as a URI string.
*/
public void setSystemId(String systemId) {
this.systemId = systemId;
}
/**
* <p>Get the System Identifier.</p>
*
* <p>If no System ID was set via
* {@link #DOMResult(Node node, String systemId)},
* {@link #DOMResult(Node node, Node nextSibling, String systemId)} or
* {@link #setSystemId(String systemId)},
* then <code>null</code> will be returned.</p>
*
* @return The system identifier.
*/
public String getSystemId() {
return systemId;
}
//////////////////////////////////////////////////////////////////////
// Internal state.
//////////////////////////////////////////////////////////////////////
/**
* <p>The node to which the transformation will be appended.</p>
*/
private Node node = null;
/**
* <p>The child node before which the result nodes will be inserted.</p>
*
* @since 1.5
*/
private Node nextSibling = null;
/**
* <p>The System ID that may be used in association with the node.</p>
*/
private String systemId = null;
}

View file

@ -0,0 +1,137 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform.dom;
import javax.xml.transform.Source;
import org.w3c.dom.Node;
/**
* <p>Acts as a holder for a transformation Source tree in the
* form of a Document Object Model (DOM) tree.</p>
*
* <p>Note that XSLT requires namespace support. Attempting to transform a DOM
* that was not contructed with a namespace-aware parser may result in errors.
* Parsers can be made namespace aware by calling
* {@link javax.xml.parsers.DocumentBuilderFactory#setNamespaceAware(boolean awareness)}.</p>
*
* @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @see <a href="http://www.w3.org/TR/DOM-Level-2">Document Object Model (DOM) Level 2 Specification</a>
*/
public class DOMSource implements Source {
/**
* <p><code>Node</code> to serve as DOM source.</p>
*/
private Node node;
/**
* <p>The base ID (URL or system ID) from where URLs
* will be resolved.</p>
*/
private String systemID;
/** If {@link javax.xml.transform.TransformerFactory#getFeature}
* returns true when passed this value as an argument,
* the Transformer supports Source input of this type.
*/
public static final String FEATURE =
"http://javax.xml.transform.dom.DOMSource/feature";
/**
* <p>Zero-argument default constructor. If this constructor is used, and
* no DOM source is set using {@link #setNode(Node node)} , then the
* <code>Transformer</code> will
* create an empty source {@link org.w3c.dom.Document} using
* {@link javax.xml.parsers.DocumentBuilder#newDocument()}.</p>
*
* @see javax.xml.transform.Transformer#transform(Source xmlSource, Result outputTarget)
*/
public DOMSource() { }
/**
* Create a new input source with a DOM node. The operation
* will be applied to the subtree rooted at this node. In XSLT,
* a "/" pattern still means the root of the tree (not the subtree),
* and the evaluation of global variables and parameters is done
* from the root node also.
*
* @param n The DOM node that will contain the Source tree.
*/
public DOMSource(Node n) {
setNode(n);
}
/**
* Create a new input source with a DOM node, and with the
* system ID also passed in as the base URI.
*
* @param node The DOM node that will contain the Source tree.
* @param systemID Specifies the base URI associated with node.
*/
public DOMSource(Node node, String systemID) {
setNode(node);
setSystemId(systemID);
}
/**
* Set the node that will represents a Source DOM tree.
*
* @param node The node that is to be transformed.
*/
public void setNode(Node node) {
this.node = node;
}
/**
* Get the node that represents a Source DOM tree.
*
* @return The node that is to be transformed.
*/
public Node getNode() {
return node;
}
/**
* Set the base ID (URL or system ID) from where URLs
* will be resolved.
*
* @param systemID Base URL for this DOM tree.
*/
public void setSystemId(String systemID) {
this.systemID = systemID;
}
/**
* Get the base ID (URL or system ID) from where URLs
* will be resolved.
*
* @return Base URL for this DOM tree.
*/
public String getSystemId() {
return this.systemID;
}
}

View file

@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation. Sun designates this
particular file as subject to the "Classpath" exception as provided
by Sun in the LICENSE file that accompanied this code.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
CA 95054 USA or visit www.sun.com if you need additional information or
have any questions.
-->
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>javax.xml.transform.dom</title>
<meta name="CVS"
content="$Id: package.html,v 1.2 2005/06/10 03:50:40 jeffsuttor Exp $" />
<meta name="AUTHOR"
content="Jeff.Suttor@Sun.com" />
</head>
<body>
<p>This package implements DOM-specific transformation APIs.</p>
<p>The {@link javax.xml.transform.dom.DOMSource} class allows the
client of the implementation of this API to specify a DOM
{@link org.w3c.dom.Node} as the source of the input tree. The model of
how the Transformer deals with the DOM tree in terms of mismatches with the
<A href="http://www.w3.org/TR/xslt#data-model">XSLT data model</A> or
other data models is beyond the scope of this document. Any of the nodes
derived from {@link org.w3c.dom.Node} are legal input.</p>
<p>The {@link javax.xml.transform.dom.DOMResult} class allows
a {@link org.w3c.dom.Node} to be specified to which result DOM nodes will
be appended. If an output node is not specified, the transformer will use
{@link javax.xml.parsers.DocumentBuilder#newDocument} to create an
output {@link org.w3c.dom.Document} node. If a node is specified, it
should be one of the following: {@link org.w3c.dom.Document},
{@link org.w3c.dom.Element}, or
{@link org.w3c.dom.DocumentFragment}. Specification of any other node
type is implementation dependent and undefined by this API. If the result is a
{@link org.w3c.dom.Document}, the output of the transformation must have
a single element root to set as the document element.</p>
<p>The {@link javax.xml.transform.dom.DOMLocator} node may be passed
to {@link javax.xml.transform.TransformerException} objects, and
retrieved by trying to cast the result of the
{@link javax.xml.transform.TransformerException#getLocator()} method.
The implementation has no responsibility to use a DOMLocator instead of a
{@link javax.xml.transform.SourceLocator} (though line numbers and the
like do not make much sense for a DOM), so the result of getLocator must always
be tested with an instanceof. </p>
</body>
</html>

View file

@ -0,0 +1,291 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation. Sun designates this
particular file as subject to the "Classpath" exception as provided
by Sun in the LICENSE file that accompanied this code.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
CA 95054 USA or visit www.sun.com if you need additional information or
have any questions.
-->
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Transformation API For XML</title>
<meta name="CVS"
content="$Id: overview.html,v 1.2 2005/06/10 03:50:39 jeffsuttor Exp $" />
<meta name="AUTHOR"
content="Jeff.Suttor@Sun.com" />
</head>
<body>
<h2>Transformation API For XML</h2>
<h3>Introduction</h3>
<p>This overview describes the set of APIs contained in
javax.xml.transform. For the sake of brevity, these interfaces are referred to
as TrAX (Transformations for XML). </p>
<p>There is a broad need for Java applications to be able to transform XML
and related tree-shaped data structures. In fact, XML is not normally very
useful to an application without going through some sort of transformation,
unless the semantic structure is used directly as data. Almost all XML-related
applications need to perform transformations. Transformations may be described
by Java code, Perl code, <A href="http://www.w3.org/TR/xslt">XSLT</A>
Stylesheets, other types of script, or by proprietary formats. The inputs, one
or multiple, to a transformation, may be a URL, XML stream, a DOM tree, SAX
Events, or a proprietary format or data structure. The output types are the
pretty much the same types as the inputs, but different inputs may need to be
combined with different outputs.</p>
<p>The great challenge of a transformation API is how to deal with all the
possible combinations of inputs and outputs, without becoming specialized for
any of the given types.</p>
<p>The Java community will greatly benefit from a common API that will
allow them to understand and apply a single model, write to consistent
interfaces, and apply the transformations polymorphically. TrAX attempts to
define a model that is clean and generic, yet fills general application
requirements across a wide variety of uses. </p>
<h3>General Terminology</h3>
<p>This section will explain some general terminology used in this
document. Technical terminology will be explained in the Model section. In many
cases, the general terminology overlaps with the technical terminology.</p>
<ul>
<li>
<p>
<b>Tree</b>
<br>This term, as used within this document, describes an
abstract structure that consists of nodes or events that may be produced by
XML. A Tree physically may be a DOM tree, a series of well balanced parse
events (such as those coming from a SAX2 ContentHander), a series of requests
(the result of which can describe a tree), or a stream of marked-up
characters.</p>
</li>
<li>
<p>
<b>Source Tree(s)</b>
<br>One or more trees that are the inputs to the
transformation.</p>
</li>
<li>
<p>
<b>Result Tree(s)</b>
<br>One or more trees that are the output of the
transformation.</p>
</li>
<li>
<p>
<b>Transformation</b>
<br>The processor of consuming a stream or tree to produce
another stream or tree.</p>
</li>
<li>
<p>
<b>Identity (or Copy) Transformation</b>
<br>The process of transformation from a source to a result,
making as few structural changes as possible and no informational changes. The
term is somewhat loosely used, as the process is really a copy. from one
"format" (such as a DOM tree, stream, or set of SAX events) to
another.</p>
</li>
<li>
<p>
<b>Serialization</b>
<br>The process of taking a tree and turning it into a stream. In
some sense, a serialization is a specialized transformation.</p>
</li>
<li>
<p>
<b>Parsing</b>
<br>The process of taking a stream and turning it into a tree. In
some sense, parsing is a specialized transformation.</p>
</li>
<li>
<p>
<b>Transformer</b>
<br>A Transformer is the object that executes the transformation.
</p>
</li>
<li>
<p>
<b>Transformation instructions</b>
<br>Describes the transformation. A form of code, script, or
simply a declaration or series of declarations.</p>
</li>
<li>
<p>
<b>Stylesheet</b>
<br>The same as "transformation instructions," except it is
likely to be used in conjunction with <A href="http://www.w3.org/TR/xslt">XSLT</A>.</p>
</li>
<li>
<p>
<b>Templates</b>
<br>Another form of "transformation instructions." In the TrAX
interface, this term is used to describe processed or compiled transformation
instructions. The Source flows through a Templates object to be formed into the
Result.</p>
</li>
<li>
<p>
<b>Processor</b>
<br>A general term for the thing that may both process the
transformation instructions, and perform the transformation.</p>
</li>
<li>
<p>
<b>DOM</b>
<br>Document Object Model, specifically referring to the
<A href="#http://www.w3.org/TR/DOM-Level-2%20">Document Object Model
(DOM) Level 2 Specification</A>.</p>
</li>
<li>
<p>
<b>SAX</b><br>
Simple API for XML, specifically referring to the <a href="http://sax.sourceforge.net/">SAX 2.0.2 release</a>.
</p>
</li>
</ul>
<h3>Model</h3>
<p>The section defines the abstract model for TrAX, apart from the details
of the interfaces.</p>
<p>A TRaX <A href="#pattern-TransformerFactory">TransformerFactory</A> is an object
that processes transformation instructions, and produces
<A href="#pattern-Templates">Templates</A> (in the technical
terminology). A <A href="#pattern-Templates">Templates</A>
object provides a <A href="#pattern-Transformer">Transformer</A>, which transforms one or
more <A href="#pattern-Source">Source</A>s into one or more
<A href="#pattern-Result">Result</A>s.</p>
<p>To use the TRaX interface, you create a
<A href="#pattern-TransformerFactory">TransformerFactory</A>,
which may directly provide a <A href="#pattern-Transformers">Transformers</A>, or which can provide
<A href="#pattern-Templates">Templates</A> from a variety of
<A href="#pattern-Source">Source</A>s. The
<A href="#pattern-Templates">Templates</A> object is a processed
or compiled representation of the transformation instructions, and provides a
<A href="#pattern-Transformer">Transformer</A>. The
<A href="#pattern-Transformer">Transformer</A> processes a
<A href="#pattern-Transformer">Source</A> according to the
instructions found in the <A href="#pattern-Templates">Templates</A>, and produces a
<A href="#pattern-Result">Result</A>.</p>
<p>The process of transformation from a tree, either in the form of an
object model, or in the form of parse events, into a stream, is known as
<code>serialization</code>. We believe this is the most suitable term for
this process, despite the overlap with Java object serialization.</p>
<H3>TRaX Patterns</H3>
<ul>
<p>
<b><a name="pattern-Processor">Processor</a></b>
<br>
<br>
<i>Intent: </i>Generic concept for the
set of objects that implement the TrAX interfaces.<br>
<i>Responsibilities: </i>Create compiled transformation instructions, transform
sources, and manage transformation parameters and
properties.<br>
<i>Thread safety: </i>Only the Templates object can be
used concurrently in multiple threads. The rest of the processor does not do
synchronized blocking, and so may not be used to perform multiple concurrent
operations. Different Processors can be used concurrently by different
threads.</p>
<p>
<b><a name="pattern-TransformerFactory">TransformerFactory</a></b>
<br>
<br>
<i>Intent: </i>Serve as a vendor-neutral Processor interface for
<A href="http://www.w3.org/TR/xslt">XSLT</A> and similar
processors.<br>
<i>Responsibilities: </i>Serve as a factory for a concrete
implementation of an TransformerFactory, serve as a direct factory for
Transformer objects, serve as a factory for Templates objects, and manage
processor specific features.<br>
<i>Thread safety: </i>A
TransformerFactory may not perform mulitple concurrent
operations.</p>
<p>
<b><a name="pattern-Templates">Templates</a></b>
<br>
<br>
<i>Intent: </i>The
runtime representation of the transformation instructions.<br>
<i>Responsibilities: </i>A data bag for transformation instructions; act as a factory
for Transformers.<br>
<i>Thread safety: </i>Threadsafe for concurrent
usage over multiple threads once construction is complete.</p>
<p>
<b><a name="pattern-Transformer">Transformer</a></b>
<br>
<br>
<i>Intent: </i>Act as a per-thread
execution context for transformations, act as an interface for performing the
transformation.<br>
<i>Responsibilities: </i>Perform the
transformation.<br>
<i>Thread safety: </i>Only one instance per thread
is safe.<br>
<i>Notes: </i>The Transformer is bound to the Templates
object that created it.</p>
<p>
<b><a name="pattern-Source">Source</a></b>
<br>
<br>
<i>Intent: </i>Serve as a
single vendor-neutral object for multiple types of input.<br>
<i>Responsibilities: </i>Act as simple data holder for System IDs, DOM nodes, streams,
etc.<br>
<i>Thread safety: </i>Threadsafe concurrently over multiple
threads for read-only operations; must be synchronized for edit
operations.</p>
<p>
<b><a name="pattern-Result">Result</a></b>
<br>
<br>
<i>Potential alternate name: </i>ResultTarget<br>
<i>Intent: </i>Serve
as a single object for multiple types of output, so there can be simple process
method signatures.<br>
<i>Responsibilities: </i>Act as simple data holder for
output stream, DOM node, ContentHandler, etc.<br>
<i>Thread safety: </i>Threadsafe concurrently over multiple threads for read-only,
must be synchronized for edit.</p>
</ul>
</body>
</html>

View file

@ -0,0 +1,233 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation. Sun designates this
particular file as subject to the "Classpath" exception as provided
by Sun in the LICENSE file that accompanied this code.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
CA 95054 USA or visit www.sun.com if you need additional information or
have any questions.
-->
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>javax.xml.transform</title>
<meta name="CVS"
content="$Id: package.html,v 1.2 2005/06/10 03:50:39 jeffsuttor Exp $" />
<meta name="AUTHOR"
content="Jeff.Suttor@Sun.com" />
</head>
<body>
<p>This package defines the generic APIs for processing transformation
instructions, and performing a transformation from source to result. These
interfaces have no dependencies on SAX or the DOM standard, and try to make as
few assumptions as possible about the details of the source and result of a
transformation. It achieves this by defining
{@link javax.xml.transform.Source} and
{@link javax.xml.transform.Result} interfaces.
</p>
<p>To define concrete classes for the user, the API defines specializations
of the interfaces found at the root level. These interfaces are found in
{@link javax.xml.transform.sax}, {@link javax.xml.transform.dom},
and {@link javax.xml.transform.stream}.
</p>
<h3>Creating Objects</h3>
<p>The API allows a concrete
{@link javax.xml.transform.TransformerFactory} object to be created from
the static function
{@link javax.xml.transform.TransformerFactory#newInstance}.
</p>
<h3>Specification of Inputs and Outputs</h3>
<p>This API defines two interface objects called
{@link javax.xml.transform.Source} and
{@link javax.xml.transform.Result}. In order to pass Source and Result
objects to the interfaces, concrete classes must be used.
Three concrete representations are defined for each of these
objects:
{@link javax.xml.transform.stream.StreamSource} and
{@link javax.xml.transform.stream.StreamResult},
{@link javax.xml.transform.sax.SAXSource} and
{@link javax.xml.transform.sax.SAXResult}, and
{@link javax.xml.transform.dom.DOMSource} and
{@link javax.xml.transform.dom.DOMResult}. Each of these objects defines
a FEATURE string (which is i the form of a URL), which can be passed into
{@link javax.xml.transform.TransformerFactory#getFeature} to see if the
given type of Source or Result object is supported. For instance, to test if a
DOMSource and a StreamResult is supported, you can apply the following
test.
</p>
<pre>
<code>
TransformerFactory tfactory = TransformerFactory.newInstance();
if (tfactory.getFeature(DOMSource.FEATURE) &amp;&amp; tfactory.getFeature(StreamResult.FEATURE)) {
...
}
</code>
</pre>
<h3>
<a name="qname-delimiter">Qualified Name Representation</a>
</h3>
<p><a href="http://www.w3.org/TR/REC-xml-names">Namespaces</a>
present something of a problem area when dealing with XML objects. Qualified
Names appear in XML markup as prefixed names. But the prefixes themselves do
not hold identity. Rather, it is the URIs that they contextually map to that
hold the identity. Therefore, when passing a Qualified Name like "xyz:foo"
among Java programs, one must provide a means to map "xyz" to a namespace.
</p>
<p>One solution has been to create a "QName" object that holds the
namespace URI, as well as the prefix and local name, but this is not always an
optimal solution, as when, for example, you want to use unique strings as keys
in a dictionary object. Not having a string representation also makes it
difficult to specify a namespaced identity outside the context of an XML
document.
</p>
<p>In order to pass namespaced values to transformations,
for
instance when setting a property or a parameter on a
{@link javax.xml.transform.Transformer} object,
this specification defines that a
String "qname" object parameter be passed as two-part string, the namespace URI
enclosed in curly braces ({}), followed by the local name. If the qname has a
null URI, then the String object only contains the local name. An application
can safely check for a non-null URI by testing to see if the first character of
the name is a '{' character.
</p>
<p>For example, if a URI and local name were obtained from an element
defined with &lt;xyz:foo xmlns:xyz="http://xyz.foo.com/yada/baz.html"/&gt;,
then the Qualified Name would be "{http://xyz.foo.com/yada/baz.html}foo".
Note that the prefix is lost.
</p>
<h3>Result Tree Serialization</h3>
<p>Serialization of the result tree to a stream can be controlled with
the {@link javax.xml.transform.Transformer#setOutputProperties} and the
{@link javax.xml.transform.Transformer#setOutputProperty} methods.
These properties only apply to stream results, they have no effect when
the result is a DOM tree or SAX event stream.</p>
<p>Strings that match the <a href="http://www.w3.org/TR/xslt#output">XSLT
specification for xsl:output attributes</a> can be referenced from the
{@link javax.xml.transform.OutputKeys} class. Other strings can be
specified as well.
If the transformer does not recognize an output key, a
{@link java.lang.IllegalArgumentException} is thrown, unless the
key name is <a href="#qname-delimiter">namespace qualified</a>. Output key names
that are namespace qualified are always allowed, although they may be
ignored by some implementations.</p>
<p>If all that is desired is the simple identity transformation of a
source to a result, then {@link javax.xml.transform.TransformerFactory}
provides a
{@link javax.xml.transform.TransformerFactory#newTransformer()} method
with no arguments. This method creates a Transformer that effectively copies
the source to the result. This method may be used to create a DOM from SAX
events or to create an XML or HTML stream from a DOM or SAX events. </p>
<h3>Exceptions and Error Reporting</h3>
<p>The transformation API throw three types of specialized exceptions. A
{@link javax.xml.transform.TransformerFactoryConfigurationError} is parallel to
the {@link javax.xml.parsers.FactoryConfigurationError}, and is thrown
when a configuration problem with the TransformerFactory exists. This error
will typically be thrown when the transformation factory class specified with
the "javax.xml.transform.TransformerFactory" system property cannot be found or
instantiated.</p>
<p>A {@link javax.xml.transform.TransformerConfigurationException}
may be thrown if for any reason a Transformer can not be created. A
TransformerConfigurationException may be thrown if there is a syntax error in
the transformation instructions, for example when
{@link javax.xml.transform.TransformerFactory#newTransformer} is
called.</p>
<p>{@link javax.xml.transform.TransformerException} is a general
exception that occurs during the course of a transformation. A transformer
exception may wrap another exception, and if any of the
{@link javax.xml.transform.TransformerException#printStackTrace()}
methods are called on it, it will produce a list of stack dumps, starting from
the most recent. The transformer exception also provides a
{@link javax.xml.transform.SourceLocator} object which indicates where
in the source tree or transformation instructions the error occurred.
{@link javax.xml.transform.TransformerException#getMessageAndLocation()}
may be called to get an error message with location info, and
{@link javax.xml.transform.TransformerException#getLocationAsString()}
may be called to get just the location string.</p>
<p>Transformation warnings and errors are sent to an
{@link javax.xml.transform.ErrorListener}, at which point the
application may decide to report the error or warning, and may decide to throw
an <code>Exception</code> for a non-fatal error. The <code>ErrorListener</code> may be set via
{@link javax.xml.transform.TransformerFactory#setErrorListener} for
reporting errors that have to do with syntax errors in the transformation
instructions, or via
{@link javax.xml.transform.Transformer#setErrorListener} to report
errors that occur during the transformation. The <code>ErrorListener</code> on both objects
will always be valid and non-<code>null</code>, whether set by the application or a default
implementation provided by the processor.
The default implementation provided by the processor will report all warnings and errors to <code>System.err</code>
and does not throw any <code>Exception</code>s.
Applications are <em>strongly</em> encouraged to register and use
<code>ErrorListener</code>s that insure proper behavior for warnings and
errors.
</p>
<h3>Resolution of URIs within a transformation</h3>
<p>The API provides a way for URIs referenced from within the stylesheet
instructions or within the transformation to be resolved by the calling
application. This can be done by creating a class that implements the
{@link javax.xml.transform.URIResolver} interface, with its one method,
{@link javax.xml.transform.URIResolver#resolve}, and use this class to
set the URI resolution for the transformation instructions or transformation
with {@link javax.xml.transform.TransformerFactory#setURIResolver} or
{@link javax.xml.transform.Transformer#setURIResolver}. The
<code>URIResolver.resolve</code> method takes two String arguments, the URI found in the
stylesheet instructions or built as part of the transformation process, and the
base URI
against which the first argument will be made absolute if the
absolute URI is required.
The returned {@link javax.xml.transform.Source} object must be usable by
the transformer, as specified in its implemented features.</p>
</body>
</html>

View file

@ -0,0 +1,144 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform.sax;
import javax.xml.transform.Result;
import org.xml.sax.ContentHandler;
import org.xml.sax.ext.LexicalHandler;
/**
* <p>Acts as an holder for a transformation Result.</p>
*
* @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
*/
public class SAXResult implements Result {
/**
* If {@link javax.xml.transform.TransformerFactory#getFeature}
* returns true when passed this value as an argument,
* the Transformer supports Result output of this type.
*/
public static final String FEATURE =
"http://javax.xml.transform.sax.SAXResult/feature";
/**
* Zero-argument default constructor.
*/
public SAXResult() {
}
/**
* Create a SAXResult that targets a SAX2 {@link org.xml.sax.ContentHandler}.
*
* @param handler Must be a non-null ContentHandler reference.
*/
public SAXResult(ContentHandler handler) {
setHandler(handler);
}
/**
* Set the target to be a SAX2 {@link org.xml.sax.ContentHandler}.
*
* @param handler Must be a non-null ContentHandler reference.
*/
public void setHandler(ContentHandler handler) {
this.handler = handler;
}
/**
* Get the {@link org.xml.sax.ContentHandler} that is the Result.
*
* @return The ContentHandler that is to be transformation output.
*/
public ContentHandler getHandler() {
return handler;
}
/**
* Set the SAX2 {@link org.xml.sax.ext.LexicalHandler} for the output.
*
* <p>This is needed to handle XML comments and the like. If the
* lexical handler is not set, an attempt should be made by the
* transformer to cast the {@link org.xml.sax.ContentHandler} to a
* <code>LexicalHandler</code>.</p>
*
* @param handler A non-null <code>LexicalHandler</code> for
* handling lexical parse events.
*/
public void setLexicalHandler(LexicalHandler handler) {
this.lexhandler = handler;
}
/**
* Get a SAX2 {@link org.xml.sax.ext.LexicalHandler} for the output.
*
* @return A <code>LexicalHandler</code>, or null.
*/
public LexicalHandler getLexicalHandler() {
return lexhandler;
}
/**
* Method setSystemId Set the systemID that may be used in association
* with the {@link org.xml.sax.ContentHandler}.
*
* @param systemId The system identifier as a URI string.
*/
public void setSystemId(String systemId) {
this.systemId = systemId;
}
/**
* Get the system identifier that was set with setSystemId.
*
* @return The system identifier that was set with setSystemId, or null
* if setSystemId was not called.
*/
public String getSystemId() {
return systemId;
}
//////////////////////////////////////////////////////////////////////
// Internal state.
//////////////////////////////////////////////////////////////////////
/**
* The handler for parse events.
*/
private ContentHandler handler;
/**
* The handler for lexical events.
*/
private LexicalHandler lexhandler;
/**
* The systemID that may be used in association
* with the node.
*/
private String systemId;
}

View file

@ -0,0 +1,209 @@
/*
* Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform.sax;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
/**
* <p>Acts as an holder for SAX-style Source.</p>
*
* <p>Note that XSLT requires namespace support. Attempting to transform an
* input source that is not
* generated with a namespace-aware parser may result in errors.
* Parsers can be made namespace aware by calling the
* {@link javax.xml.parsers.SAXParserFactory#setNamespaceAware(boolean awareness)} method.</p>
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
*/
public class SAXSource implements Source {
/**
* If {@link javax.xml.transform.TransformerFactory#getFeature}
* returns true when passed this value as an argument,
* the Transformer supports Source input of this type.
*/
public static final String FEATURE =
"http://javax.xml.transform.sax.SAXSource/feature";
/**
* <p>Zero-argument default constructor. If this constructor is used, and
* no SAX source is set using
* {@link #setInputSource(InputSource inputSource)} , then the
* <code>Transformer</code> will
* create an empty source {@link org.xml.sax.InputSource} using
* {@link org.xml.sax.InputSource#InputSource() new InputSource()}.</p>
*
* @see javax.xml.transform.Transformer#transform(Source xmlSource, Result outputTarget)
*/
public SAXSource() { }
/**
* Create a <code>SAXSource</code>, using an {@link org.xml.sax.XMLReader}
* and a SAX InputSource. The {@link javax.xml.transform.Transformer}
* or {@link javax.xml.transform.sax.SAXTransformerFactory} will set itself
* to be the reader's {@link org.xml.sax.ContentHandler}, and then will call
* reader.parse(inputSource).
*
* @param reader An XMLReader to be used for the parse.
* @param inputSource A SAX input source reference that must be non-null
* and that will be passed to the reader parse method.
*/
public SAXSource(XMLReader reader, InputSource inputSource) {
this.reader = reader;
this.inputSource = inputSource;
}
/**
* Create a <code>SAXSource</code>, using a SAX <code>InputSource</code>.
* The {@link javax.xml.transform.Transformer} or
* {@link javax.xml.transform.sax.SAXTransformerFactory} creates a
* reader via {@link org.xml.sax.helpers.XMLReaderFactory}
* (if setXMLReader is not used), sets itself as
* the reader's {@link org.xml.sax.ContentHandler}, and calls
* reader.parse(inputSource).
*
* @param inputSource An input source reference that must be non-null
* and that will be passed to the parse method of the reader.
*/
public SAXSource(InputSource inputSource) {
this.inputSource = inputSource;
}
/**
* Set the XMLReader to be used for the Source.
*
* @param reader A valid XMLReader or XMLFilter reference.
*/
public void setXMLReader(XMLReader reader) {
this.reader = reader;
}
/**
* Get the XMLReader to be used for the Source.
*
* @return A valid XMLReader or XMLFilter reference, or null.
*/
public XMLReader getXMLReader() {
return reader;
}
/**
* Set the SAX InputSource to be used for the Source.
*
* @param inputSource A valid InputSource reference.
*/
public void setInputSource(InputSource inputSource) {
this.inputSource = inputSource;
}
/**
* Get the SAX InputSource to be used for the Source.
*
* @return A valid InputSource reference, or null.
*/
public InputSource getInputSource() {
return inputSource;
}
/**
* Set the system identifier for this Source. If an input source
* has already been set, it will set the system ID or that
* input source, otherwise it will create a new input source.
*
* <p>The system identifier is optional if there is a byte stream
* or a character stream, but it is still useful to provide one,
* since the application can use it to resolve relative URIs
* and can include it in error messages and warnings (the parser
* will attempt to open a connection to the URI only if
* no byte stream or character stream is specified).</p>
*
* @param systemId The system identifier as a URI string.
*/
public void setSystemId(String systemId) {
if (null == inputSource) {
inputSource = new InputSource(systemId);
} else {
inputSource.setSystemId(systemId);
}
}
/**
* <p>Get the base ID (URI or system ID) from where URIs
* will be resolved.</p>
*
* @return Base URL for the <code>Source</code>, or <code>null</code>.
*/
public String getSystemId() {
if (inputSource == null) {
return null;
} else {
return inputSource.getSystemId();
}
}
/**
* The XMLReader to be used for the source tree input. May be null.
*/
private XMLReader reader;
/**
* <p>The SAX InputSource to be used for the source tree input.
* Should not be <code>null</code>.</p>
*/
private InputSource inputSource;
/**
* Attempt to obtain a SAX InputSource object from a Source
* object.
*
* @param source Must be a non-null Source reference.
*
* @return An InputSource, or null if Source can not be converted.
*/
public static InputSource sourceToInputSource(Source source) {
if (source instanceof SAXSource) {
return ((SAXSource) source).getInputSource();
} else if (source instanceof StreamSource) {
StreamSource ss = (StreamSource) source;
InputSource isource = new InputSource(ss.getSystemId());
isource.setByteStream(ss.getInputStream());
isource.setCharacterStream(ss.getReader());
isource.setPublicId(ss.getPublicId());
return isource;
} else {
return null;
}
}
}

View file

@ -0,0 +1,150 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform.sax;
import javax.xml.transform.*;
import org.xml.sax.XMLFilter;
/**
* This class extends TransformerFactory to provide SAX-specific
* factory methods. It provides two types of ContentHandlers,
* one for creating Transformers, the other for creating Templates
* objects.
*
* <p>If an application wants to set the ErrorHandler or EntityResolver
* for an XMLReader used during a transformation, it should use a URIResolver
* to return the SAXSource which provides (with getXMLReader) a reference to
* the XMLReader.</p>
*/
public abstract class SAXTransformerFactory extends TransformerFactory {
/** If {@link javax.xml.transform.TransformerFactory#getFeature}
* returns true when passed this value as an argument,
* the TransformerFactory returned from
* {@link javax.xml.transform.TransformerFactory#newInstance} may
* be safely cast to a SAXTransformerFactory.
*/
public static final String FEATURE =
"http://javax.xml.transform.sax.SAXTransformerFactory/feature";
/** If {@link javax.xml.transform.TransformerFactory#getFeature}
* returns true when passed this value as an argument,
* the {@link #newXMLFilter(Source src)}
* and {@link #newXMLFilter(Templates templates)} methods are supported.
*/
public static final String FEATURE_XMLFILTER =
"http://javax.xml.transform.sax.SAXTransformerFactory/feature/xmlfilter";
/**
* The default constructor is protected on purpose.
*/
protected SAXTransformerFactory() {}
/**
* Get a TransformerHandler object that can process SAX
* ContentHandler events into a Result, based on the transformation
* instructions specified by the argument.
*
* @param src The Source of the transformation instructions.
*
* @return TransformerHandler ready to transform SAX events.
*
* @throws TransformerConfigurationException If for some reason the
* TransformerHandler can not be created.
*/
public abstract TransformerHandler newTransformerHandler(Source src)
throws TransformerConfigurationException;
/**
* Get a TransformerHandler object that can process SAX
* ContentHandler events into a Result, based on the Templates argument.
*
* @param templates The compiled transformation instructions.
*
* @return TransformerHandler ready to transform SAX events.
*
* @throws TransformerConfigurationException If for some reason the
* TransformerHandler can not be created.
*/
public abstract TransformerHandler newTransformerHandler(
Templates templates) throws TransformerConfigurationException;
/**
* Get a TransformerHandler object that can process SAX
* ContentHandler events into a Result. The transformation
* is defined as an identity (or copy) transformation, for example
* to copy a series of SAX parse events into a DOM tree.
*
* @return A non-null reference to a TransformerHandler, that may
* be used as a ContentHandler for SAX parse events.
*
* @throws TransformerConfigurationException If for some reason the
* TransformerHandler cannot be created.
*/
public abstract TransformerHandler newTransformerHandler()
throws TransformerConfigurationException;
/**
* Get a TemplatesHandler object that can process SAX
* ContentHandler events into a Templates object.
*
* @return A non-null reference to a TransformerHandler, that may
* be used as a ContentHandler for SAX parse events.
*
* @throws TransformerConfigurationException If for some reason the
* TemplatesHandler cannot be created.
*/
public abstract TemplatesHandler newTemplatesHandler()
throws TransformerConfigurationException;
/**
* Create an XMLFilter that uses the given Source as the
* transformation instructions.
*
* @param src The Source of the transformation instructions.
*
* @return An XMLFilter object, or null if this feature is not supported.
*
* @throws TransformerConfigurationException If for some reason the
* TemplatesHandler cannot be created.
*/
public abstract XMLFilter newXMLFilter(Source src)
throws TransformerConfigurationException;
/**
* Create an XMLFilter, based on the Templates argument..
*
* @param templates The compiled transformation instructions.
*
* @return An XMLFilter object, or null if this feature is not supported.
*
* @throws TransformerConfigurationException If for some reason the
* TemplatesHandler cannot be created.
*/
public abstract XMLFilter newXMLFilter(Templates templates)
throws TransformerConfigurationException;
}

View file

@ -0,0 +1,68 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform.sax;
import javax.xml.transform.*;
import org.xml.sax.ContentHandler;
/**
* A SAX ContentHandler that may be used to process SAX
* parse events (parsing transformation instructions) into a Templates object.
*
* <p>Note that TemplatesHandler does not need to implement LexicalHandler.</p>
*/
public interface TemplatesHandler extends ContentHandler {
/**
* When a TemplatesHandler object is used as a ContentHandler
* for the parsing of transformation instructions, it creates a Templates object,
* which the caller can get once the SAX events have been completed.
*
* @return The Templates object that was created during
* the SAX event process, or null if no Templates object has
* been created.
*
*/
public Templates getTemplates();
/**
* Set the base ID (URI or system ID) for the Templates object
* created by this builder. This must be set in order to
* resolve relative URIs in the stylesheet. This must be
* called before the startDocument event.
*
* @param systemID Base URI for this stylesheet.
*/
public void setSystemId(String systemID);
/**
* Get the base ID (URI or system ID) from where relative
* URLs will be resolved.
* @return The systemID that was set with {@link #setSystemId}.
*/
public String getSystemId();
}

View file

@ -0,0 +1,76 @@
/*
* Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform.sax;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.ext.LexicalHandler;
/**
* A TransformerHandler
* listens for SAX ContentHandler parse events and transforms
* them to a Result.
*/
public interface TransformerHandler
extends ContentHandler, LexicalHandler, DTDHandler {
/**
* <p>Set the <code>Result</code> associated with this
* <code>TransformerHandler</code> to be used for the transformation.</p>
*
* @param result A <code>Result</code> instance, should not be
* <code>null</code>.
*
* @throws IllegalArgumentException if result is invalid for some reason.
*/
public void setResult(Result result) throws IllegalArgumentException;
/**
* Set the base ID (URI or system ID) from where relative
* URLs will be resolved.
* @param systemID Base URI for the source tree.
*/
public void setSystemId(String systemID);
/**
* Get the base ID (URI or system ID) from where relative
* URLs will be resolved.
* @return The systemID that was set with {@link #setSystemId}.
*/
public String getSystemId();
/**
* <p>Get the <code>Transformer</code> associated with this handler, which
* is needed in order to set parameters and output properties.</p>
*
* @return <code>Transformer</code> associated with this
* <code>TransformerHandler</code>.
*/
public Transformer getTransformer();
}

View file

@ -0,0 +1,104 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation. Sun designates this
particular file as subject to the "Classpath" exception as provided
by Sun in the LICENSE file that accompanied this code.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
CA 95054 USA or visit www.sun.com if you need additional information or
have any questions.
-->
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>javax.xml.transform.sax</title>
<meta name="CVS"
content="$Id: package.html,v 1.2 2005/06/10 03:50:41 jeffsuttor Exp $" />
<meta name="AUTHOR"
content="Jeff.Suttor@Sun.com" />
</head>
<body>
<p>This package implements SAX2-specific transformation APIs. It provides
classes which allow input from {@link org.xml.sax.ContentHandler}
events, and also classes that produce org.xml.sax.ContentHandler events. It
also provides methods to set the input source as an
{@link org.xml.sax.XMLReader}, or to use a
{@link org.xml.sax.InputSource} as the source. It also allows the
creation of a {@link org.xml.sax.XMLFilter}, which enables
transformations to "pull" from other transformations, and lets the transformer
to be used polymorphically as an {@link org.xml.sax.XMLReader}.</p>
<p>The {@link javax.xml.transform.sax.SAXSource} class allows the
setting of an {@link org.xml.sax.XMLReader} to be used for "pulling"
parse events, and an {@link org.xml.sax.InputSource} that may be used to
specify the SAX source.</p>
<p>The {@link javax.xml.transform.sax.SAXResult} class allows the
setting of a {@link org.xml.sax.ContentHandler} to be the receiver of
SAX2 events from the transformation.
<p>The {@link javax.xml.transform.sax.SAXTransformerFactory} extends
{@link javax.xml.transform.TransformerFactory} to provide factory
methods for creating {@link javax.xml.transform.sax.TemplatesHandler},
{@link javax.xml.transform.sax.TransformerHandler}, and
{@link org.xml.sax.XMLReader} instances.</p>
<p>To obtain a {@link javax.xml.transform.sax.SAXTransformerFactory},
the caller must cast the {@link javax.xml.transform.TransformerFactory}
instance returned from
{@link javax.xml.transform.TransformerFactory#newInstance}.
<p>The {@link javax.xml.transform.sax.TransformerHandler} interface
allows a transformation to be created from SAX2 parse events, which is a "push"
model rather than the "pull" model that normally occurs for a transformation.
Normal parse events are received through the
{@link org.xml.sax.ContentHandler} interface, lexical events such as
startCDATA and endCDATA are received through the
{@link org.xml.sax.ext.LexicalHandler} interface, and events that signal
the start or end of disabling output escaping are received via
{@link org.xml.sax.ContentHandler#processingInstruction}, with the
target parameter being
{@link javax.xml.transform.Result#PI_DISABLE_OUTPUT_ESCAPING} and
{@link javax.xml.transform.Result#PI_ENABLE_OUTPUT_ESCAPING}. If
parameters, output properties, or other features need to be set on the
Transformer handler, a {@link javax.xml.transform.Transformer} reference
will need to be obtained from
{@link javax.xml.transform.sax.TransformerHandler#getTransformer}, and
the methods invoked from that reference.
<p>The {@link javax.xml.transform.sax.TemplatesHandler} interface
allows the creation of {@link javax.xml.transform.Templates} objects
from SAX2 parse events. Once the {@link org.xml.sax.ContentHandler}
events are complete, the Templates object may be obtained from
{@link javax.xml.transform.sax.TemplatesHandler#getTemplates}. Note that
{@link javax.xml.transform.sax.TemplatesHandler#setSystemId} should
normally be called in order to establish a base system ID from which relative
URLs may be resolved.
<p>The
{@link javax.xml.transform.sax.SAXTransformerFactory#newXMLFilter}
method allows the creation of a {@link org.xml.sax.XMLFilter}, which
encapsulates the SAX2 notion of a "pull" transformation. The following
illustrates several transformations chained together. Each filter points to a
parent {@link org.xml.sax.XMLReader}, and the final transformation is
caused by invoking {@link org.xml.sax.XMLReader#parse} on the final
reader in the chain.</p>
</body>
</html>

View file

@ -0,0 +1,183 @@
/*
* Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform.stax;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.Result;
/**
* <p>Acts as a holder for an XML {@link Result} in the
* form of a StAX writer,i.e.
* {@link XMLStreamWriter} or {@link XMLEventWriter}.
* <code>StAXResult</code> can be used in all cases that accept
* a <code>Result</code>, e.g. {@link javax.xml.transform.Transformer},
* {@link javax.xml.validation.Validator} which accept
* <code>Result</code> as input.
*
* @author <a href="mailto:Neeraj.Bajaj@Sun.com">Neeraj Bajaj</a>
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
*
* @see <a href="http://jcp.org/en/jsr/detail?id=173">
* JSR 173: Streaming API for XML</a>
* @see XMLStreamWriter
* @see XMLEventWriter
*
* @since 1.6
*/
public class StAXResult implements Result {
/** If {@link javax.xml.transform.TransformerFactory#getFeature(String name)}
* returns true when passed this value as an argument,
* the Transformer supports Result output of this type.
*/
public static final String FEATURE =
"http://javax.xml.transform.stax.StAXResult/feature";
/**
* <p><code>XMLEventWriter</code> to be used for
* <code>Result</code> output.</p>
*/
private XMLEventWriter xmlEventWriter = null;
/**
* <p><code>XMLStreamWriter</code> to be used for
* <code>Result</code> output.</p>
*/
private XMLStreamWriter xmlStreamWriter = null;
/** <p>System identifier for this <code>StAXResult</code>.<p> */
private String systemId = null;
/**
* <p>Creates a new instance of a <code>StAXResult</code>
* by supplying an {@link XMLEventWriter}.</p>
*
* <p><code>XMLEventWriter</code> must be a
* non-<code>null</code> reference.</p>
*
* @param xmlEventWriter <code>XMLEventWriter</code> used to create
* this <code>StAXResult</code>.
*
* @throws IllegalArgumentException If <code>xmlEventWriter</code> ==
* <code>null</code>.
*/
public StAXResult(final XMLEventWriter xmlEventWriter) {
if (xmlEventWriter == null) {
throw new IllegalArgumentException(
"StAXResult(XMLEventWriter) with XMLEventWriter == null");
}
this.xmlEventWriter = xmlEventWriter;
}
/**
* <p>Creates a new instance of a <code>StAXResult</code>
* by supplying an {@link XMLStreamWriter}.</p>
*
* <p><code>XMLStreamWriter</code> must be a
* non-<code>null</code> reference.</p>
*
* @param xmlStreamWriter <code>XMLStreamWriter</code> used to create
* this <code>StAXResult</code>.
*
* @throws IllegalArgumentException If <code>xmlStreamWriter</code> ==
* <code>null</code>.
*/
public StAXResult(final XMLStreamWriter xmlStreamWriter) {
if (xmlStreamWriter == null) {
throw new IllegalArgumentException(
"StAXResult(XMLStreamWriter) with XMLStreamWriter == null");
}
this.xmlStreamWriter = xmlStreamWriter;
}
/**
* <p>Get the <code>XMLEventWriter</code> used by this
* <code>StAXResult</code>.</p>
*
* <p><code>XMLEventWriter</code> will be <code>null</code>
* if this <code>StAXResult</code> was created with a
* <code>XMLStreamWriter</code>.</p>
*
* @return <code>XMLEventWriter</code> used by this
* <code>StAXResult</code>.
*/
public XMLEventWriter getXMLEventWriter() {
return xmlEventWriter;
}
/**
* <p>Get the <code>XMLStreamWriter</code> used by this
* <code>StAXResult</code>.</p>
*
* <p><code>XMLStreamWriter</code> will be <code>null</code>
* if this <code>StAXResult</code> was created with a
* <code>XMLEventWriter</code>.</p>
*
* @return <code>XMLStreamWriter</code> used by this
* <code>StAXResult</code>.
*/
public XMLStreamWriter getXMLStreamWriter() {
return xmlStreamWriter;
}
/**
* <p>In the context of a <code>StAXResult</code>, it is not appropriate
* to explicitly set the system identifier.
* The <code>XMLEventWriter</code> or <code>XMLStreamWriter</code>
* used to construct this <code>StAXResult</code> determines the
* system identifier of the XML result.</p>
*
* <p>An {@link UnsupportedOperationException} is <strong>always</strong>
* thrown by this method.</p>
*
* @param systemId Ignored.
*
* @throws UnsupportedOperationException Is <strong>always</strong>
* thrown by this method.
*/
public void setSystemId(final String systemId) {
throw new UnsupportedOperationException(
"StAXResult#setSystemId(systemId) cannot set the "
+ "system identifier for a StAXResult");
}
/**
* <p>The returned system identifier is always <code>null</code>.</p>
*
* @return The returned system identifier is always <code>null</code>.
*/
public String getSystemId() {
return null;
}
}

View file

@ -0,0 +1,236 @@
/*
* Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform.stax;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.Source;
/**
* <p>Acts as a holder for an XML {@link Source} in the
* form of a StAX reader,i.e.
* {@link XMLStreamReader} or {@link XMLEventReader}.
* <code>StAXSource</code> can be used in all cases that accept
* a <code>Source</code>, e.g. {@link javax.xml.transform.Transformer},
* {@link javax.xml.validation.Validator} which accept
* <code>Source</code> as input.
*
* <p><code>StAXSource</code>s are consumed during processing
* and are not reusable.</p>
*
* @author <a href="mailto:Neeraj.Bajaj@Sun.com">Neeraj Bajaj</a>
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
*
* @see <a href="http://jcp.org/en/jsr/detail?id=173">
* JSR 173: Streaming API for XML</a>
* @see XMLStreamReader
* @see XMLEventReader
*
* @since 1.6
*/
public class StAXSource implements Source {
/** If {@link javax.xml.transform.TransformerFactory#getFeature(String name)}
* returns true when passed this value as an argument,
* the Transformer supports Source input of this type.
*/
public static final String FEATURE =
"http://javax.xml.transform.stax.StAXSource/feature";
/** <p><code>XMLEventReader</code> to be used for source input.</p> */
private XMLEventReader xmlEventReader = null;
/** <p><code>XMLStreamReader</code> to be used for source input.</p> */
private XMLStreamReader xmlStreamReader = null;
/** <p>System identifier of source input.</p> */
private String systemId = null;
/**
* <p>Creates a new instance of a <code>StAXSource</code>
* by supplying an {@link XMLEventReader}.</p>
*
* <p><code>XMLEventReader</code> must be a
* non-<code>null</code> reference.</p>
*
* <p><code>XMLEventReader</code> must be in
* {@link XMLStreamConstants#START_DOCUMENT} or
* {@link XMLStreamConstants#START_ELEMENT} state.</p>
*
* @param xmlEventReader <code>XMLEventReader</code> used to create
* this <code>StAXSource</code>.
*
* @throws XMLStreamException If <code>xmlEventReader</code> access
* throws an <code>Exception</code>.
* @throws IllegalArgumentException If <code>xmlEventReader</code> ==
* <code>null</code>.
* @throws IllegalStateException If <code>xmlEventReader</code>
* is not in <code>XMLStreamConstants.START_DOCUMENT</code> or
* <code>XMLStreamConstants.START_ELEMENT</code> state.
*/
public StAXSource(final XMLEventReader xmlEventReader)
throws XMLStreamException {
if (xmlEventReader == null) {
throw new IllegalArgumentException(
"StAXSource(XMLEventReader) with XMLEventReader == null");
}
// TODO: This is ugly ...
// there is no way to know the current position(event) of
// XMLEventReader. peek() is the only way to know the next event.
// The next event on the input stream should be
// XMLStreamConstants.START_DOCUMENT or
// XMLStreamConstants.START_ELEMENT.
XMLEvent event = xmlEventReader.peek();
int eventType = event.getEventType();
if (eventType != XMLStreamConstants.START_DOCUMENT
&& eventType != XMLStreamConstants.START_ELEMENT) {
throw new IllegalStateException(
"StAXSource(XMLEventReader) with XMLEventReader "
+ "not in XMLStreamConstants.START_DOCUMENT or "
+ "XMLStreamConstants.START_ELEMENT state");
}
this.xmlEventReader = xmlEventReader;
systemId = event.getLocation().getSystemId();
}
/**
* <p>Creates a new instance of a <code>StAXSource</code>
* by supplying an {@link XMLStreamReader}.</p>
*
* <p><code>XMLStreamReader</code> must be a
* non-<code>null</code> reference.</p>
*
* <p><code>XMLStreamReader</code> must be in
* {@link XMLStreamConstants#START_DOCUMENT} or
* {@link XMLStreamConstants#START_ELEMENT} state.</p>
*
* @param xmlStreamReader <code>XMLStreamReader</code> used to create
* this <code>StAXSource</code>.
*
* @throws IllegalArgumentException If <code>xmlStreamReader</code> ==
* <code>null</code>.
* @throws IllegalStateException If <code>xmlStreamReader</code>
* is not in <code>XMLStreamConstants.START_DOCUMENT</code> or
* <code>XMLStreamConstants.START_ELEMENT</code> state.
*/
public StAXSource(final XMLStreamReader xmlStreamReader) {
if (xmlStreamReader == null) {
throw new IllegalArgumentException(
"StAXSource(XMLStreamReader) with XMLStreamReader == null");
}
int eventType = xmlStreamReader.getEventType();
if (eventType != XMLStreamConstants.START_DOCUMENT
&& eventType != XMLStreamConstants.START_ELEMENT) {
throw new IllegalStateException(
"StAXSource(XMLStreamReader) with XMLStreamReader"
+ "not in XMLStreamConstants.START_DOCUMENT or "
+ "XMLStreamConstants.START_ELEMENT state");
}
this.xmlStreamReader = xmlStreamReader;
systemId = xmlStreamReader.getLocation().getSystemId();
}
/**
* <p>Get the <code>XMLEventReader</code> used by this
* <code>StAXSource</code>.</p>
*
* <p><code>XMLEventReader</code> will be <code>null</code>.
* if this <code>StAXSource</code> was created with a
* <code>XMLStreamReader</code>.</p>
*
* @return <code>XMLEventReader</code> used by this
* <code>StAXSource</code>.
*/
public XMLEventReader getXMLEventReader() {
return xmlEventReader;
}
/**
* <p>Get the <code>XMLStreamReader</code> used by this
* <code>StAXSource</code>.</p>
*
* <p><code>XMLStreamReader</code> will be <code>null</code>
* if this <code>StAXSource</code> was created with a
* <code>XMLEventReader</code>.</p>
*
* @return <code>XMLStreamReader</code> used by this
* <code>StAXSource</code>.
*/
public XMLStreamReader getXMLStreamReader() {
return xmlStreamReader;
}
/**
* <p>In the context of a <code>StAXSource</code>, it is not appropriate
* to explicitly set the system identifier.
* The <code>XMLStreamReader</code> or <code>XMLEventReader</code>
* used to construct this <code>StAXSource</code> determines the
* system identifier of the XML source.</p>
*
* <p>An {@link UnsupportedOperationException} is <strong>always</strong>
* thrown by this method.</p>
*
* @param systemId Ignored.
*
* @throws UnsupportedOperationException Is <strong>always</strong>
* thrown by this method.
*/
public void setSystemId(final String systemId) {
throw new UnsupportedOperationException(
"StAXSource#setSystemId(systemId) cannot set the "
+ "system identifier for a StAXSource");
}
/**
* <p>Get the system identifier used by this
* <code>StAXSource</code>.</p>
*
* <p>The <code>XMLStreamReader</code> or <code>XMLEventReader</code>
* used to construct this <code>StAXSource</code> is queried to determine
* the system identifier of the XML source.</p>
*
* <p>The system identifier may be <code>null</code> or
* an empty <code>""</code> <code>String</code>.</p>
*
* @return System identifier used by this <code>StAXSource</code>.
*/
public String getSystemId() {
return systemId;
}
}

View file

@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation. Sun designates this
particular file as subject to the "Classpath" exception as provided
by Sun in the LICENSE file that accompanied this code.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
CA 95054 USA or visit www.sun.com if you need additional information or
have any questions.
-->
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>javax.xml.transform.stax</title>
<meta name="CVS"
content="$Id: package.html,v 1.2 2005/11/03 19:34:28 jeffsuttor Exp $" />
<meta name="AUTHOR"
content="Jeff.Suttor@Sun.com" />
<meta name="AUTHOR"
content="Neeraj.Bajaj@Sun.com" />
</head>
<body>
<p>
Provides for StAX-specific transformation APIs.
TODO: better description(s).
</p>
<h2>Package Specification</h2>
<ul>
<li><a href="http://jcp.org/en/jsr/detail?id=173">JSR 173: Streaming API for XML</a></li>
</ul>
<h2>Related Documentation</h2>
<p>For overviews, tutorials, examples, guides, and tool documentation, please see:</p>
<ul>
<li><a href="">TODO: Refer to non-spec documentation</a></li>
</ul>
<!-- Put @see and @since tags down here. -->
<ul>
<li>@see XMLStreamReader</li>
<li>@see XMLEventReader</li>
</ul>
<p>
@since 1.6
</p>
</body>
</html>

View file

@ -0,0 +1,203 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform.stream;
import javax.xml.transform.Result;
import java.io.File;
import java.io.OutputStream;
import java.io.Writer;
import java.net.MalformedURLException;
/**
* <p>Acts as an holder for a transformation result,
* which may be XML, plain Text, HTML, or some other form of markup.</p>
*
* @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
*/
public class StreamResult implements Result {
/** If {@link javax.xml.transform.TransformerFactory#getFeature}
* returns true when passed this value as an argument,
* the Transformer supports Result output of this type.
*/
public static final String FEATURE =
"http://javax.xml.transform.stream.StreamResult/feature";
/**
* Zero-argument default constructor.
*/
public StreamResult() {
}
/**
* Construct a StreamResult from a byte stream. Normally,
* a stream should be used rather than a reader, so that
* the transformer may use instructions contained in the
* transformation instructions to control the encoding.
*
* @param outputStream A valid OutputStream reference.
*/
public StreamResult(OutputStream outputStream) {
setOutputStream(outputStream);
}
/**
* Construct a StreamResult from a character stream. Normally,
* a stream should be used rather than a reader, so that
* the transformer may use instructions contained in the
* transformation instructions to control the encoding. However,
* there are times when it is useful to write to a character
* stream, such as when using a StringWriter.
*
* @param writer A valid Writer reference.
*/
public StreamResult(Writer writer) {
setWriter(writer);
}
/**
* Construct a StreamResult from a URL.
*
* @param systemId Must be a String that conforms to the URI syntax.
*/
public StreamResult(String systemId) {
this.systemId = systemId;
}
/**
* Construct a StreamResult from a File.
*
* @param f Must a non-null File reference.
*/
public StreamResult(File f) {
//convert file to appropriate URI, f.toURI().toASCIIString()
//converts the URI to string as per rule specified in
//RFC 2396,
setSystemId(f.toURI().toASCIIString());
}
/**
* Set the ByteStream that is to be written to. Normally,
* a stream should be used rather than a reader, so that
* the transformer may use instructions contained in the
* transformation instructions to control the encoding.
*
* @param outputStream A valid OutputStream reference.
*/
public void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
/**
* Get the byte stream that was set with setOutputStream.
*
* @return The byte stream that was set with setOutputStream, or null
* if setOutputStream or the ByteStream constructor was not called.
*/
public OutputStream getOutputStream() {
return outputStream;
}
/**
* Set the writer that is to receive the result. Normally,
* a stream should be used rather than a writer, so that
* the transformer may use instructions contained in the
* transformation instructions to control the encoding. However,
* there are times when it is useful to write to a writer,
* such as when using a StringWriter.
*
* @param writer A valid Writer reference.
*/
public void setWriter(Writer writer) {
this.writer = writer;
}
/**
* Get the character stream that was set with setWriter.
*
* @return The character stream that was set with setWriter, or null
* if setWriter or the Writer constructor was not called.
*/
public Writer getWriter() {
return writer;
}
/**
* Set the systemID that may be used in association
* with the byte or character stream, or, if neither is set, use
* this value as a writeable URI (probably a file name).
*
* @param systemId The system identifier as a URI string.
*/
public void setSystemId(String systemId) {
this.systemId = systemId;
}
/**
* <p>Set the system ID from a <code>File</code> reference.</p>
*
*
* @param f Must a non-null File reference.
*/
public void setSystemId(File f) {
//convert file to appropriate URI, f.toURI().toASCIIString()
//converts the URI to string as per rule specified in
//RFC 2396,
this.systemId = f.toURI().toASCIIString();
}
/**
* Get the system identifier that was set with setSystemId.
*
* @return The system identifier that was set with setSystemId, or null
* if setSystemId was not called.
*/
public String getSystemId() {
return systemId;
}
//////////////////////////////////////////////////////////////////////
// Internal state.
//////////////////////////////////////////////////////////////////////
/**
* The systemID that may be used in association
* with the byte or character stream, or, if neither is set, use
* this value as a writeable URI (probably a file name).
*/
private String systemId;
/**
* The byte stream that is to be written to.
*/
private OutputStream outputStream;
/**
* The character stream that is to be written to.
*/
private Writer writer;
}

View file

@ -0,0 +1,284 @@
/*
* Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.transform.stream;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import javax.xml.transform.Source;
/**
* <p>Acts as an holder for a transformation Source in the form
* of a stream of XML markup.</p>
*
* <p><em>Note:</em> Due to their internal use of either a {@link Reader} or {@link InputStream} instance,
* <code>StreamSource</code> instances may only be used once.</p>
*
* @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
*/
public class StreamSource implements Source {
/** If {@link javax.xml.transform.TransformerFactory#getFeature}
* returns true when passed this value as an argument,
* the Transformer supports Source input of this type.
*/
public static final String FEATURE =
"http://javax.xml.transform.stream.StreamSource/feature";
/**
* <p>Zero-argument default constructor. If this constructor is used, and
* no Stream source is set using
* {@link #setInputStream(java.io.InputStream inputStream)} or
* {@link #setReader(java.io.Reader reader)}, then the
* <code>Transformer</code> will
* create an empty source {@link java.io.InputStream} using
* {@link java.io.InputStream#InputStream() new InputStream()}.</p>
*
* @see javax.xml.transform.Transformer#transform(Source xmlSource, Result outputTarget)
*/
public StreamSource() { }
/**
* Construct a StreamSource from a byte stream. Normally,
* a stream should be used rather than a reader, so
* the XML parser can resolve character encoding specified
* by the XML declaration.
*
* <p>If this constructor is used to process a stylesheet, normally
* setSystemId should also be called, so that relative URI references
* can be resolved.</p>
*
* @param inputStream A valid InputStream reference to an XML stream.
*/
public StreamSource(InputStream inputStream) {
setInputStream(inputStream);
}
/**
* Construct a StreamSource from a byte stream. Normally,
* a stream should be used rather than a reader, so that
* the XML parser can resolve character encoding specified
* by the XML declaration.
*
* <p>This constructor allows the systemID to be set in addition
* to the input stream, which allows relative URIs
* to be processed.</p>
*
* @param inputStream A valid InputStream reference to an XML stream.
* @param systemId Must be a String that conforms to the URI syntax.
*/
public StreamSource(InputStream inputStream, String systemId) {
setInputStream(inputStream);
setSystemId(systemId);
}
/**
* Construct a StreamSource from a character reader. Normally,
* a stream should be used rather than a reader, so that
* the XML parser can resolve character encoding specified
* by the XML declaration. However, in many cases the encoding
* of the input stream is already resolved, as in the case of
* reading XML from a StringReader.
*
* @param reader A valid Reader reference to an XML character stream.
*/
public StreamSource(Reader reader) {
setReader(reader);
}
/**
* Construct a StreamSource from a character reader. Normally,
* a stream should be used rather than a reader, so that
* the XML parser may resolve character encoding specified
* by the XML declaration. However, in many cases the encoding
* of the input stream is already resolved, as in the case of
* reading XML from a StringReader.
*
* @param reader A valid Reader reference to an XML character stream.
* @param systemId Must be a String that conforms to the URI syntax.
*/
public StreamSource(Reader reader, String systemId) {
setReader(reader);
setSystemId(systemId);
}
/**
* Construct a StreamSource from a URL.
*
* @param systemId Must be a String that conforms to the URI syntax.
*/
public StreamSource(String systemId) {
this.systemId = systemId;
}
/**
* Construct a StreamSource from a File.
*
* @param f Must a non-null File reference.
*/
public StreamSource(File f) {
//convert file to appropriate URI, f.toURI().toASCIIString()
//converts the URI to string as per rule specified in
//RFC 2396,
setSystemId(f.toURI().toASCIIString());
}
/**
* Set the byte stream to be used as input. Normally,
* a stream should be used rather than a reader, so that
* the XML parser can resolve character encoding specified
* by the XML declaration.
*
* <p>If this Source object is used to process a stylesheet, normally
* setSystemId should also be called, so that relative URL references
* can be resolved.</p>
*
* @param inputStream A valid InputStream reference to an XML stream.
*/
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
/**
* Get the byte stream that was set with setByteStream.
*
* @return The byte stream that was set with setByteStream, or null
* if setByteStream or the ByteStream constructor was not called.
*/
public InputStream getInputStream() {
return inputStream;
}
/**
* Set the input to be a character reader. Normally,
* a stream should be used rather than a reader, so that
* the XML parser can resolve character encoding specified
* by the XML declaration. However, in many cases the encoding
* of the input stream is already resolved, as in the case of
* reading XML from a StringReader.
*
* @param reader A valid Reader reference to an XML CharacterStream.
*/
public void setReader(Reader reader) {
this.reader = reader;
}
/**
* Get the character stream that was set with setReader.
*
* @return The character stream that was set with setReader, or null
* if setReader or the Reader constructor was not called.
*/
public Reader getReader() {
return reader;
}
/**
* Set the public identifier for this Source.
*
* <p>The public identifier is always optional: if the application
* writer includes one, it will be provided as part of the
* location information.</p>
*
* @param publicId The public identifier as a string.
*/
public void setPublicId(String publicId) {
this.publicId = publicId;
}
/**
* Get the public identifier that was set with setPublicId.
*
* @return The public identifier that was set with setPublicId, or null
* if setPublicId was not called.
*/
public String getPublicId() {
return publicId;
}
/**
* Set the system identifier for this Source.
*
* <p>The system identifier is optional if there is a byte stream
* or a character stream, but it is still useful to provide one,
* since the application can use it to resolve relative URIs
* and can include it in error messages and warnings (the parser
* will attempt to open a connection to the URI only if
* there is no byte stream or character stream specified).</p>
*
* @param systemId The system identifier as a URL string.
*/
public void setSystemId(String systemId) {
this.systemId = systemId;
}
/**
* Get the system identifier that was set with setSystemId.
*
* @return The system identifier that was set with setSystemId, or null
* if setSystemId was not called.
*/
public String getSystemId() {
return systemId;
}
/**
* Set the system ID from a File reference.
*
* @param f Must a non-null File reference.
*/
public void setSystemId(File f) {
//convert file to appropriate URI, f.toURI().toASCIIString()
//converts the URI to string as per rule specified in
//RFC 2396,
this.systemId = f.toURI().toASCIIString();
}
//////////////////////////////////////////////////////////////////////
// Internal state.
//////////////////////////////////////////////////////////////////////
/**
* The public identifier for this input source, or null.
*/
private String publicId;
/**
* The system identifier as a URL string, or null.
*/
private String systemId;
/**
* The byte stream for this Source, or null.
*/
private InputStream inputStream;
/**
* The character stream for this Source, or null.
*/
private Reader reader;
}

View file

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2000-2005 Sun Microsystems, Inc. All Rights Reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation. Sun designates this
particular file as subject to the "Classpath" exception as provided
by Sun in the LICENSE file that accompanied this code.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
CA 95054 USA or visit www.sun.com if you need additional information or
have any questions.
-->
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>javax.xml.transform.stream</title>
<meta name="CVS"
content="$Id: package.html,v 1.2 2005/06/10 03:50:42 jeffsuttor Exp $" />
<meta name="AUTHOR"
content="Jeff.Suttor@Sun.com" />
</head>
<body>
<p>This package implements stream- and URI- specific transformation APIs.
</p>
<p>The {@link javax.xml.transform.stream.StreamSource} class
provides methods for specifying {@link java.io.InputStream} input,
{@link java.io.Reader} input, and URL input in the form of strings. Even
if an input stream or reader is specified as the source,
{@link javax.xml.transform.stream.StreamSource#setSystemId} should still
be called, so that the transformer can know from where it should resolve
relative URIs. The public identifier is always optional: if the application
writer includes one, it will be provided as part of the
{@link javax.xml.transform.SourceLocator} information.</p>
<p>The {@link javax.xml.transform.stream.StreamResult} class
provides methods for specifying {@link java.io.OutputStream},
{@link java.io.Writer}, or an output system ID, as the output of the
transformation result.</p>
<p>Normally streams should be used rather than readers or writers, for
both the Source and Result, since readers and writers already have the encoding
established to and from the internal Unicode format. However, there are times
when it is useful to write to a character stream, such as when using a
StringWriter in order to write to a String, or in the case of reading source
XML from a StringReader.</p>
</body>
</html>

View file

@ -0,0 +1,104 @@
/*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.validation;
/**
* Immutable in-memory representation of grammar.
*
* <p>
* This object represents a set of constraints that can be checked/
* enforced against an XML document.
*
* <p>
* A {@link Schema} object is thread safe and applications are
* encouraged to share it across many parsers in many threads.
*
* <p>
* A {@link Schema} object is immutable in the sense that it shouldn't
* change the set of constraints once it is created. In other words,
* if an application validates the same document twice against the same
* {@link Schema}, it must always produce the same result.
*
* <p>
* A {@link Schema} object is usually created from {@link SchemaFactory}.
*
* <p>
* Two kinds of validators can be created from a {@link Schema} object.
* One is {@link Validator}, which provides highly-level validation
* operations that cover typical use cases. The other is
* {@link ValidatorHandler}, which works on top of SAX for better
* modularity.
*
* <p>
* This specification does not refine
* the {@link java.lang.Object#equals(java.lang.Object)} method.
* In other words, if you parse the same schema twice, you may
* still get <code>!schemaA.equals(schemaB)</code>.
*
* @author <a href="mailto:Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
* @see <a href="http://www.w3.org/TR/xmlschema-1/">XML Schema Part 1: Structures</a>
* @see <a href="http://www.w3.org/TR/xml11/">Extensible Markup Language (XML) 1.1</a>
* @see <a href="http://www.w3.org/TR/REC-xml">Extensible Markup Language (XML) 1.0 (Second Edition)</a>
* @since 1.5
*/
public abstract class Schema {
/**
* Constructor for the derived class.
*
* <p>
* The constructor does nothing.
*/
protected Schema() {
}
/**
* Creates a new {@link Validator} for this {@link Schema}.
*
* <p>A validator enforces/checks the set of constraints this object
* represents.</p>
*
* <p>Implementors should assure that the properties set on the
* {@link SchemaFactory} that created this {@link Schema} are also
* set on the {@link Validator} constructed.</p>
*
* @return
* Always return a non-null valid object.
*/
public abstract Validator newValidator();
/**
* Creates a new {@link ValidatorHandler} for this {@link Schema}.
*
* <p>Implementors should assure that the properties set on the
* {@link SchemaFactory} that created this {@link Schema} are also
* set on the {@link ValidatorHandler} constructed.</p>
*
* @return
* Always return a non-null valid object.
*/
public abstract ValidatorHandler newValidatorHandler();
}

View file

@ -0,0 +1,753 @@
/*
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.validation;
import java.io.File;
import java.net.URL;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
/**
* Factory that creates {@link Schema} objects&#x2E; Entry-point to
* the validation API.
*
* <p>
* {@link SchemaFactory} is a schema compiler. It reads external
* representations of schemas and prepares them for validation.
*
* <p>
* The {@link SchemaFactory} class is not thread-safe. In other words,
* it is the application's responsibility to ensure that at most
* one thread is using a {@link SchemaFactory} object at any
* given moment. Implementations are encouraged to mark methods
* as <code>synchronized</code> to protect themselves from broken clients.
*
* <p>
* {@link SchemaFactory} is not re-entrant. While one of the
* <code>newSchema</code> methods is being invoked, applications
* may not attempt to recursively invoke the <code>newSchema</code> method,
* even from the same thread.
*
* <h2><a name="schemaLanguage"></a>Schema Language</h2>
* <p>
* This spec uses a namespace URI to designate a schema language.
* The following table shows the values defined by this specification.
* <p>
* To be compliant with the spec, the implementation
* is only required to support W3C XML Schema 1.0. However,
* if it chooses to support other schema languages listed here,
* it must conform to the relevant behaviors described in this spec.
*
* <p>
* Schema languages not listed here are expected to
* introduce their own URIs to represent themselves.
* The {@link SchemaFactory} class is capable of locating other
* implementations for other schema languages at run-time.
*
* <p>
* Note that because the XML DTD is strongly tied to the parsing process
* and has a significant effect on the parsing process, it is impossible
* to define the DTD validation as a process independent from parsing.
* For this reason, this specification does not define the semantics for
* the XML DTD. This doesn't prohibit implentors from implementing it
* in a way they see fit, but <em>users are warned that any DTD
* validation implemented on this interface necessarily deviate from
* the XML DTD semantics as defined in the XML 1.0</em>.
*
* <table border="1" cellpadding="2">
* <thead>
* <tr>
* <th>value</th>
* <th>language</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>{@link javax.xml.XMLConstants#W3C_XML_SCHEMA_NS_URI} ("<code>http://www.w3.org/2001/XMLSchema</code>")</td>
* <td><a href="http://www.w3.org/TR/xmlschema-1">W3C XML Schema 1.0</a></td>
* </tr>
* <tr>
* <td>{@link javax.xml.XMLConstants#RELAXNG_NS_URI} ("<code>http://relaxng.org/ns/structure/1.0</code>")</td>
* <td><a href="http://www.relaxng.org/">RELAX NG 1.0</a></td>
* </tr>
* </tbody>
* </table>
*
* @author <a href="mailto:Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
* @author <a href="mailto:Neeraj.Bajaj@sun.com">Neeraj Bajaj</a>
*
* @since 1.5
*/
public abstract class SchemaFactory {
private static SecuritySupport ss = new SecuritySupport();
/**
* <p>Constructor for derived classes.</p>
*
* <p>The constructor does nothing.</p>
*
* <p>Derived classes must create {@link SchemaFactory} objects that have
* <code>null</code> {@link ErrorHandler} and
* <code>null</code> {@link LSResourceResolver}.</p>
*/
protected SchemaFactory() {
}
/**
* <p>Lookup an implementation of the <code>SchemaFactory</code> that supports the specified
* schema language and return it.</p>
*
* <p>To find a <code>SchemaFactory</code> object for a given schema language,
* this method looks the following places in the following order
* where "the class loader" refers to the context class loader:</p>
* <ol>
* <li>
* If the system property
* <code>"javax.xml.validation.SchemaFactory:<i>schemaLanguage</i>"</code>
* is present (where <i>schemaLanguage</i> is the parameter
* to this method), then its value is read
* as a class name. The method will try to
* create a new instance of this class by using the class loader,
* and returns it if it is successfully created.
* </li>
* <li>
* <code>$java.home/lib/jaxp.properties</code> is read and
* the value associated with the key being the system property above
* is looked for. If present, the value is processed just like above.
* </li>
* <li>
* <p>The class loader is asked for service provider provider-configuration files matching
* <code>javax.xml.validation.SchemaFactory</code> in the resource directory META-INF/services.
* See the JAR File Specification for file format and parsing rules.
* Each potential service provider is required to implement the method:</p>
* <pre>
* {@link #isSchemaLanguageSupported(String schemaLanguage)}
* </pre>
* The first service provider found in class loader order that supports the specified schema language is returned.
* </li>
* <li>
* Platform default <code>SchemaFactory</code> is located
* in a implementation specific way. There must be a platform default
* <code>SchemaFactory</code> for W3C XML Schema.
* </li>
* </ol>
*
* <p>If everything fails, {@link IllegalArgumentException} will be thrown.</p>
*
* <p><strong>Tip for Trouble-shooting:</strong></p>
* <p>See {@link java.util.Properties#load(java.io.InputStream)} for
* exactly how a property file is parsed. In particular, colons ':'
* need to be escaped in a property file, so make sure schema language
* URIs are properly escaped in it. For example:</p>
* <pre>
* http\://www.w3.org/2001/XMLSchema=org.acme.foo.XSSchemaFactory
* </pre>
*
* @param schemaLanguage
* Specifies the schema language which the returned
* SchemaFactory will understand. See
* <a href="#schemaLanguage">the list of available
* schema languages</a> for the possible values.
*
* @return New instance of a <code>SchemaFactory</code>
*
* @throws IllegalArgumentException
* If no implementation of the schema language is available.
* @throws NullPointerException
* If the <code>schemaLanguage</code> parameter is null.
*
* @see #newInstance(String schemaLanguage, String factoryClassName, ClassLoader classLoader)
*/
public static final SchemaFactory newInstance(String schemaLanguage) {
ClassLoader cl;
cl = ss.getContextClassLoader();
if (cl == null) {
//cl = ClassLoader.getSystemClassLoader();
//use the current class loader
cl = SchemaFactory.class.getClassLoader();
}
SchemaFactory f = new SchemaFactoryFinder(cl).newFactory(schemaLanguage);
if (f == null) {
throw new IllegalArgumentException(
"No SchemaFactory"
+ " that implements the schema language specified by: " + schemaLanguage
+ " could be loaded");
}
return f;
}
/**
* <p>Obtain a new instance of a <code>SchemaFactory</code> from class name. <code>SchemaFactory</code>
* is returned if specified factory class name supports the specified schema language.
* This function is useful when there are multiple providers in the classpath.
* It gives more control to the application as it can specify which provider
* should be loaded.</p>
*
* <h2>Tip for Trouble-shooting</h2>
* <p>Setting the <code>jaxp.debug</code> system property will cause
* this method to print a lot of debug messages
* to <code>System.err</code> about what it is doing and where it is looking at.</p>
*
* <p> If you have problems try:</p>
* <pre>
* java -Djaxp.debug=1 YourProgram ....
* </pre>
*
* @param schemaLanguage Specifies the schema language which the returned
* <code>SchemaFactory</code> will understand. See
* <a href="#schemaLanguage">the list of available
* schema languages</a> for the possible values.
*
* @param factoryClassName fully qualified factory class name that provides implementation of <code>javax.xml.validation.SchemaFactory</code>.
*
* @param classLoader <code>ClassLoader</code> used to load the factory class. If <code>null</code>
* current <code>Thread</code>'s context classLoader is used to load the factory class.
*
* @return New instance of a <code>SchemaFactory</code>
*
* @throws IllegalArgumentException
* if <code>factoryClassName</code> is <code>null</code>, or
* the factory class cannot be loaded, instantiated or doesn't
* support the schema language specified in <code>schemLanguage</code>
* parameter.
*
* @throws NullPointerException
* If the <code>schemaLanguage</code> parameter is null.
*
* @see #newInstance(String schemaLanguage)
*
* @since 1.6
*/
public static SchemaFactory newInstance(String schemaLanguage, String factoryClassName, ClassLoader classLoader){
ClassLoader cl = classLoader;
if (cl == null) {
cl = ss.getContextClassLoader();
}
SchemaFactory f = new SchemaFactoryFinder(cl).createInstance(factoryClassName);
if (f == null) {
throw new IllegalArgumentException(
"Factory " + factoryClassName
+ " could not be loaded to implement the schema language specified by: " + schemaLanguage);
}
//if this factory supports the given schemalanguage return this factory else thrown exception
if(f.isSchemaLanguageSupported(schemaLanguage)){
return f;
}else{
throw new IllegalArgumentException(
"Factory " + f.getClass().getName()
+ " does not implement the schema language specified by: " + schemaLanguage);
}
}
/**
* <p>Is specified schema supported by this <code>SchemaFactory</code>?</p>
*
* @param schemaLanguage Specifies the schema language which the returned <code>SchemaFactory</code> will understand.
* <code>schemaLanguage</code> must specify a <a href="#schemaLanguage">valid</a> schema language.
*
* @return <code>true</code> if <code>SchemaFactory</code> supports <code>schemaLanguage</code>, else <code>false</code>.
*
* @throws NullPointerException If <code>schemaLanguage</code> is <code>null</code>.
* @throws IllegalArgumentException If <code>schemaLanguage.length() == 0</code>
* or <code>schemaLanguage</code> does not specify a <a href="#schemaLanguage">valid</a> schema language.
*/
public abstract boolean isSchemaLanguageSupported(String schemaLanguage);
/**
* Look up the value of a feature flag.
*
* <p>The feature name is any fully-qualified URI. It is
* possible for a {@link SchemaFactory} to recognize a feature name but
* temporarily be unable to return its value.
*
* <p>Implementors are free (and encouraged) to invent their own features,
* using names built on their own URIs.</p>
*
* @param name The feature name, which is a non-null fully-qualified URI.
*
* @return The current value of the feature (true or false).
*
* @throws SAXNotRecognizedException If the feature
* value can't be assigned or retrieved.
* @throws SAXNotSupportedException When the
* {@link SchemaFactory} recognizes the feature name but
* cannot determine its value at this time.
* @throws NullPointerException If <code>name</code> is <code>null</code>.
*
* @see #setFeature(String, boolean)
*/
public boolean getFeature(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException("the name parameter is null");
}
throw new SAXNotRecognizedException(name);
}
/**
* <p>Set a feature for this <code>SchemaFactory</code>,
* {@link Schema}s created by this factory, and by extension,
* {@link Validator}s and {@link ValidatorHandler}s created by
* those {@link Schema}s.
* </p>
*
* <p>Implementors and developers should pay particular attention
* to how the special {@link Schema} object returned by {@link
* #newSchema()} is processed. In some cases, for example, when the
* <code>SchemaFactory</code> and the class actually loading the
* schema come from different implementations, it may not be possible
* for <code>SchemaFactory</code> features to be inherited automatically.
* Developers should
* make sure that features, such as secure processing, are explicitly
* set in both places.</p>
*
* <p>The feature name is any fully-qualified URI. It is
* possible for a {@link SchemaFactory} to expose a feature value but
* to be unable to change the current value.</p>
*
* <p>All implementations are required to support the {@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} feature.
* When the feature is:</p>
* <ul>
* <li>
* <code>true</code>: the implementation will limit XML processing to conform to implementation limits.
* Examples include enity expansion limits and XML Schema constructs that would consume large amounts of resources.
* If XML processing is limited for security reasons, it will be reported via a call to the registered
* {@link ErrorHandler#fatalError(SAXParseException exception)}.
* See {@link #setErrorHandler(ErrorHandler errorHandler)}.
* </li>
* <li>
* <code>false</code>: the implementation will processing XML according to the XML specifications without
* regard to possible implementation limits.
* </li>
* </ul>
*
* @param name The feature name, which is a non-null fully-qualified URI.
* @param value The requested value of the feature (true or false).
*
* @throws SAXNotRecognizedException If the feature
* value can't be assigned or retrieved.
* @throws SAXNotSupportedException When the
* {@link SchemaFactory} recognizes the feature name but
* cannot set the requested value.
* @throws NullPointerException If <code>name</code> is <code>null</code>.
*
* @see #getFeature(String)
*/
public void setFeature(String name, boolean value)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException("the name parameter is null");
}
throw new SAXNotRecognizedException(name);
}
/**
* Set the value of a property.
*
* <p>The property name is any fully-qualified URI. It is
* possible for a {@link SchemaFactory} to recognize a property name but
* to be unable to change the current value.</p>
*
* <p>{@link SchemaFactory}s are not required to recognize setting
* any specific property names.</p>
*
* @param name The property name, which is a non-null fully-qualified URI.
* @param object The requested value for the property.
*
* @throws SAXNotRecognizedException If the property
* value can't be assigned or retrieved.
* @throws SAXNotSupportedException When the
* {@link SchemaFactory} recognizes the property name but
* cannot set the requested value.
* @throws NullPointerException If <code>name</code> is <code>null</code>.
*/
public void setProperty(String name, Object object)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException("the name parameter is null");
}
throw new SAXNotRecognizedException(name);
}
/**
* Look up the value of a property.
*
* <p>The property name is any fully-qualified URI. It is
* possible for a {@link SchemaFactory} to recognize a property name but
* temporarily be unable to return its value.</p>
*
* <p>{@link SchemaFactory}s are not required to recognize any specific
* property names.</p>
*
* <p>Implementors are free (and encouraged) to invent their own properties,
* using names built on their own URIs.</p>
*
* @param name The property name, which is a non-null fully-qualified URI.
*
* @return The current value of the property.
*
* @throws SAXNotRecognizedException If the property
* value can't be assigned or retrieved.
* @throws SAXNotSupportedException When the
* XMLReader recognizes the property name but
* cannot determine its value at this time.
* @throws NullPointerException If <code>name</code> is <code>null</code>.
*
* @see #setProperty(String, Object)
*/
public Object getProperty(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException("the name parameter is null");
}
throw new SAXNotRecognizedException(name);
}
/**
* Sets the {@link ErrorHandler} to receive errors encountered
* during the <code>newSchema</code> method invocation.
*
* <p>
* Error handler can be used to customize the error handling process
* during schema parsing. When an {@link ErrorHandler} is set,
* errors found during the parsing of schemas will be first sent
* to the {@link ErrorHandler}.
*
* <p>
* The error handler can abort the parsing of a schema immediately
* by throwing {@link SAXException} from the handler. Or for example
* it can print an error to the screen and try to continue the
* processing by returning normally from the {@link ErrorHandler}
*
* <p>
* If any {@link Throwable} (or instances of its derived classes)
* is thrown from an {@link ErrorHandler},
* the caller of the <code>newSchema</code> method will be thrown
* the same {@link Throwable} object.
*
* <p>
* {@link SchemaFactory} is not allowed to
* throw {@link SAXException} without first reporting it to
* {@link ErrorHandler}.
*
* <p>
* Applications can call this method even during a {@link Schema}
* is being parsed.
*
* <p>
* When the {@link ErrorHandler} is null, the implementation will
* behave as if the following {@link ErrorHandler} is set:
* <pre>
* class DraconianErrorHandler implements {@link ErrorHandler} {
* public void fatalError( {@link org.xml.sax.SAXParseException} e ) throws {@link SAXException} {
* throw e;
* }
* public void error( {@link org.xml.sax.SAXParseException} e ) throws {@link SAXException} {
* throw e;
* }
* public void warning( {@link org.xml.sax.SAXParseException} e ) throws {@link SAXException} {
* // noop
* }
* }
* </pre>
*
* <p>
* When a new {@link SchemaFactory} object is created, initially
* this field is set to null. This field will <em>NOT</em> be
* inherited to {@link Schema}s, {@link Validator}s, or
* {@link ValidatorHandler}s that are created from this {@link SchemaFactory}.
*
* @param errorHandler A new error handler to be set.
* This parameter can be <code>null</code>.
*/
public abstract void setErrorHandler(ErrorHandler errorHandler);
/**
* Gets the current {@link ErrorHandler} set to this {@link SchemaFactory}.
*
* @return
* This method returns the object that was last set through
* the {@link #setErrorHandler(ErrorHandler)} method, or null
* if that method has never been called since this {@link SchemaFactory}
* has created.
*
* @see #setErrorHandler(ErrorHandler)
*/
public abstract ErrorHandler getErrorHandler();
/**
* Sets the {@link LSResourceResolver} to customize
* resource resolution when parsing schemas.
*
* <p>
* {@link SchemaFactory} uses a {@link LSResourceResolver}
* when it needs to locate external resources while parsing schemas,
* although exactly what constitutes "locating external resources" is
* up to each schema language. For example, for W3C XML Schema,
* this includes files <code>&lt;include></code>d or <code>&lt;import></code>ed,
* and DTD referenced from schema files, etc.
*
* <p>
* Applications can call this method even during a {@link Schema}
* is being parsed.
*
* <p>
* When the {@link LSResourceResolver} is null, the implementation will
* behave as if the following {@link LSResourceResolver} is set:
* <pre>
* class DumbDOMResourceResolver implements {@link LSResourceResolver} {
* public {@link org.w3c.dom.ls.LSInput} resolveResource(
* String publicId, String systemId, String baseURI) {
*
* return null; // always return null
* }
* }
* </pre>
*
* <p>
* If a {@link LSResourceResolver} throws a {@link RuntimeException}
* (or instances of its derived classes),
* then the {@link SchemaFactory} will abort the parsing and
* the caller of the <code>newSchema</code> method will receive
* the same {@link RuntimeException}.
*
* <p>
* When a new {@link SchemaFactory} object is created, initially
* this field is set to null. This field will <em>NOT</em> be
* inherited to {@link Schema}s, {@link Validator}s, or
* {@link ValidatorHandler}s that are created from this {@link SchemaFactory}.
*
* @param resourceResolver
* A new resource resolver to be set. This parameter can be null.
*/
public abstract void setResourceResolver(LSResourceResolver resourceResolver);
/**
* Gets the current {@link LSResourceResolver} set to this {@link SchemaFactory}.
*
* @return
* This method returns the object that was last set through
* the {@link #setResourceResolver(LSResourceResolver)} method, or null
* if that method has never been called since this {@link SchemaFactory}
* has created.
*
* @see #setErrorHandler(ErrorHandler)
*/
public abstract LSResourceResolver getResourceResolver();
/**
* <p>Parses the specified source as a schema and returns it as a schema.</p>
*
* <p>This is a convenience method for {@link #newSchema(Source[] schemas)}.</p>
*
* @param schema Source that represents a schema.
*
* @return New <code>Schema</code> from parsing <code>schema</code>.
*
* @throws SAXException If a SAX error occurs during parsing.
* @throws NullPointerException if <code>schema</code> is null.
*/
public Schema newSchema(Source schema) throws SAXException {
return newSchema(new Source[]{schema});
}
/**
* <p>Parses the specified <code>File</code> as a schema and returns it as a <code>Schema</code>.</p>
*
* <p>This is a convenience method for {@link #newSchema(Source schema)}.</p>
*
* @param schema File that represents a schema.
*
* @return New <code>Schema</code> from parsing <code>schema</code>.
*
* @throws SAXException If a SAX error occurs during parsing.
* @throws NullPointerException if <code>schema</code> is null.
*/
public Schema newSchema(File schema) throws SAXException {
return newSchema(new StreamSource(schema));
}
/**
* <p>Parses the specified <code>URL</code> as a schema and returns it as a <code>Schema</code>.</p>
*
* <p>This is a convenience method for {@link #newSchema(Source schema)}.</p>
*
* @param schema <code>URL</code> that represents a schema.
*
* @return New <code>Schema</code> from parsing <code>schema</code>.
*
* @throws SAXException If a SAX error occurs during parsing.
* @throws NullPointerException if <code>schema</code> is null.
*/
public Schema newSchema(URL schema) throws SAXException {
return newSchema(new StreamSource(schema.toExternalForm()));
}
/**
* Parses the specified source(s) as a schema and returns it as a schema.
*
* <p>
* The callee will read all the {@link Source}s and combine them into a
* single schema. The exact semantics of the combination depends on the schema
* language that this {@link SchemaFactory} object is created for.
*
* <p>
* When an {@link ErrorHandler} is set, the callee will report all the errors
* found in sources to the handler. If the handler throws an exception, it will
* abort the schema compilation and the same exception will be thrown from
* this method. Also, after an error is reported to a handler, the callee is allowed
* to abort the further processing by throwing it. If an error handler is not set,
* the callee will throw the first error it finds in the sources.
*
* <h2>W3C XML Schema 1.0</h2>
* <p>
* The resulting schema contains components from the specified sources.
* The same result would be achieved if all these sources were
* imported, using appropriate values for schemaLocation and namespace,
* into a single schema document with a different targetNamespace
* and no components of its own, if the import elements were given
* in the same order as the sources. Section 4.2.3 of the XML Schema
* recommendation describes the options processors have in this
* regard. While a processor should be consistent in its treatment of
* JAXP schema sources and XML Schema imports, the behaviour between
* JAXP-compliant parsers may vary; in particular, parsers may choose
* to ignore all but the first &lt;import> for a given namespace,
* regardless of information provided in schemaLocation.
*
* <p>
* If the parsed set of schemas includes error(s) as
* specified in the section 5.1 of the XML Schema spec, then
* the error must be reported to the {@link ErrorHandler}.
*
* <h2>RELAX NG</h2>
*
* <p>For RELAX NG, this method must throw {@link UnsupportedOperationException}
* if <code>schemas.length!=1</code>.
*
*
* @param schemas
* inputs to be parsed. {@link SchemaFactory} is required
* to recognize {@link javax.xml.transform.sax.SAXSource},
* {@link StreamSource},
* {@link javax.xml.transform.stax.StAXSource},
* and {@link javax.xml.transform.dom.DOMSource}.
* Input schemas must be XML documents or
* XML elements and must not be null. For backwards compatibility,
* the results of passing anything other than
* a document or element are implementation-dependent.
* Implementations must either recognize and process the input
* or thrown an IllegalArgumentException.
*
* @return
* Always return a non-null valid {@link Schema} object.
* Note that when an error has been reported, there is no
* guarantee that the returned {@link Schema} object is
* meaningful.
*
* @throws SAXException
* If an error is found during processing the specified inputs.
* When an {@link ErrorHandler} is set, errors are reported to
* there first. See {@link #setErrorHandler(ErrorHandler)}.
* @throws NullPointerException
* If the <code>schemas</code> parameter itself is null or
* any item in the array is null.
* @throws IllegalArgumentException
* If any item in the array is not recognized by this method.
* @throws UnsupportedOperationException
* If the schema language doesn't support this operation.
*/
public abstract Schema newSchema(Source[] schemas) throws SAXException;
/**
* Creates a special {@link Schema} object.
*
* <p>The exact semantics of the returned {@link Schema} object
* depend on the schema language for which this {@link SchemaFactory}
* is created.
*
* <p>Also, implementations are allowed to use implementation-specific
* property/feature to alter the semantics of this method.</p>
*
* <p>Implementors and developers should pay particular attention
* to how the features set on this {@link SchemaFactory} are
* processed by this special {@link Schema}.
* In some cases, for example, when the
* {@link SchemaFactory} and the class actually loading the
* schema come from different implementations, it may not be possible
* for {@link SchemaFactory} features to be inherited automatically.
* Developers should
* make sure that features, such as secure processing, are explicitly
* set in both places.</p>
*
* <h2>W3C XML Schema 1.0</h2>
* <p>
* For XML Schema, this method creates a {@link Schema} object that
* performs validation by using location hints specified in documents.
*
* <p>
* The returned {@link Schema} object assumes that if documents
* refer to the same URL in the schema location hints,
* they will always resolve to the same schema document. This
* asusmption allows implementations to reuse parsed results of
* schema documents so that multiple validations against the same
* schema will run faster.
*
* <p>
* Note that the use of schema location hints introduces a
* vulnerability to denial-of-service attacks.
*
*
* <h2>RELAX NG</h2>
* <p>
* RELAX NG does not support this operation.
*
* @return
* Always return non-null valid {@link Schema} object.
*
* @throws UnsupportedOperationException
* If this operation is not supported by the callee.
* @throws SAXException
* If this operation is supported but failed for some reason.
*/
public abstract Schema newSchema() throws SAXException;
}

View file

@ -0,0 +1,538 @@
/*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.validation;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Properties;
/**
* Implementation of {@link SchemaFactory#newInstance(String)}.
*
* @author <a href="Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
* @since 1.5
*/
class SchemaFactoryFinder {
/** debug support code. */
private static boolean debug = false;
/**
*<p> Take care of restrictions imposed by java security model </p>
*/
private static SecuritySupport ss = new SecuritySupport();
/**
* <p>Cache properties for performance.</p>
*/
private static Properties cacheProps = new Properties();
/**
* <p>First time requires initialization overhead.</p>
*/
private static boolean firstTime = true;
static {
// Use try/catch block to support applets
try {
debug = ss.getSystemProperty("jaxp.debug") != null;
} catch (Exception _) {
debug = false;
}
}
/**
* <p>Conditional debug printing.</p>
*
* @param msg to print
*/
private static void debugPrintln(String msg) {
if (debug) {
System.err.println("JAXP: " + msg);
}
}
/**
* <p><code>ClassLoader</code> to use to find <code>SchemaFactory</code>.</p>
*/
private final ClassLoader classLoader;
/**
* <p>Constructor that specifies <code>ClassLoader</code> to use
* to find <code>SchemaFactory</code>.</p>
*
* @param loader
* to be used to load resource, {@link SchemaFactory}, and
* {@link SchemaFactoryLoader} implementations during
* the resolution process.
* If this parameter is null, the default system class loader
* will be used.
*/
public SchemaFactoryFinder(ClassLoader loader) {
this.classLoader = loader;
if( debug ) {
debugDisplayClassLoader();
}
}
private void debugDisplayClassLoader() {
try {
if( classLoader == ss.getContextClassLoader() ) {
debugPrintln("using thread context class loader ("+classLoader+") for search");
return;
}
} catch( Throwable _ ) {
; // getContextClassLoader() undefined in JDK1.1
}
if( classLoader==ClassLoader.getSystemClassLoader() ) {
debugPrintln("using system class loader ("+classLoader+") for search");
return;
}
debugPrintln("using class loader ("+classLoader+") for search");
}
/**
* <p>Creates a new {@link SchemaFactory} object for the specified
* schema language.</p>
*
* @param schemaLanguage
* See {@link SchemaFactory Schema Language} table in <code>SchemaFactory</code>
* for the list of available schema languages.
*
* @return <code>null</code> if the callee fails to create one.
*
* @throws NullPointerException
* If the <code>schemaLanguage</code> parameter is null.
*/
public SchemaFactory newFactory(String schemaLanguage) {
if(schemaLanguage==null) throw new NullPointerException();
SchemaFactory f = _newFactory(schemaLanguage);
if (f != null) {
debugPrintln("factory '" + f.getClass().getName() + "' was found for " + schemaLanguage);
} else {
debugPrintln("unable to find a factory for " + schemaLanguage);
}
return f;
}
/**
* <p>Lookup a <code>SchemaFactory</code> for the given <code>schemaLanguage</code>.</p>
*
* @param schemaLanguage Schema language to lookup <code>SchemaFactory</code> for.
*
* @return <code>SchemaFactory</code> for the given <code>schemaLanguage</code>.
*/
private SchemaFactory _newFactory(String schemaLanguage) {
SchemaFactory sf;
String propertyName = SERVICE_CLASS.getName() + ":" + schemaLanguage;
// system property look up
try {
debugPrintln("Looking up system property '"+propertyName+"'" );
String r = ss.getSystemProperty(propertyName);
if(r!=null) {
debugPrintln("The value is '"+r+"'");
sf = createInstance(r);
if(sf!=null) return sf;
} else
debugPrintln("The property is undefined.");
} catch( Throwable t ) {
if( debug ) {
debugPrintln("failed to look up system property '"+propertyName+"'" );
t.printStackTrace();
}
}
String javah = ss.getSystemProperty( "java.home" );
String configFile = javah + File.separator +
"lib" + File.separator + "jaxp.properties";
String factoryClassName = null ;
// try to read from $java.home/lib/jaxp.properties
try {
if(firstTime){
synchronized(cacheProps){
if(firstTime){
File f=new File( configFile );
firstTime = false;
if(ss.doesFileExist(f)){
debugPrintln("Read properties file " + f);
cacheProps.load(ss.getFileInputStream(f));
}
}
}
}
factoryClassName = cacheProps.getProperty(propertyName);
debugPrintln("found " + factoryClassName + " in $java.home/jaxp.properties");
if (factoryClassName != null) {
sf = createInstance(factoryClassName);
if(sf != null){
return sf;
}
}
} catch (Exception ex) {
if (debug) {
ex.printStackTrace();
}
}
/**
// try to read from $java.home/lib/jaxp.properties
try {
String javah = ss.getSystemProperty( "java.home" );
String configFile = javah + File.separator +
"lib" + File.separator + "jaxp.properties";
File f = new File( configFile );
if( ss.doesFileExist(f)) {
sf = loadFromProperty(
propertyName,f.getAbsolutePath(), new FileInputStream(f));
if(sf!=null) return sf;
} else {
debugPrintln("Tried to read "+ f.getAbsolutePath()+", but it doesn't exist.");
}
} catch(Throwable e) {
if( debug ) {
debugPrintln("failed to read $java.home/lib/jaxp.properties");
e.printStackTrace();
}
}
*/
// try META-INF/services files
Iterator sitr = createServiceFileIterator();
while(sitr.hasNext()) {
URL resource = (URL)sitr.next();
debugPrintln("looking into " + resource);
try {
sf = loadFromService(schemaLanguage,resource.toExternalForm(),
ss.getURLInputStream(resource));
if(sf!=null) return sf;
} catch(IOException e) {
if( debug ) {
debugPrintln("failed to read "+resource);
e.printStackTrace();
}
}
}
// platform default
if(schemaLanguage.equals("http://www.w3.org/2001/XMLSchema")) {
debugPrintln("attempting to use the platform default XML Schema validator");
return createInstance("com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory");
}
debugPrintln("all things were tried, but none was found. bailing out.");
return null;
}
/** <p>Create class using appropriate ClassLoader.</p>
*
* @param className Name of class to create.
* @return Created class or <code>null</code>.
*/
private Class createClass(String className) {
Class clazz;
// use approprite ClassLoader
try {
if (classLoader != null) {
clazz = classLoader.loadClass(className);
} else {
clazz = Class.forName(className);
}
} catch (Throwable t) {
if(debug) t.printStackTrace();
return null;
}
return clazz;
}
/**
* <p>Creates an instance of the specified and returns it.</p>
*
* @param className
* fully qualified class name to be instanciated.
*
* @return null
* if it fails. Error messages will be printed by this method.
*/
SchemaFactory createInstance( String className ) {
SchemaFactory schemaFactory = null;
debugPrintln("createInstance(" + className + ")");
// get Class from className
Class clazz = createClass(className);
if (clazz == null) {
debugPrintln("failed to getClass(" + className + ")");
return null;
}
debugPrintln("loaded " + className + " from " + which(clazz));
// instantiate Class as a SchemaFactory
try {
schemaFactory = (SchemaFactory) clazz.newInstance();
} catch (ClassCastException classCastException) {
debugPrintln("could not instantiate " + clazz.getName());
if (debug) {
classCastException.printStackTrace();
}
return null;
} catch (IllegalAccessException illegalAccessException) {
debugPrintln("could not instantiate " + clazz.getName());
if (debug) {
illegalAccessException.printStackTrace();
}
return null;
} catch (InstantiationException instantiationException) {
debugPrintln("could not instantiate " + clazz.getName());
if (debug) {
instantiationException.printStackTrace();
}
return null;
}
return schemaFactory;
}
/** Iterator that lazily computes one value and returns it. */
private static abstract class SingleIterator implements Iterator {
private boolean seen = false;
public final void remove() { throw new UnsupportedOperationException(); }
public final boolean hasNext() { return !seen; }
public final Object next() {
if(seen) throw new NoSuchElementException();
seen = true;
return value();
}
protected abstract Object value();
}
/**
* Looks up a value in a property file
* while producing all sorts of debug messages.
*
* @return null
* if there was an error.
*/
private SchemaFactory loadFromProperty( String keyName, String resourceName, InputStream in )
throws IOException {
debugPrintln("Reading "+resourceName );
Properties props=new Properties();
props.load(in);
in.close();
String factoryClassName = props.getProperty(keyName);
if(factoryClassName != null){
debugPrintln("found "+keyName+" = " + factoryClassName);
return createInstance(factoryClassName);
} else {
debugPrintln(keyName+" is not in the property file");
return null;
}
}
/**
* <p>Look up a value in a property file.</p>
*
* <p>Set <code>debug</code> to <code>true</code> to trace property evaluation.</p>
*
* @param schemaLanguage Schema Language to support.
* @param inputName Name of <code>InputStream</code>.
* @param in <code>InputStream</code> of properties.
*
* @return <code>SchemaFactory</code> as determined by <code>keyName</code> value or <code>null</code> if there was an error.
*
* @throws IOException If IO error reading from <code>in</code>.
*/
private SchemaFactory loadFromService(
String schemaLanguage,
String inputName,
InputStream in)
throws IOException {
SchemaFactory schemaFactory = null;
final Class[] stringClassArray = {"".getClass()};
final Object[] schemaLanguageObjectArray = {schemaLanguage};
final String isSchemaLanguageSupportedMethod = "isSchemaLanguageSupported";
debugPrintln("Reading " + inputName);
// read from InputStream until a match is found
BufferedReader configFile = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = configFile.readLine()) != null) {
// '#' is comment char
int comment = line.indexOf("#");
switch (comment) {
case -1: break; // no comment
case 0: line = ""; break; // entire line is a comment
default: line = line.substring(0, comment); break; // trim comment
}
// trim whitespace
line = line.trim();
// any content left on line?
if (line.length() == 0) {
continue;
}
// line content is now the name of the class
Class clazz = createClass(line);
if (clazz == null) {
continue;
}
// create an instance of the Class
try {
schemaFactory = (SchemaFactory) clazz.newInstance();
} catch (ClassCastException classCastExcpetion) {
schemaFactory = null;
continue;
} catch (InstantiationException instantiationException) {
schemaFactory = null;
continue;
} catch (IllegalAccessException illegalAccessException) {
schemaFactory = null;
continue;
}
// does this Class support desired Schema?
try {
Method isSchemaLanguageSupported = clazz.getMethod(isSchemaLanguageSupportedMethod, stringClassArray);
Boolean supported = (Boolean) isSchemaLanguageSupported.invoke(schemaFactory, schemaLanguageObjectArray);
if (supported.booleanValue()) {
break;
}
} catch (NoSuchMethodException noSuchMethodException) {
} catch (IllegalAccessException illegalAccessException) {
} catch (InvocationTargetException invocationTargetException) {
}
schemaFactory = null;
}
// clean up
configFile.close();
// return new instance of SchemaFactory or null
return schemaFactory;
}
/**
* Returns an {@link Iterator} that enumerates all
* the META-INF/services files that we care.
*/
private Iterator createServiceFileIterator() {
if (classLoader == null) {
return new SingleIterator() {
protected Object value() {
ClassLoader classLoader = SchemaFactoryFinder.class.getClassLoader();
//return (ClassLoader.getSystemResource( SERVICE_ID ));
return ss.getResourceAsURL(classLoader, SERVICE_ID);
}
};
} else {
try {
//final Enumeration e = classLoader.getResources(SERVICE_ID);
final Enumeration e = ss.getResources(classLoader, SERVICE_ID);
if(!e.hasMoreElements()) {
debugPrintln("no "+SERVICE_ID+" file was found");
}
// wrap it into an Iterator.
return new Iterator() {
public void remove() {
throw new UnsupportedOperationException();
}
public boolean hasNext() {
return e.hasMoreElements();
}
public Object next() {
return e.nextElement();
}
};
} catch (IOException e) {
debugPrintln("failed to enumerate resources "+SERVICE_ID);
if(debug) e.printStackTrace();
return new ArrayList().iterator(); // empty iterator
}
}
}
private static final Class SERVICE_CLASS = SchemaFactory.class;
private static final String SERVICE_ID = "META-INF/services/" + SERVICE_CLASS.getName();
private static String which( Class clazz ) {
return which( clazz.getName(), clazz.getClassLoader() );
}
/**
* <p>Search the specified classloader for the given classname.</p>
*
* @param classname the fully qualified name of the class to search for
* @param loader the classloader to search
*
* @return the source location of the resource, or null if it wasn't found
*/
private static String which(String classname, ClassLoader loader) {
String classnameAsResource = classname.replace('.', '/') + ".class";
if( loader==null ) loader = ClassLoader.getSystemClassLoader();
//URL it = loader.getResource(classnameAsResource);
URL it = ss.getResourceAsURL(loader, classnameAsResource);
if (it != null) {
return it.toString();
} else {
return null;
}
}
}

View file

@ -0,0 +1,68 @@
/*
* Copyright 2004-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.validation;
/**
* <p>Factory that creates {@link SchemaFactory}.</p>
*
* <p><b>DO NOT USE THIS CLASS</b></p>
*
* <p>
* This class was introduced as a part of an early proposal during the
* JSR-206 standardization process. The proposal was eventually abandoned
* but this class accidentally remained in the source tree, and made its
* way into the final version.
* </p><p>
* This class does not participate in any JAXP 1.3 or JAXP 1.4 processing.
* It must not be used by users or JAXP implementations.
* </p>
*
* @author <a href="Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
* @since 1.5
*/
public abstract class SchemaFactoryLoader {
/**
* A do-nothing constructor.
*/
protected SchemaFactoryLoader() {
}
/**
* Creates a new {@link SchemaFactory} object for the specified
* schema language.
*
* @param schemaLanguage
* See <a href="SchemaFactory.html#schemaLanguage">
* the list of available schema languages</a>.
*
* @throws NullPointerException
* If the <tt>schemaLanguage</tt> parameter is null.
*
* @return <code>null</code> if the callee fails to create one.
*/
public abstract SchemaFactory newFactory(String schemaLanguage);
}

View file

@ -0,0 +1,163 @@
/*
* Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.validation;
import java.io.IOException;
import java.net.URL;
import java.security.*;
import java.net.*;
import java.io.*;
import java.util.*;
/**
* 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 SecuritySupport {
ClassLoader getContextClassLoader() {
return (ClassLoader)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ClassLoader cl = null;
//try {
cl = Thread.currentThread().getContextClassLoader();
//} catch (SecurityException ex) { }
if (cl == null)
cl = ClassLoader.getSystemClassLoader();
return cl;
}
});
}
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 getURLInputStream(final URL url)
throws IOException
{
try {
return (InputStream)
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IOException {
return url.openStream();
}
});
} catch (PrivilegedActionException e) {
throw (IOException)e.getException();
}
}
URL getResourceAsURL(final ClassLoader cl,
final String name)
{
return (URL)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
URL url;
if (cl == null) {
url = ClassLoader.getSystemResource(name);
} else {
url = cl.getResource(name);
}
return url;
}
});
}
Enumeration getResources(final ClassLoader cl,
final String name) throws IOException
{
try{
return (Enumeration)
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IOException{
Enumeration enumeration;
if (cl == null) {
enumeration = ClassLoader.getSystemResources(name);
} else {
enumeration = cl.getResources(name);
}
return enumeration;
}
});
}catch(PrivilegedActionException e){
throw (IOException)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 doesFileExist(final File f) {
return ((Boolean)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return new Boolean(f.exists());
}
})).booleanValue();
}
}

View file

@ -0,0 +1,197 @@
/*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.validation;
import org.w3c.dom.TypeInfo;
/**
* This class provides access to the type information determined
* by {@link ValidatorHandler}.
*
* <p>
* Some schema languages, such as W3C XML Schema, encourages a validator
* to report the "type" it assigns to each attribute/element.
* Those applications who wish to access this type information can invoke
* methods defined on this "interface" to access such type information.
*
* <p>
* Implementation of this "interface" can be obtained through the
* {@link ValidatorHandler#getTypeInfoProvider()} method.
*
* @author <a href="mailto:Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
* @see org.w3c.dom.TypeInfo
* @since 1.5
*/
public abstract class TypeInfoProvider {
/**
* Constructor for the derived class.
*
* <p>
* The constructor does nothing.
*/
protected TypeInfoProvider() {
}
/**
* <p>Returns the immutable {@link TypeInfo} object for the current
* element.</p>
*
* <p>The method may only be called by the startElement event
* or the endElement event
* of the {@link org.xml.sax.ContentHandler} that the application sets to
* the {@link ValidatorHandler}.</p>
*
* <p>When W3C XML Schema validation is being performed, in the
* case where an element has a union type, the {@link TypeInfo}
* returned by a call to <code>getElementTypeInfo()</code> from the
* startElement
* event will be the union type. The <code>TypeInfo</code>
* returned by a call
* from the endElement event will be the actual member type used
* to validate the element.</p>
*
* @throws IllegalStateException
* If this method is called from other {@link org.xml.sax.ContentHandler}
* methods.
* @return
* An immutable {@link TypeInfo} object that represents the
* type of the current element.
* Note that the caller can keep references to the obtained
* {@link TypeInfo} longer than the callback scope.
*
* Otherwise, this method returns
* null if the validator is unable to
* determine the type of the current element for some reason
* (for example, if the validator is recovering from
* an earlier error.)
*
*/
public abstract TypeInfo getElementTypeInfo();
/**
* Returns the immutable {@link TypeInfo} object for the specified
* attribute of the current element.
*
* <p>
* The method may only be called by the startElement event of
* the {@link org.xml.sax.ContentHandler} that the application sets to the
* {@link ValidatorHandler}.</p>
*
* @param index
* The index of the attribute. The same index for
* the {@link org.xml.sax.Attributes} object passed to the
* <code>startElement</code> callback.
*
* @throws IndexOutOfBoundsException
* If the index is invalid.
* @throws IllegalStateException
* If this method is called from other {@link org.xml.sax.ContentHandler}
* methods.
*
* @return
* An immutable {@link TypeInfo} object that represents the
* type of the specified attribute.
* Note that the caller can keep references to the obtained
* {@link TypeInfo} longer than the callback scope.
*
* Otherwise, this method returns
* null if the validator is unable to
* determine the type.
*/
public abstract TypeInfo getAttributeTypeInfo(int index);
/**
* Returns <code>true</code> if the specified attribute is determined
* to be ID.
*
* <p>
* Exacly how an attribute is "determined to be ID" is up to the
* schema language. In case of W3C XML Schema, this means
* that the actual type of the attribute is the built-in ID type
* or its derived type.
*
* <p>
* A {@link javax.xml.parsers.DocumentBuilder} uses this information
* to properly implement {@link org.w3c.dom.Attr#isId()}.
*
* <p>
* The method may only be called by the startElement event of
* the {@link org.xml.sax.ContentHandler} that the application sets to the
* {@link ValidatorHandler}.
*
* @param index
* The index of the attribute. The same index for
* the {@link org.xml.sax.Attributes} object passed to the
* <code>startElement</code> callback.
*
* @throws IndexOutOfBoundsException
* If the index is invalid.
* @throws IllegalStateException
* If this method is called from other {@link org.xml.sax.ContentHandler}
* methods.
*
* @return true
* if the type of the specified attribute is ID.
*/
public abstract boolean isIdAttribute(int index);
/**
* Returns <code>false</code> if the attribute was added by the validator.
*
* <p>
* This method provides information necessary for
* a {@link javax.xml.parsers.DocumentBuilder} to determine what
* the DOM tree should return from the {@link org.w3c.dom.Attr#getSpecified()} method.
*
* <p>
* The method may only be called by the startElement event of
* the {@link org.xml.sax.ContentHandler} that the application sets to the
* {@link ValidatorHandler}.
*
* <p>
* A general guideline for validators is to return true if
* the attribute was originally present in the pipeline, and
* false if it was added by the validator.
*
* @param index
* The index of the attribute. The same index for
* the {@link org.xml.sax.Attributes} object passed to the
* <code>startElement</code> callback.
*
* @throws IndexOutOfBoundsException
* If the index is invalid.
* @throws IllegalStateException
* If this method is called from other {@link org.xml.sax.ContentHandler}
* methods.
*
* @return
* <code>true</code> if the attribute was present before the validator
* processes input. <code>false</code> if the attribute was added
* by the validator.
*/
public abstract boolean isSpecified(int index);
}

View file

@ -0,0 +1,505 @@
/*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.validation;
import java.io.IOException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
/**
* <p>A processor that checks an XML document against {@link Schema}.</p>
*
* <p>
* A validator object is not thread-safe and not reentrant.
* In other words, it is the application's responsibility to make
* sure that one {@link Validator} object is not used from
* more than one thread at any given time, and while the <code>validate</code>
* method is invoked, applications may not recursively call
* the <code>validate</code> method.
* <p>
*
*
* @author <a href="mailto:Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
* @since 1.5
*/
public abstract class Validator {
/**
* Constructor for derived classes.
*
* <p>The constructor does nothing.</p>
*
* <p>Derived classes must create {@link Validator} objects that have
* <code>null</code> {@link ErrorHandler} and
* <code>null</code> {@link LSResourceResolver}.
* </p>
*/
protected Validator() {
}
/**
* <p>Reset this <code>Validator</code> to its original configuration.</p>
*
* <p><code>Validator</code> is reset to the same state as when it was created with
* {@link Schema#newValidator()}.
* <code>reset()</code> is designed to allow the reuse of existing <code>Validator</code>s
* thus saving resources associated with the creation of new <code>Validator</code>s.</p>
*
* <p>The reset <code>Validator</code> is not guaranteed to have the same {@link LSResourceResolver} or {@link ErrorHandler}
* <code>Object</code>s, e.g. {@link Object#equals(Object obj)}. It is guaranteed to have a functionally equal
* <code>LSResourceResolver</code> and <code>ErrorHandler</code>.</p>
*/
public abstract void reset();
/**
* Validates the specified input.
*
* <p>This is just a convenience method for
* {@link #validate(Source source, Result result)}
* with <code>result</code> of <code>null</code>.</p>
*
* @param source
* XML to be validated. Must be an XML document or
* XML element and must not be null. For backwards compatibility,
* the results of attempting to validate anything other than
* a document or element are implementation-dependent.
* Implementations must either recognize and process the input
* or throw an IllegalArgumentException.
*
* @throws IllegalArgumentException
* If the <code>Source</code>
* is an XML artifact that the implementation cannot
* validate (for example, a processing instruction).
*
* @throws SAXException
* If the {@link ErrorHandler} throws a {@link SAXException} or
* if a fatal error is found and the {@link ErrorHandler} returns
* normally.
*
* @throws IOException
* If the validator is processing a
* {@link javax.xml.transform.sax.SAXSource} and the
* underlying {@link org.xml.sax.XMLReader} throws an
* {@link IOException}.
*
*
* @throws NullPointerException If <code>source</code> is
* <code>null</code>.
*
* @see #validate(Source source, Result result)
*/
public void validate(Source source)
throws SAXException, IOException {
validate(source, null);
}
/**
* <p>Validates the specified input and send the augmented validation
* result to the specified output.</p>
*
* <p>This method places the following restrictions on the types of
* the {@link Source}/{@link Result} accepted.</p>
*
* <table border=1>
* <thead>
* <tr>
* <th colspan="5"><code>Source</code> / <code>Result</code> Accepted</th>
* </tr>
* <tr>
* <th></th>
* <th>{@link javax.xml.transform.stream.StreamSource}</th>
* <th>{@link javax.xml.transform.sax.SAXSource}</th>
* <th>{@link javax.xml.transform.dom.DOMSource}</th>
* <th>{@link javax.xml.transform.stax.StAXSource}</th>
* </tr>
* </thead>
* <tbody align="center">
* <tr>
* <td><code>null</code></td>
* <td>OK</td>
* <td>OK</td>
* <td>OK</td>
* <td>OK</td>
* </tr>
* <tr>
* <th>{@link javax.xml.transform.stream.StreamResult}</th>
* <td>OK</td>
* <td><code>IllegalArgumentException</code></td>
* <td><code>IllegalArgumentException</code></td>
* <td><code>IllegalArgumentException</code></td>
* </tr>
* <tr>
* <th>{@link javax.xml.transform.sax.SAXResult}</th>
* <td><code>IllegalArgumentException</code></td>
* <td>OK</td>
* <td><code>IllegalArgumentException</code></td>
* <td><code>IllegalArgumentException</code></td>
* </tr>
* <tr>
* <th>{@link javax.xml.transform.dom.DOMResult}</th>
* <td><code>IllegalArgumentException</code></td>
* <td><code>IllegalArgumentException</code></td>
* <td>OK</td>
* <td><code>IllegalArgumentException</code></td>
* </tr>
* <tr>
* <th>{@link javax.xml.transform.stax.StAXResult}</th>
* <td><code>IllegalArgumentException</code></td>
* <td><code>IllegalArgumentException</code></td>
* <td><code>IllegalArgumentException</code></td>
* <td>OK</td>
* </tr>
* </tbody>
* </table>
*
* <p>To validate one <code>Source</code> into another kind of
* <code>Result</code>, use the identity transformer (see
* {@link javax.xml.transform.TransformerFactory#newTransformer()}).</p>
*
* <p>Errors found during the validation is sent to the specified
* {@link ErrorHandler}.</p>
*
* <p>If a document is valid, or if a document contains some errors
* but none of them were fatal and the <code>ErrorHandler</code> didn't
* throw any exception, then the method returns normally.</p>
*
* @param source
* XML to be validated. Must be an XML document or
* XML element and must not be null. For backwards compatibility,
* the results of attempting to validate anything other than
* a document or element are implementation-dependent.
* Implementations must either recognize and process the input
* or throw an IllegalArgumentException.
*
* @param result
* The <code>Result</code> object that receives (possibly augmented)
* XML. This parameter can be null if the caller is not interested
* in it.
*
* Note that when a <code>DOMResult</code> is used,
* a validator might just pass the same DOM node from
* <code>DOMSource</code> to <code>DOMResult</code>
* (in which case <code>source.getNode()==result.getNode()</code>),
* it might copy the entire DOM tree, or it might alter the
* node given by the source.
*
* @throws IllegalArgumentException
* If the <code>Result</code> type doesn't match the
* <code>Source</code> type of if the <code>Source</code>
* is an XML artifact that the implementation cannot
* validate (for example, a processing instruction).
* @throws SAXException
* If the <code>ErrorHandler</code> throws a
* <code>SAXException</code> or
* if a fatal error is found and the <code>ErrorHandler</code> returns
* normally.
* @throws IOException
* If the validator is processing a
* <code>SAXSource</code> and the
* underlying {@link org.xml.sax.XMLReader} throws an
* <code>IOException</code>.
* @throws NullPointerException
* If the <code>source</code> parameter is <code>null</code>.
*
* @see #validate(Source source)
*/
public abstract void validate(Source source, Result result)
throws SAXException, IOException;
/**
* Sets the {@link ErrorHandler} to receive errors encountered
* during the <code>validate</code> method invocation.
*
* <p>
* Error handler can be used to customize the error handling process
* during a validation. When an {@link ErrorHandler} is set,
* errors found during the validation will be first sent
* to the {@link ErrorHandler}.
*
* <p>
* The error handler can abort further validation immediately
* by throwing {@link SAXException} from the handler. Or for example
* it can print an error to the screen and try to continue the
* validation by returning normally from the {@link ErrorHandler}
*
* <p>
* If any {@link Throwable} is thrown from an {@link ErrorHandler},
* the caller of the <code>validate</code> method will be thrown
* the same {@link Throwable} object.
*
* <p>
* {@link Validator} is not allowed to
* throw {@link SAXException} without first reporting it to
* {@link ErrorHandler}.
*
* <p>
* When the {@link ErrorHandler} is null, the implementation will
* behave as if the following {@link ErrorHandler} is set:
* <pre>
* class DraconianErrorHandler implements {@link ErrorHandler} {
* public void fatalError( {@link org.xml.sax.SAXParseException} e ) throws {@link SAXException} {
* throw e;
* }
* public void error( {@link org.xml.sax.SAXParseException} e ) throws {@link SAXException} {
* throw e;
* }
* public void warning( {@link org.xml.sax.SAXParseException} e ) throws {@link SAXException} {
* // noop
* }
* }
* </pre>
*
* <p>
* When a new {@link Validator} object is created, initially
* this field is set to null.
*
* @param errorHandler
* A new error handler to be set. This parameter can be null.
*/
public abstract void setErrorHandler(ErrorHandler errorHandler);
/**
* Gets the current {@link ErrorHandler} set to this {@link Validator}.
*
* @return
* This method returns the object that was last set through
* the {@link #setErrorHandler(ErrorHandler)} method, or null
* if that method has never been called since this {@link Validator}
* has created.
*
* @see #setErrorHandler(ErrorHandler)
*/
public abstract ErrorHandler getErrorHandler();
/**
* Sets the {@link LSResourceResolver} to customize
* resource resolution while in a validation episode.
*
* <p>
* {@link Validator} uses a {@link LSResourceResolver}
* when it needs to locate external resources while a validation,
* although exactly what constitutes "locating external resources" is
* up to each schema language.
*
* <p>
* When the {@link LSResourceResolver} is null, the implementation will
* behave as if the following {@link LSResourceResolver} is set:
* <pre>
* class DumbLSResourceResolver implements {@link LSResourceResolver} {
* public {@link org.w3c.dom.ls.LSInput} resolveResource(
* String publicId, String systemId, String baseURI) {
*
* return null; // always return null
* }
* }
* </pre>
*
* <p>
* If a {@link LSResourceResolver} throws a {@link RuntimeException}
* (or instances of its derived classes),
* then the {@link Validator} will abort the parsing and
* the caller of the <code>validate</code> method will receive
* the same {@link RuntimeException}.
*
* <p>
* When a new {@link Validator} object is created, initially
* this field is set to null.
*
* @param resourceResolver
* A new resource resolver to be set. This parameter can be null.
*/
public abstract void setResourceResolver(LSResourceResolver resourceResolver);
/**
* Gets the current {@link LSResourceResolver} set to this {@link Validator}.
*
* @return
* This method returns the object that was last set through
* the {@link #setResourceResolver(LSResourceResolver)} method, or null
* if that method has never been called since this {@link Validator}
* has created.
*
* @see #setErrorHandler(ErrorHandler)
*/
public abstract LSResourceResolver getResourceResolver();
/**
* Look up the value of a feature flag.
*
* <p>The feature name is any fully-qualified URI. It is
* possible for a {@link Validator} to recognize a feature name but
* temporarily be unable to return its value.
* Some feature values may be available only in specific
* contexts, such as before, during, or after a validation.
*
* <p>Implementors are free (and encouraged) to invent their own features,
* using names built on their own URIs.</p>
*
* @param name The feature name, which is a non-null fully-qualified URI.
*
* @return The current value of the feature (true or false).
*
* @throws SAXNotRecognizedException If the feature
* value can't be assigned or retrieved.
* @throws SAXNotSupportedException When the
* {@link Validator} recognizes the feature name but
* cannot determine its value at this time.
* @throws NullPointerException
* When the name parameter is null.
*
* @see #setFeature(String, boolean)
*/
public boolean getFeature(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException("the name parameter is null");
}
throw new SAXNotRecognizedException(name);
}
/**
* Set the value of a feature flag.
*
* <p>
* Feature can be used to control the way a {@link Validator}
* parses schemas, although {@link Validator}s are not required
* to recognize any specific feature names.</p>
*
* <p>The feature name is any fully-qualified URI. It is
* possible for a {@link Validator} to expose a feature value but
* to be unable to change the current value.
* Some feature values may be immutable or mutable only
* in specific contexts, such as before, during, or after
* a validation.</p>
*
* @param name The feature name, which is a non-null fully-qualified URI.
* @param value The requested value of the feature (true or false).
*
* @throws SAXNotRecognizedException If the feature
* value can't be assigned or retrieved.
* @throws SAXNotSupportedException When the
* {@link Validator} recognizes the feature name but
* cannot set the requested value.
* @throws NullPointerException
* When the name parameter is null.
*
* @see #getFeature(String)
*/
public void setFeature(String name, boolean value)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException("the name parameter is null");
}
throw new SAXNotRecognizedException(name);
}
/**
* Set the value of a property.
*
* <p>The property name is any fully-qualified URI. It is
* possible for a {@link Validator} to recognize a property name but
* to be unable to change the current value.
* Some property values may be immutable or mutable only
* in specific contexts, such as before, during, or after
* a validation.</p>
*
* <p>{@link Validator}s are not required to recognize setting
* any specific property names.</p>
*
* @param name The property name, which is a non-null fully-qualified URI.
* @param object The requested value for the property.
*
* @throws SAXNotRecognizedException If the property
* value can't be assigned or retrieved.
* @throws SAXNotSupportedException When the
* {@link Validator} recognizes the property name but
* cannot set the requested value.
* @throws NullPointerException
* When the name parameter is null.
*/
public void setProperty(String name, Object object)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException("the name parameter is null");
}
throw new SAXNotRecognizedException(name);
}
/**
* Look up the value of a property.
*
* <p>The property name is any fully-qualified URI. It is
* possible for a {@link Validator} to recognize a property name but
* temporarily be unable to return its value.
* Some property values may be available only in specific
* contexts, such as before, during, or after a validation.</p>
*
* <p>{@link Validator}s are not required to recognize any specific
* property names.</p>
*
* <p>Implementors are free (and encouraged) to invent their own properties,
* using names built on their own URIs.</p>
*
* @param name The property name, which is a non-null fully-qualified URI.
*
* @return The current value of the property.
*
* @throws SAXNotRecognizedException If the property
* value can't be assigned or retrieved.
* @throws SAXNotSupportedException When the
* XMLReader recognizes the property name but
* cannot determine its value at this time.
* @throws NullPointerException
* When the name parameter is null.
*
* @see #setProperty(String, Object)
*/
public Object getProperty(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException("the name parameter is null");
}
throw new SAXNotRecognizedException(name);
}
}

View file

@ -0,0 +1,485 @@
/*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.validation;
import org.w3c.dom.ls.LSResourceResolver;
import org.xml.sax.ContentHandler;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
/**
* Streaming validator that works on SAX stream.
*
* <p>
* A {@link ValidatorHandler} object is not thread-safe and not reentrant.
* In other words, it is the application's responsibility to make
* sure that one {@link ValidatorHandler} object is not used from
* more than one thread at any given time.
*
* <p>
* {@link ValidatorHandler} checks if the SAX events follow
* the set of constraints described in the associated {@link Schema},
* and additionally it may modify the SAX events (for example
* by adding default values, etc.)
*
* <p>
* {@link ValidatorHandler} extends from {@link ContentHandler},
* but it refines the underlying {@link ContentHandler} in
* the following way:
* <ol>
* <li>startElement/endElement events must receive non-null String
* for <code>uri</code>, <code>localName</code>, and <code>qname</code>,
* even though SAX allows some of them to be null.
* Similarly, the user-specified {@link ContentHandler} will receive non-null
* Strings for all three parameters.
*
* <li>Applications must ensure that {@link ValidatorHandler}'s
* {@link ContentHandler#startPrefixMapping(String,String)} and
* {@link ContentHandler#endPrefixMapping(String)} are invoked
* properly. Similarly, the user-specified {@link ContentHandler}
* will receive startPrefixMapping/endPrefixMapping events.
* If the {@link ValidatorHandler} introduces additional namespace
* bindings, the user-specified {@link ContentHandler} will receive
* additional startPrefixMapping/endPrefixMapping events.
*
* <li>{@link org.xml.sax.Attributes} for the
* {@link ContentHandler#startElement(String,String,String,Attributes)} method
* may or may not include xmlns* attributes.
* </ol>
*
* <p>
* A {@link ValidatorHandler} is automatically reset every time
* the startDocument method is invoked.
*
* <h2>Recognized Properties and Features</h2>
* <p>
* This spec defines the following feature that must be recognized
* by all {@link ValidatorHandler} implementations.
*
* <h3><code>http://xml.org/sax/features/namespace-prefixes</code></h3>
* <p>
* This feature controls how a {@link ValidatorHandler} introduces
* namespace bindings that were not present in the original SAX event
* stream.
* When this feature is set to true, it must make
* sure that the user's {@link ContentHandler} will see
* the corresponding <code>xmlns*</code> attribute in
* the {@link org.xml.sax.Attributes} object of the
* {@link ContentHandler#startElement(String,String,String,Attributes)}
* callback. Otherwise, <code>xmlns*</code> attributes must not be
* added to {@link org.xml.sax.Attributes} that's passed to the
* user-specified {@link ContentHandler}.
* <p>
* (Note that regardless of this switch, namespace bindings are
* always notified to applications through
* {@link ContentHandler#startPrefixMapping(String,String)} and
* {@link ContentHandler#endPrefixMapping(String)} methods of the
* {@link ContentHandler} specified by the user.)
*
* <p>
* Note that this feature does <em>NOT</em> affect the way
* a {@link ValidatorHandler} receives SAX events. It merely
* changes the way it augments SAX events.
*
* <p>This feature is set to <code>false</code> by default.</p>
*
* @author <a href="mailto:Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
* @since 1.5
*/
public abstract class ValidatorHandler implements ContentHandler {
/**
* <p>Constructor for derived classes.</p>
*
* <p>The constructor does nothing.</p>
*
* <p>Derived classes must create {@link ValidatorHandler} objects that have
* <code>null</code> {@link ErrorHandler} and
* <code>null</code> {@link LSResourceResolver}.</p>
*/
protected ValidatorHandler() {
}
/**
* Sets the {@link ContentHandler} which receives
* the augmented validation result.
*
* <p>
* When a {@link ContentHandler} is specified, a
* {@link ValidatorHandler} will work as a filter
* and basically copy the incoming events to the
* specified {@link ContentHandler}.
*
* <p>
* In doing so, a {@link ValidatorHandler} may modify
* the events, for example by adding defaulted attributes.
*
* <p>
* A {@link ValidatorHandler} may buffer events to certain
* extent, but to allow {@link ValidatorHandler} to be used
* by a parser, the following requirement has to be met.
*
* <ol>
* <li>When
* {@link ContentHandler#startElement(String, String, String, Attributes)},
* {@link ContentHandler#endElement(String, String, String)},
* {@link ContentHandler#startDocument()}, or
* {@link ContentHandler#endDocument()}
* are invoked on a {@link ValidatorHandler},
* the same method on the user-specified {@link ContentHandler}
* must be invoked for the same event before the callback
* returns.
* <li>{@link ValidatorHandler} may not introduce new elements that
* were not present in the input.
*
* <li>{@link ValidatorHandler} may not remove attributes that were
* present in the input.
* </ol>
*
* <p>
* When a callback method on the specified {@link ContentHandler}
* throws an exception, the same exception object must be thrown
* from the {@link ValidatorHandler}. The {@link ErrorHandler}
* should not be notified of such an exception.
*
* <p>
* This method can be called even during a middle of a validation.
*
* @param receiver
* A {@link ContentHandler} or a null value.
*/
public abstract void setContentHandler(ContentHandler receiver);
/**
* Gets the {@link ContentHandler} which receives the
* augmented validation result.
*
* @return
* This method returns the object that was last set through
* the {@link #getContentHandler()} method, or null
* if that method has never been called since this {@link ValidatorHandler}
* has created.
*
* @see #setContentHandler(ContentHandler)
*/
public abstract ContentHandler getContentHandler();
/**
* Sets the {@link ErrorHandler} to receive errors encountered
* during the validation.
*
* <p>
* Error handler can be used to customize the error handling process
* during a validation. When an {@link ErrorHandler} is set,
* errors found during the validation will be first sent
* to the {@link ErrorHandler}.
*
* <p>
* The error handler can abort further validation immediately
* by throwing {@link org.xml.sax.SAXException} from the handler. Or for example
* it can print an error to the screen and try to continue the
* validation by returning normally from the {@link ErrorHandler}
*
* <p>
* If any {@link Throwable} is thrown from an {@link ErrorHandler},
* the same {@link Throwable} object will be thrown toward the
* root of the call stack.
*
* <p>
* {@link ValidatorHandler} is not allowed to
* throw {@link org.xml.sax.SAXException} without first reporting it to
* {@link ErrorHandler}.
*
* <p>
* When the {@link ErrorHandler} is null, the implementation will
* behave as if the following {@link ErrorHandler} is set:
* <pre>
* class DraconianErrorHandler implements {@link ErrorHandler} {
* public void fatalError( {@link org.xml.sax.SAXParseException} e ) throws {@link org.xml.sax.SAXException} {
* throw e;
* }
* public void error( {@link org.xml.sax.SAXParseException} e ) throws {@link org.xml.sax.SAXException} {
* throw e;
* }
* public void warning( {@link org.xml.sax.SAXParseException} e ) throws {@link org.xml.sax.SAXException} {
* // noop
* }
* }
* </pre>
*
* <p>
* When a new {@link ValidatorHandler} object is created, initially
* this field is set to null.
*
* @param errorHandler
* A new error handler to be set. This parameter can be null.
*/
public abstract void setErrorHandler(ErrorHandler errorHandler);
/**
* Gets the current {@link ErrorHandler} set to this {@link ValidatorHandler}.
*
* @return
* This method returns the object that was last set through
* the {@link #setErrorHandler(ErrorHandler)} method, or null
* if that method has never been called since this {@link ValidatorHandler}
* has created.
*
* @see #setErrorHandler(ErrorHandler)
*/
public abstract ErrorHandler getErrorHandler();
/**
* Sets the {@link LSResourceResolver} to customize
* resource resolution while in a validation episode.
*
* <p>
* {@link ValidatorHandler} uses a {@link LSResourceResolver}
* when it needs to locate external resources while a validation,
* although exactly what constitutes "locating external resources" is
* up to each schema language.
*
* <p>
* When the {@link LSResourceResolver} is null, the implementation will
* behave as if the following {@link LSResourceResolver} is set:
* <pre>
* class DumbLSResourceResolver implements {@link LSResourceResolver} {
* public {@link org.w3c.dom.ls.LSInput} resolveResource(
* String publicId, String systemId, String baseURI) {
*
* return null; // always return null
* }
* }
* </pre>
*
* <p>
* If a {@link LSResourceResolver} throws a {@link RuntimeException}
* (or instances of its derived classes),
* then the {@link ValidatorHandler} will abort the parsing and
* the caller of the <code>validate</code> method will receive
* the same {@link RuntimeException}.
*
* <p>
* When a new {@link ValidatorHandler} object is created, initially
* this field is set to null.
*
* @param resourceResolver
* A new resource resolver to be set. This parameter can be null.
*/
public abstract void setResourceResolver(LSResourceResolver resourceResolver);
/**
* Gets the current {@link LSResourceResolver} set to this {@link ValidatorHandler}.
*
* @return
* This method returns the object that was last set through
* the {@link #setResourceResolver(LSResourceResolver)} method, or null
* if that method has never been called since this {@link ValidatorHandler}
* has created.
*
* @see #setErrorHandler(ErrorHandler)
*/
public abstract LSResourceResolver getResourceResolver();
/**
* Obtains the {@link TypeInfoProvider} implementation of this
* {@link ValidatorHandler}.
*
* <p>
* The obtained {@link TypeInfoProvider} can be queried during a parse
* to access the type information determined by the validator.
*
* <p>
* Some schema languages do not define the notion of type,
* for those languages, this method may not be supported.
* However, to be compliant with this specification, implementations
* for W3C XML Schema 1.0 must support this operation.
*
* @return
* null if the validator / schema language does not support
* the notion of {@link org.w3c.dom.TypeInfo}.
* Otherwise a non-null valid {@link TypeInfoProvider}.
*/
public abstract TypeInfoProvider getTypeInfoProvider();
/**
* Look up the value of a feature flag.
*
* <p>The feature name is any fully-qualified URI. It is
* possible for a {@link ValidatorHandler} to recognize a feature name but
* temporarily be unable to return its value.
* Some feature values may be available only in specific
* contexts, such as before, during, or after a validation.
*
* <p>Implementors are free (and encouraged) to invent their own features,
* using names built on their own URIs.</p>
*
* @param name The feature name, which is a non-null fully-qualified URI.
*
* @return The current value of the feature (true or false).
*
* @throws SAXNotRecognizedException If the feature
* value can't be assigned or retrieved.
* @throws SAXNotSupportedException When the
* {@link ValidatorHandler} recognizes the feature name but
* cannot determine its value at this time.
* @throws NullPointerException When <code>name</code> is <code>null</code>.
*
* @see #setFeature(String, boolean)
*/
public boolean getFeature(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException();
}
throw new SAXNotRecognizedException(name);
}
/**
* <p>Set a feature for this <code>ValidatorHandler</code>.</p>
*
* <p>Feature can be used to control the way a
* {@link ValidatorHandler} parses schemas. The feature name is
* any fully-qualified URI. It is possible for a
* {@link SchemaFactory} to
* expose a feature value but to be unable to change the current
* value. Some feature values may be immutable or mutable only in
* specific contexts, such as before, during, or after a
* validation.</p>
*
* <p>All implementations are required to support the {@link javax.xml.XMLConstants#FEATURE_SECURE_PROCESSING} feature.
* When the feature is:</p>
* <ul>
* <li>
* <code>true</code>: the implementation will limit XML processing to conform to implementation limits.
* Examples include enity expansion limits and XML Schema constructs that would consume large amounts of resources.
* If XML processing is limited for security reasons, it will be reported via a call to the registered
* {@link ErrorHandler#fatalError(SAXParseException exception)}.
* See {@link #setErrorHandler(ErrorHandler errorHandler)}.
* </li>
* <li>
* <code>false</code>: the implementation will processing XML according to the XML specifications without
* regard to possible implementation limits.
* </li>
* </ul>
*
* @param name The feature name, which is a non-null fully-qualified URI.
* @param value The requested value of the feature (true or false).
*
* @throws SAXNotRecognizedException If the feature
* value can't be assigned or retrieved.
* @throws SAXNotSupportedException When the
* {@link ValidatorHandler} recognizes the feature name but
* cannot set the requested value.
* @throws NullPointerException When <code>name</code> is <code>null</code>.
*
* @see #getFeature(String)
*/
public void setFeature(String name, boolean value)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException();
}
throw new SAXNotRecognizedException(name);
}
/**
* Set the value of a property.
*
* <p>The property name is any fully-qualified URI. It is
* possible for a {@link ValidatorHandler} to recognize a property name but
* to be unable to change the current value.
* Some property values may be immutable or mutable only
* in specific contexts, such as before, during, or after
* a validation.</p>
*
* <p>{@link ValidatorHandler}s are not required to recognize setting
* any specific property names.</p>
*
* @param name The property name, which is a non-null fully-qualified URI.
* @param object The requested value for the property.
*
* @throws SAXNotRecognizedException If the property
* value can't be assigned or retrieved.
* @throws SAXNotSupportedException When the
* {@link ValidatorHandler} recognizes the property name but
* cannot set the requested value.
* @throws NullPointerException When <code>name</code> is <code>null</code>.
*/
public void setProperty(String name, Object object)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException();
}
throw new SAXNotRecognizedException(name);
}
/**
* Look up the value of a property.
*
* <p>The property name is any fully-qualified URI. It is
* possible for a {@link ValidatorHandler} to recognize a property name but
* temporarily be unable to return its value.
* Some property values may be available only in specific
* contexts, such as before, during, or after a validation.</p>
*
* <p>{@link ValidatorHandler}s are not required to recognize any specific
* property names.</p>
*
* <p>Implementors are free (and encouraged) to invent their own properties,
* using names built on their own URIs.</p>
*
* @param name The property name, which is a non-null fully-qualified URI.
*
* @return The current value of the property.
*
* @throws SAXNotRecognizedException If the property
* value can't be assigned or retrieved.
* @throws SAXNotSupportedException When the
* XMLReader recognizes the property name but
* cannot determine its value at this time.
* @throws NullPointerException When <code>name</code> is <code>null</code>.
*
* @see #setProperty(String, Object)
*/
public Object getProperty(String name)
throws SAXNotRecognizedException, SAXNotSupportedException {
if (name == null) {
throw new NullPointerException();
}
throw new SAXNotRecognizedException(name);
}
}

View file

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation. Sun designates this
particular file as subject to the "Classpath" exception as provided
by Sun in the LICENSE file that accompanied this code.
This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).
You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
CA 95054 USA or visit www.sun.com if you need additional information or
have any questions.
-->
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>javax.xml.validation</title>
<meta name="CVS"
content="$Id: package.html,v 1.2 2005/06/10 03:50:43 jeffsuttor Exp $" />
<meta name="AUTHOR"
content="Jeff.Suttor@Sun.com" />
</head>
<body>
<p>
This package provides an API for validation of XML documents. <em>Validation</em> is the process of verifying
that an XML document is an instance of a specified XML <em>schema</em>. An XML schema defines the
content model (also called a <em>grammar</em> or <em>vocabulary</em>) that its instance documents
will represent.
</p>
<p>
There are a number of popular technologies available for creating an XML schema. Some of the most
popular include:
</p>
<ul>
<li><strong>Document Type Definition (DTD)</strong> - XML's built-in schema language.</li>
<li><strong><a href="http://www.w3.org/XML/Schema">W3C XML Schema (WXS)</a></strong> - an object-oriented XML schema
language. WXS also provides a type system for constraining the character data of an XML document.
WXS is maintained by the <a href="http://www.w3.org">World Wide Web Consortium (W3C)</a> and is a W3C
Recommendation (that is, a ratified W3C standard specification).</li>
<li><strong><a href="http://www.relaxng.org">RELAX NG (RNG)</a></strong> - a pattern-based,
user-friendly XML schema language. RNG schemas may also use types to constrain XML character data.
RNG is maintained by the <a href="http://www.oasis-open.org">Organization for the Advancement of
Structured Information Standards (OASIS)</a> and is both an OASIS and an
<a href="http://www.iso.org">ISO (International Organization for Standardization)</a> standard.</li>
<li><strong><a href="http://www.schematron.com/">Schematron</a></strong> - a rules-based XML schema
language. Whereas DTD, WXS, and RNG are designed to express the structure of a content model,
Schematron is designed to enforce individual rules that are difficult or impossible to express
with other schema languages. Schematron is intended to supplement a schema written in
structural schema language such as the aforementioned. Schematron is in the process
of becoming an ISO standard.</li>
</ul>
<p>
Previous versions of JAXP supported validation as a feature of an XML parser, represented by
either a {@link javax.xml.parsers.SAXParser} or {@link javax.xml.parsers.DocumentBuilder} instance.
</p>
<p>
The JAXP validation API decouples the validation of an instance document from the parsing of an
XML document. This is advantageous for several reasons, some of which are:
</p>
<ul>
<li><strong>Support for additional schema langauges.</strong> As of JDK 1.5, the two most
popular JAXP parser implementations, Crimson and Xerces, only support a subset of the available
XML schema languages. The Validation API provides a standard mechanism through which applications
may take of advantage of specialization validation libraries which support additional schema
languages.</li>
<li><strong>Easy runtime coupling of an XML instance and schema.</strong> Specifying the location
of a schema to use for validation with JAXP parsers can be confusing. The Validation API makes this
process simple (see <a href="#example-1">example</a> below).</li>
</ul>
<p>
<a name="example-1"><strong>Usage example</strong>.</a> The following example demonstrates validating
an XML document with the Validation API (for readability, some exception handling is not shown):
</p>
<pre>
// parse an XML document into a DOM tree
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(new File("instance.xml"));
// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// load a WXS schema, represented by a Schema instance
Source schemaFile = new StreamSource(new File("mySchema.xsd"));
Schema schema = factory.newSchema(schemaFile);
// create a Validator instance, which can be used to validate an instance document
Validator validator = schema.newValidator();
// validate the DOM tree
try {
validator.validate(new DOMSource(document));
} catch (SAXException e) {
// instance document is invalid!
}
</pre>
<p>
The JAXP parsing API has been integrated with the Validation API. Applications may create a {@link javax.xml.validation.Schema} with the validation API
and associate it with a {@link javax.xml.parsers.DocumentBuilderFactory} or a {@link javax.xml.parsers.SAXParserFactory} instance
by using the {@link javax.xml.parsers.DocumentBuilderFactory#setSchema(Schema)} and {@link javax.xml.parsers.SAXParserFactory#setSchema(Schema)}
methods. <strong>You should not</strong> both set a schema and call <code>setValidating(true)</code> on a parser factory. The former technique
will cause parsers to use the new validation API; the latter will cause parsers to use their own internal validation
facilities. <strong>Turning on both of these options simultaneously will cause either redundant behavior or error conditions.</strong>
</p>
</body>
</html>

View file

@ -0,0 +1,160 @@
/*
* Copyright 2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.xpath;
import java.net.URL;
import java.security.*;
import java.net.*;
import java.io.*;
import java.util.*;
/**
* 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 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;
}
});
}
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 getURLInputStream(final URL url)
throws IOException
{
try {
return (InputStream)
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IOException {
return url.openStream();
}
});
} catch (PrivilegedActionException e) {
throw (IOException)e.getException();
}
}
URL getResourceAsURL(final ClassLoader cl,
final String name)
{
return (URL)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
URL url;
if (cl == null) {
url = ClassLoader.getSystemResource(name);
} else {
url = cl.getResource(name);
}
return url;
}
});
}
Enumeration getResources(final ClassLoader cl,
final String name) throws IOException
{
try{
return (Enumeration)
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws IOException{
Enumeration enumeration;
if (cl == null) {
enumeration = ClassLoader.getSystemResources(name);
} else {
enumeration = cl.getResources(name);
}
return enumeration;
}
});
}catch(PrivilegedActionException e){
throw (IOException)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 doesFileExist(final File f) {
return ((Boolean)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return new Boolean(f.exists());
}
})).booleanValue();
}
}

View file

@ -0,0 +1,319 @@
/*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.xpath;
import org.xml.sax.InputSource;
import javax.xml.namespace.QName;
import javax.xml.namespace.NamespaceContext;
/**
* <p><code>XPath</code> provides access to the XPath evaluation environment and expressions.</p>
*
* <a name="XPath-evaluation"/>
* <table border="1" cellpadding="2">
* <thead>
* <tr>
* <th colspan="2">Evaluation of XPath Expressions.</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>context</td>
* <td>
* If a request is made to evaluate the expression in the absence
* of a context item, an empty document node will be used for the context.
* For the purposes of evaluating XPath expressions, a DocumentFragment
* is treated like a Document node.
* </td>
* </tr>
* <tr>
* <td>variables</td>
* <td>
* If the expression contains a variable reference, its value will be found through the {@link XPathVariableResolver}
* set with {@link #setXPathVariableResolver(XPathVariableResolver resolver)}.
* An {@link XPathExpressionException} is raised if the variable resolver is undefined or
* the resolver returns <code>null</code> for the variable.
* The value of a variable must be immutable through the course of any single evaluation.</p>
* </td>
* </tr>
* <tr>
* <td>functions</td>
* <td>
* If the expression contains a function reference, the function will be found through the {@link XPathFunctionResolver}
* set with {@link #setXPathFunctionResolver(XPathFunctionResolver resolver)}.
* An {@link XPathExpressionException} is raised if the function resolver is undefined or
* the function resolver returns <code>null</code> for the function.</p>
* </td>
* </tr>
* <tr>
* <td>QNames</td>
* <td>
* QNames in the expression are resolved against the XPath namespace context
* set with {@link #setNamespaceContext(NamespaceContext nsContext)}.
* </td>
* </tr>
* <tr>
* <td>result</td>
* <td>
* This result of evaluating an expression is converted to an instance of the desired return type.
* Valid return types are defined in {@link XPathConstants}.
* Conversion to the return type follows XPath conversion rules.</p>
* </td>
* </tr>
* </table>
*
* <p>An XPath object is not thread-safe and not reentrant.
* In other words, it is the application's responsibility to make
* sure that one {@link XPath} object is not used from
* more than one thread at any given time, and while the <code>evaluate</code>
* method is invoked, applications may not recursively call
* the <code>evaluate</code> method.
* <p>
*
* @author <a href="Norman.Walsh@Sun.com">Norman Walsh</a>
* @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @see <a href="http://www.w3.org/TR/xpath">XML Path Language (XPath) Version 1.0</a>
* @since 1.5
*/
public interface XPath {
/**
* <p>Reset this <code>XPath</code> to its original configuration.</p>
*
* <p><code>XPath</code> is reset to the same state as when it was created with
* {@link XPathFactory#newXPath()}.
* <code>reset()</code> is designed to allow the reuse of existing <code>XPath</code>s
* thus saving resources associated with the creation of new <code>XPath</code>s.</p>
*
* <p>The reset <code>XPath</code> is not guaranteed to have the same {@link XPathFunctionResolver}, {@link XPathVariableResolver}
* or {@link NamespaceContext} <code>Object</code>s, e.g. {@link Object#equals(Object obj)}.
* It is guaranteed to have a functionally equal <code>XPathFunctionResolver</code>, <code>XPathVariableResolver</code>
* and <code>NamespaceContext</code>.</p>
*/
public void reset();
/**
* <p>Establish a variable resolver.</p>
*
* <p>A <code>NullPointerException</code> is thrown if <code>resolver</code> is <code>null</code>.</p>
*
* @param resolver Variable resolver.
*
* @throws NullPointerException If <code>resolver</code> is <code>null</code>.
*/
public void setXPathVariableResolver(XPathVariableResolver resolver);
/**
* <p>Return the current variable resolver.</p>
*
* <p><code>null</code> is returned in no variable resolver is in effect.</p>
*
* @return Current variable resolver.
*/
public XPathVariableResolver getXPathVariableResolver();
/**
* <p>Establish a function resolver.</p>
*
* <p>A <code>NullPointerException</code> is thrown if <code>resolver</code> is <code>null</code>.</p>
*
* @param resolver XPath function resolver.
*
* @throws NullPointerException If <code>resolver</code> is <code>null</code>.
*/
public void setXPathFunctionResolver(XPathFunctionResolver resolver);
/**
* <p>Return the current function resolver.</p>
*
* <p><code>null</code> is returned in no function resolver is in effect.</p>
*
* @return Current function resolver.
*/
public XPathFunctionResolver getXPathFunctionResolver();
/**
* <p>Establish a namespace context.</p>
*
* <p>A <code>NullPointerException</code> is thrown if <code>nsContext</code> is <code>null</code>.</p>
*
* @param nsContext Namespace context to use.
*
* @throws NullPointerException If <code>nsContext</code> is <code>null</code>.
*/
public void setNamespaceContext(NamespaceContext nsContext);
/**
* <p>Return the current namespace context.</p>
*
* <p><code>null</code> is returned in no namespace context is in effect.</p>
*
* @return Current Namespace context.
*/
public NamespaceContext getNamespaceContext();
/**
* <p>Compile an XPath expression for later evaluation.</p>
*
* <p>If <code>expression</code> contains any {@link XPathFunction}s,
* they must be available via the {@link XPathFunctionResolver}.
* An {@link XPathExpressionException} will be thrown if the
* <code>XPathFunction</code>
* cannot be resovled with the <code>XPathFunctionResolver</code>.</p>
*
* <p>If <code>expression</code> contains any variables, the
* {@link XPathVariableResolver} in effect
* <strong>at compile time</strong> will be used to resolve them.</p>
*
* <p>If <code>expression</code> is <code>null</code>, a <code>NullPointerException</code> is thrown.</p>
*
* @param expression The XPath expression.
*
* @return Compiled XPath expression.
* @throws XPathExpressionException If <code>expression</code> cannot be compiled.
* @throws NullPointerException If <code>expression</code> is <code>null</code>.
*/
public XPathExpression compile(String expression)
throws XPathExpressionException;
/**
* <p>Evaluate an <code>XPath</code> expression in the specified context and return the result as the specified type.</p>
*
* <p>See <a href="#XPath-evaluation">Evaluation of XPath Expressions</a> for context item evaluation,
* variable, function and <code>QName</code> resolution and return type conversion.</p>
*
* <p>If <code>returnType</code> is not one of the types defined in {@link XPathConstants} (
* {@link XPathConstants#NUMBER NUMBER},
* {@link XPathConstants#STRING STRING},
* {@link XPathConstants#BOOLEAN BOOLEAN},
* {@link XPathConstants#NODE NODE} or
* {@link XPathConstants#NODESET NODESET})
* then an <code>IllegalArgumentException</code> is thrown.</p>
*
* <p>If a <code>null</code> value is provided for
* <code>item</code>, an empty document will be used for the
* context.
* If <code>expression</code> or <code>returnType</code> is <code>null</code>, then a
* <code>NullPointerException</code> is thrown.</p>
*
* @param expression The XPath expression.
* @param item The starting context (a node, for example).
* @param returnType The desired return type.
*
* @return Result of evaluating an XPath expression as an <code>Object</code> of <code>returnType</code>.
*
* @throws XPathExpressionException If <code>expression</code> cannot be evaluated.
* @throws IllegalArgumentException If <code>returnType</code> is not one of the types defined in {@link XPathConstants}.
* @throws NullPointerException If <code>expression</code> or <code>returnType</code> is <code>null</code>.
*/
public Object evaluate(String expression, Object item, QName returnType)
throws XPathExpressionException;
/**
* <p>Evaluate an XPath expression in the specified context and return the result as a <code>String</code>.</p>
*
* <p>This method calls {@link #evaluate(String expression, Object item, QName returnType)} with a <code>returnType</code> of
* {@link XPathConstants#STRING}.</p>
*
* <p>See <a href="#XPath-evaluation">Evaluation of XPath Expressions</a> for context item evaluation,
* variable, function and QName resolution and return type conversion.</p>
*
* <p>If a <code>null</code> value is provided for
* <code>item</code>, an empty document will be used for the
* context.
* If <code>expression</code> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</p>
*
* @param expression The XPath expression.
* @param item The starting context (a node, for example).
*
* @return The <code>String</code> that is the result of evaluating the expression and
* converting the result to a <code>String</code>.
*
* @throws XPathExpressionException If <code>expression</code> cannot be evaluated.
* @throws NullPointerException If <code>expression</code> is <code>null</code>.
*/
public String evaluate(String expression, Object item)
throws XPathExpressionException;
/**
* <p>Evaluate an XPath expression in the context of the specified <code>InputSource</code>
* and return the result as the specified type.</p>
*
* <p>This method builds a data model for the {@link InputSource} and calls
* {@link #evaluate(String expression, Object item, QName returnType)} on the resulting document object.</p>
*
* <p>See <a href="#XPath-evaluation">Evaluation of XPath Expressions</a> for context item evaluation,
* variable, function and QName resolution and return type conversion.</p>
*
* <p>If <code>returnType</code> is not one of the types defined in {@link XPathConstants},
* then an <code>IllegalArgumentException</code> is thrown.</p>
*
* <p>If <code>expression</code>, <code>source</code> or <code>returnType</code> is <code>null</code>,
* then a <code>NullPointerException</code> is thrown.</p>
*
* @param expression The XPath expression.
* @param source The input source of the document to evaluate over.
* @param returnType The desired return type.
*
* @return The <code>Object</code> that encapsulates the result of evaluating the expression.
*
* @throws XPathExpressionException If expression cannot be evaluated.
* @throws IllegalArgumentException If <code>returnType</code> is not one of the types defined in {@link XPathConstants}.
* @throws NullPointerException If <code>expression</code>, <code>source</code> or <code>returnType</code>
* is <code>null</code>.
*/
public Object evaluate(
String expression,
InputSource source,
QName returnType)
throws XPathExpressionException;
/**
* <p>Evaluate an XPath expression in the context of the specified <code>InputSource</code>
* and return the result as a <code>String</code>.</p>
*
* <p>This method calls {@link #evaluate(String expression, InputSource source, QName returnType)} with a
* <code>returnType</code> of {@link XPathConstants#STRING}.</p>
*
* <p>See <a href="#XPath-evaluation">Evaluation of XPath Expressions</a> for context item evaluation,
* variable, function and QName resolution and return type conversion.</p>
*
* <p>If <code>expression</code> or <code>source</code> is <code>null</code>,
* then a <code>NullPointerException</code> is thrown.</p>
*
* @param expression The XPath expression.
* @param source The <code>InputSource</code> of the document to evaluate over.
*
* @return The <code>String</code> that is the result of evaluating the expression and
* converting the result to a <code>String</code>.
*
* @throws XPathExpressionException If expression cannot be evaluated.
* @throws NullPointerException If <code>expression</code> or <code>source</code> is <code>null</code>.
*/
public String evaluate(String expression, InputSource source)
throws XPathExpressionException;
}

View file

@ -0,0 +1,84 @@
/*
* Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package javax.xml.xpath;
import javax.xml.namespace.QName;
/**
* <p>XPath constants.</p>
*
* @author <a href="mailto:Norman.Walsh@Sun.COM">Norman Walsh</a>
* @author <a href="mailto:Jeff.Suttor@Sun.COM">Jeff Suttor</a>
* @see <a href="http://www.w3.org/TR/xpath">XML Path Language (XPath) Version 1.0</a>
* @since 1.5
*/
public class XPathConstants {
/**
* <p>Private constructor to prevent instantiation.</p>
*/
private XPathConstants() { }
/**
* <p>The XPath 1.0 number data type.</p>
*
* <p>Maps to Java {@link Double}.</p>
*/
public static final QName NUMBER = new QName("http://www.w3.org/1999/XSL/Transform", "NUMBER");
/**
* <p>The XPath 1.0 string data type.</p>
*
* <p>Maps to Java {@link String}.</p>
*/
public static final QName STRING = new QName("http://www.w3.org/1999/XSL/Transform", "STRING");
/**
* <p>The XPath 1.0 boolean data type.</p>
*
* <p>Maps to Java {@link Boolean}.</p>
*/
public static final QName BOOLEAN = new QName("http://www.w3.org/1999/XSL/Transform", "BOOLEAN");
/**
* <p>The XPath 1.0 NodeSet data type.</p>
*
* <p>Maps to Java {@link org.w3c.dom.NodeList}.</p>
*/
public static final QName NODESET = new QName("http://www.w3.org/1999/XSL/Transform", "NODESET");
/**
* <p>The XPath 1.0 NodeSet data type.
*
* <p>Maps to Java {@link org.w3c.dom.Node}.</p>
*/
public static final QName NODE = new QName("http://www.w3.org/1999/XSL/Transform", "NODE");
/**
* <p>The URI for the DOM object model, "http://java.sun.com/jaxp/xpath/dom".</p>
*/
public static final String DOM_OBJECT_MODEL = "http://java.sun.com/jaxp/xpath/dom";
}

Some files were not shown because too many files have changed in this diff Show more