Upgrading to JAXP 1.3 APIs.

git-svn-id: https://svn.apache.org/repos/asf/xml/commons/trunk@226183 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
neeraj 2005-04-08 10:39:14 +00:00
parent 71fde1266d
commit 5b838d686f
62 changed files with 10589 additions and 2458 deletions

View File

@ -0,0 +1,187 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
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>
* @version $Revision$, $Date$
* @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,75 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
package javax.xml.datatype;
/**
* <p>Indicates a serious configuration error.</p>
*
* TODO: support all constructors
*
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision$, $Date$
* @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,267 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
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>
* @version $Revision$, $Date$
* @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.
*/
public static final class Field {
/**
* <p><code>String</code> representation of <ode>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;
}

View File

@ -0,0 +1,934 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
package javax.xml.datatype;
import java.math.BigInteger;
import java.math.BigDecimal;
import java.util.GregorianCalendar;
/**
* <p>Factory that creates new <code>javax.xml.datatype</code> <code>Object</code>s that map XML to/from Java <code>Object</code>s.</p>
*
* <p id="DatatypeFactory.newInstance">{@link #newInstance()} is used to create a new <code>DatatypeFactory</code>.
* The following implementation resolution mechanisms are used in the following order:</p>
* <ol>
* <li>
* If the system property specified by {@link #DATATYPEFACTORY_PROPERTY}, "<code>javax.xml.datatype.DatatypeFactory</code>",
* exists, a class with the name of the property's value is instantiated.
* Any Exception thrown during the instantiation process is wrapped as a {@link DatatypeConfigurationException}.
* </li>
* <li>
* If the file ${JAVA_HOME}/lib/jaxp.properties exists, it is loaded in a {@link java.util.Properties} <code>Object</code>.
* The <code>Properties</code> <code>Object </code> is then queried for the property as documented in the prior step
* and processed as documented in the prior step.
* </li>
* <li>
* The services resolution mechanism is used, e.g. <code>META-INF/services/java.xml.datatype.DatatypeFactory</code>.
* Any Exception thrown during the instantiation process is wrapped as a {@link DatatypeConfigurationException}.
* </li>
* <li>
* The final mechanism is to attempt to instantiate the <code>Class</code> specified by
* {@link #DATATYPEFACTORY_IMPLEMENTATION_CLASS}, "<code>javax.xml.datatype.DatatypeFactoryImpl</code>".
* Any Exception thrown during the instantiation process is wrapped as a {@link DatatypeConfigurationException}.
* </li>
* </ol>
*
* @author <a href="mailto:Joseph.Fialli@Sun.COM">Joseph Fialli</a>
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision$, $Date$
* @since 1.5
*/
public abstract class DatatypeFactory {
/**
* <p>Default property name as defined in JSR 206: Java(TM) API for XML Processing (JAXP) 1.3.</p>
*
* <p>Default value is <code>javax.xml.datatype.DatatypeFactory</code>.</p>
*/
public static final String DATATYPEFACTORY_PROPERTY = "javax.xml.datatype.DatatypeFactory";
/**
* <p>Default implementation class name as defined in JSR 206: Java(TM) API for XML Processing (JAXP) 1.3.</p>
*
* <p>Default value is <code>org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl</code>.</p>
*/
public static final String DATATYPEFACTORY_IMPLEMENTATION_CLASS = "org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl";
/**
* <p>Protected constructor to prevent instaniation outside of package.</p>
*
* <p>Use {@link #newInstance()} to create a <code>DatatypeFactory</code>.</p>
*/
protected DatatypeFactory() {
}
/**
* <p>Obtain a new instance of a <code>DatatypeFactory</code>.</p>
*
* <p>The implementation resolution mechanisms are <a href="#DatatypeFactory.newInstance">defined</a> in this
* <code>Class</code>'s documentation.</p>
*
* @return New instance of a <code>DocumentBuilderFactory</code>
*
* @throws DatatypeConfigurationException If the implementation is not
* available or cannot be instantiated.
*/
public static DatatypeFactory newInstance()
throws DatatypeConfigurationException {
try {
return (DatatypeFactory) FactoryFinder.find(
/* The default property name according to the JAXP spec */
DATATYPEFACTORY_PROPERTY,
/* The fallback implementation class name */
DATATYPEFACTORY_IMPLEMENTATION_CLASS);
} catch (FactoryFinder.ConfigurationError e) {
throw new DatatypeConfigurationException(e.getMessage(), e.getException());
}
}
/**
* <p>Obtain a new instance of a <code>Duration</code>
* specifying the <code>Duration</code> as its string representation, "PnYnMnDTnHnMnS",
* as defined in XML Schema 1.0 section 3.2.6.1.</p>
*
* <p>XML Schema Part 2: Datatypes, 3.2.6 duration, defines <code>duration</code> as:</p>
* <blockquote>
* duration represents a duration of time.
* The value space of duration is a six-dimensional space where the coordinates designate the
* Gregorian year, month, day, hour, minute, and second components defined in Section 5.5.3.2 of [ISO 8601], respectively.
* These components are ordered in their significance by their order of appearance i.e. as
* year, month, day, hour, minute, and second.
* </blockquote>
* <p>All six values are set and availabe from the created {@link Duration}</p>
*
* <p>The XML Schema specification states that values can be of an arbitrary size.
* Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values.
* An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits
* if implementation capacities are exceeded.</p>
*
* @param lexicalRepresentation <code>String</code> representation of a <code>Duration</code>.
*
* @return New <code>Duration</code> created from parsing the <code>lexicalRepresentation</code>.
*
* @throws IllegalArgumentException If <code>lexicalRepresentation</code> is not a valid representation of a <code>Duration</code>.
* @throws UnsupportedOperationException If implementation cannot support requested values.
* @throws NullPointerException if <code>lexicalRepresentation</code> is <code>null</code>.
*/
public abstract Duration newDuration(final String lexicalRepresentation);
/**
* <p>Obtain a new instance of a <code>Duration</code>
* specifying the <code>Duration</code> as milliseconds.</p>
*
* <p>XML Schema Part 2: Datatypes, 3.2.6 duration, defines <code>duration</code> as:</p>
* <blockquote>
* duration represents a duration of time.
* The value space of duration is a six-dimensional space where the coordinates designate the
* Gregorian year, month, day, hour, minute, and second components defined in Section 5.5.3.2 of [ISO 8601], respectively.
* These components are ordered in their significance by their order of appearance i.e. as
* year, month, day, hour, minute, and second.
* </blockquote>
* <p>All six values are set by computing their values from the specified milliseconds
* and are availabe using the <code>get</code> methods of the created {@link Duration}.
* The values conform to and are defined by:</p>
* <ul>
* <li>ISO 8601:2000(E) Section 5.5.3.2 Alternative format</li>
* <li><a href="http://www.w3.org/TR/xmlschema-2/#isoformats">
* W3C XML Schema 1.0 Part 2, Appendix D, ISO 8601 Date and Time Formats</a>
* </li>
* <li>{@link XMLGregorianCalendar} Date/Time Datatype Field Mapping Between XML Schema 1.0 and Java Representation</li>
* </ul>
*
* <p>The default start instance is defined by {@link GregorianCalendar}'s use of the start of the epoch: i.e.,
* {@link java.util.Calendar#YEAR} = 1970,
* {@link java.util.Calendar#MONTH} = {@link java.util.Calendar#JANUARY},
* {@link java.util.Calendar#DATE} = 1, etc.
* This is important as there are variations in the Gregorian Calendar,
* e.g. leap years have different days in the month = {@link java.util.Calendar#FEBRUARY}
* so the result of {@link Duration#getMonths()} and {@link Duration#getDays()} can be influenced.</p>
*
* @param durationInMilliSeconds Duration in milliseconds to create.
*
* @return New <code>Duration</code> representing <code>durationInMilliSeconds</code>.
*/
public abstract Duration newDuration(final long durationInMilliSeconds);
/**
* <p>Obtain a new instance of a <code>Duration</code>
* specifying the <code>Duration</code> as isPositive, years, months, days, hours, minutes, seconds.</p>
*
* <p>The XML Schema specification states that values can be of an arbitrary size.
* Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values.
* An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits
* if implementation capacities are exceeded.</p>
*
* <p>A <code>null</code> value indicates that field isnot set.</p>
*
* @param isPositive Set to <code>false</code> to create a negative duration. When the length
* of the duration is zero, this parameter will be ignored.
* @param years of this <code>Duration</code>
* @param months of this <code>Duration</code>
* @param days of this <code>Duration</code>
* @param hours of this <code>Duration</code>
* @param minutes of this <code>Duration</code>
* @param seconds of this <code>Duration</code>
*
* @return New <code>Duration</code> created from the specified values.
*
* @throws IllegalArgumentException If values are not a valid representation of a <code>Duration</code>.
* @throws UnsupportedOperationException If implementation cannot support requested values.
*/
public abstract Duration newDuration(
final boolean isPositive,
final BigInteger years,
final BigInteger months,
final BigInteger days,
final BigInteger hours,
final BigInteger minutes,
final BigDecimal seconds);
/**
* <p>Obtain a new instance of a <code>Duration</code>
* specifying the <code>Duration</code> as isPositive, years, months, days, hours, minutes, seconds.</p>
*
* <p>A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field isnot set.</p>
*
* @param isPositive Set to <code>false</code> to create a negative duration. When the length
* of the duration is zero, this parameter will be ignored.
* @param years of this <code>Duration</code>
* @param months of this <code>Duration</code>
* @param days of this <code>Duration</code>
* @param hours of this <code>Duration</code>
* @param minutes of this <code>Duration</code>
* @param seconds of this <code>Duration</code>
*
* @return New <code>Duration</code> created from the specified values.
*
* @throws IllegalArgumentException If values are not a valid representation of a <code>Duration</code>.
*
* @see #newDuration(
* boolean isPositive,
* BigInteger years,
* BigInteger months,
* BigInteger days,
* BigInteger hours,
* BigInteger minutes,
* BigDecimal seconds)
*/
public Duration newDuration(
final boolean isPositive,
final int years,
final int months,
final int days,
final int hours,
final int minutes,
final int seconds) {
// years may not be set
BigInteger realYears = (years != DatatypeConstants.FIELD_UNDEFINED) ? BigInteger.valueOf((long) years) : null;
// months may not be set
BigInteger realMonths = (months != DatatypeConstants.FIELD_UNDEFINED) ? BigInteger.valueOf((long) months) : null;
// days may not be set
BigInteger realDays = (days != DatatypeConstants.FIELD_UNDEFINED) ? BigInteger.valueOf((long) days) : null;
// hours may not be set
BigInteger realHours = (hours != DatatypeConstants.FIELD_UNDEFINED) ? BigInteger.valueOf((long) hours) : null;
// minutes may not be set
BigInteger realMinutes = (minutes != DatatypeConstants.FIELD_UNDEFINED) ? BigInteger.valueOf((long) minutes) : null;
// seconds may not be set
BigDecimal realSeconds = (seconds != DatatypeConstants.FIELD_UNDEFINED) ? BigDecimal.valueOf((long) seconds) : null;
return newDuration(
isPositive,
realYears,
realMonths,
realDays,
realHours,
realMinutes,
realSeconds
);
}
/**
* <p>Create a <code>Duration</code> of type <code>xdt:dayTimeDuration</code> by parsing its <code>String</code> representation,
* "<em>PnDTnHnMnS</em>", <a href="http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration">
* XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration</a>.</p>
*
* <p>The datatype <code>xdt:dayTimeDuration</code> is a subtype of <code>xs:duration</code>
* whose lexical representation contains only day, hour, minute, and second components.
* This datatype resides in the namespace <code>http://www.w3.org/2003/11/xpath-datatypes</code>.</p>
*
* <p>All four values are set and availabe from the created {@link Duration}</p>
*
* <p>The XML Schema specification states that values can be of an arbitrary size.
* Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values.
* An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits
* if implementation capacities are exceeded.</p>
*
* @param lexicalRepresentation Lexical representation of a duration.
*
* @return New <code>Duration</code> created using the specified <code>lexicalRepresentation</code>.
*
* @throws IllegalArgumentException If the given string does not conform to the aforementioned specification.
* @throws UnsupportedOperationException If implementation cannot support requested values.
* @throws NullPointerException If <code>lexicalRepresentation</code> is <code>null</code>.
*/
public Duration newDurationDayTime(final String lexicalRepresentation) {
return newDuration(lexicalRepresentation);
}
/**
* <p>Create a <code>Duration</code> of type <code>xdt:dayTimeDuration</code> using the specified milliseconds as defined in
* <a href="http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration">
* XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration</a>.</p>
*
* <p>The datatype <code>xdt:dayTimeDuration</code> is a subtype of <code>xs:duration</code>
* whose lexical representation contains only day, hour, minute, and second components.
* This datatype resides in the namespace <code>http://www.w3.org/2003/11/xpath-datatypes</code>.</p>
*
* <p>All four values are set by computing their values from the specified milliseconds
* and are availabe using the <code>get</code> methods of the created {@link Duration}.
* The values conform to and are defined by:</p>
* <ul>
* <li>ISO 8601:2000(E) Section 5.5.3.2 Alternative format</li>
* <li><a href="http://www.w3.org/TR/xmlschema-2/#isoformats">
* W3C XML Schema 1.0 Part 2, Appendix D, ISO 8601 Date and Time Formats</a>
* </li>
* <li>{@link XMLGregorianCalendar} Date/Time Datatype Field Mapping Between XML Schema 1.0 and Java Representation</li>
* </ul>
*
* <p>The default start instance is defined by {@link GregorianCalendar}'s use of the start of the epoch: i.e.,
* {@link java.util.Calendar#YEAR} = 1970,
* {@link java.util.Calendar#MONTH} = {@link java.util.Calendar#JANUARY},
* {@link java.util.Calendar#DATE} = 1, etc.
* This is important as there are variations in the Gregorian Calendar,
* e.g. leap years have different days in the month = {@link java.util.Calendar#FEBRUARY}
* so the result of {@link Duration#getDays()} can be influenced.</p>
*
* <p>Any remaining milliseconds after determining the day, hour, minute and second are discarded.</p>
*
* @param durationInMilliseconds Milliseconds of <code>Duration</code> to create.
*
* @return New <code>Duration</code> created with the specified <code>durationInMilliseconds</code>.
*
* @see <a href="http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration">
* XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration</a>
*/
public Duration newDurationDayTime(final long durationInMilliseconds) {
return newDuration(durationInMilliseconds);
}
/**
* <p>Create a <code>Duration</code> of type <code>xdt:dayTimeDuration</code> using the specified
* <code>day</code>, <code>hour</code>, <code>minute</code> and <code>second</code> as defined in
* <a href="http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration">
* XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration</a>.</p>
*
* <p>The datatype <code>xdt:dayTimeDuration</code> is a subtype of <code>xs:duration</code>
* whose lexical representation contains only day, hour, minute, and second components.
* This datatype resides in the namespace <code>http://www.w3.org/2003/11/xpath-datatypes</code>.</p>
*
* <p>The XML Schema specification states that values can be of an arbitrary size.
* Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values.
* An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits
* if implementation capacities are exceeded.</p>
*
* <p>A <code>null</code> value indicates that field isnot set.</p>
*
* @param isPositive Set to <code>false</code> to create a negative duration. When the length
* of the duration is zero, this parameter will be ignored.
* @param day Day of <code>Duration</code>.
* @param hour Hour of <code>Duration</code>.
* @param minute Minute of <code>Duration</code>.
* @param second Second of <code>Duration</code>.
*
* @return New <code>Duration</code> created with the specified <code>day</code>, <code>hour</code>, <code>minute</code>
* and <code>second</code>.
*
* @throws IllegalArgumentException If any values would create an invalid <code>Duration</code>.
* @throws UnsupportedOperationException If implementation cannot support requested values.
*/
public Duration newDurationDayTime(
final boolean isPositive,
final BigInteger day,
final BigInteger hour,
final BigInteger minute,
final BigInteger second) {
return newDuration(
isPositive,
null, // years
null, // months
day,
hour,
minute,
(second != null)? new BigDecimal(second):null
);
}
/**
* <p>Create a <code>Duration</code> of type <code>xdt:dayTimeDuration</code> using the specified
* <code>day</code>, <code>hour</code>, <code>minute</code> and <code>second</code> as defined in
* <a href="http://www.w3.org/TR/xpath-datamodel#dt-dayTimeDuration">
* XQuery 1.0 and XPath 2.0 Data Model, xdt:dayTimeDuration</a>.</p>
*
* <p>The datatype <code>xdt:dayTimeDuration</code> is a subtype of <code>xs:duration</code>
* whose lexical representation contains only day, hour, minute, and second components.
* This datatype resides in the namespace <code>http://www.w3.org/2003/11/xpath-datatypes</code>.</p>
*
* <p>A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field isnot set.</p>
*
* @param isPositive Set to <code>false</code> to create a negative duration. When the length
* of the duration is zero, this parameter will be ignored.
* @param day Day of <code>Duration</code>.
* @param hour Hour of <code>Duration</code>.
* @param minute Minute of <code>Duration</code>.
* @param second Second of <code>Duration</code>.
*
* @return New <code>Duration</code> created with the specified <code>day</code>, <code>hour</code>, <code>minute</code>
* and <code>second</code>.
*
* @throws IllegalArgumentException If any values would create an invalid <code>Duration</code>.
*/
public Duration newDurationDayTime(
final boolean isPositive,
final int day,
final int hour,
final int minute,
final int second) {
return newDurationDayTime(
isPositive,
BigInteger.valueOf((long) day),
BigInteger.valueOf((long) hour),
BigInteger.valueOf((long) minute),
BigInteger.valueOf((long) second)
);
}
/**
* <p>Create a <code>Duration</code> of type <code>xdt:yearMonthDuration</code> by parsing its <code>String</code> representation,
* "<em>PnYnM</em>", <a href="http://www.w3.org/TR/xpath-datamodel#dt-yearMonthDuration">
* XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration</a>.</p>
*
* <p>The datatype <code>xdt:yearMonthDuration</code> is a subtype of <code>xs:duration</code>
* whose lexical representation contains only year and month components.
* This datatype resides in the namespace {@link javax.xml.XMLConstants#W3C_XPATH_DATATYPE_NS_URI}.</p>
*
* <p>Both values are set and availabe from the created {@link Duration}</p>
*
* <p>The XML Schema specification states that values can be of an arbitrary size.
* Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values.
* An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits
* if implementation capacities are exceeded.</p>
*
* @param lexicalRepresentation Lexical representation of a duration.
*
* @return New <code>Duration</code> created using the specified <code>lexicalRepresentation</code>.
*
* @throws IllegalArgumentException If the <code>lexicalRepresentation</code> does not conform to the specification.
* @throws UnsupportedOperationException If implementation cannot support requested values.
* @throws NullPointerException If <code>lexicalRepresentation</code> is <code>null</code>.
*/
public Duration newDurationYearMonth(final String lexicalRepresentation) {
return newDuration(lexicalRepresentation);
}
/**
* <p>Create a <code>Duration</code> of type <code>xdt:yearMonthDuration</code> using the specified milliseconds as defined in
* <a href="http://www.w3.org/TR/xpath-datamodel#dt-yearMonthDuration">
* XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration</a>.</p>
*
* <p>The datatype <code>xdt:yearMonthDuration</code> is a subtype of <code>xs:duration</code>
* whose lexical representation contains only year and month components.
* This datatype resides in the namespace {@link javax.xml.XMLConstants#W3C_XPATH_DATATYPE_NS_URI}.</p>
*
* <p>Both values are set by computing their values from the specified milliseconds
* and are availabe using the <code>get</code> methods of the created {@link Duration}.
* The values conform to and are defined by:</p>
* <ul>
* <li>ISO 8601:2000(E) Section 5.5.3.2 Alternative format</li>
* <li><a href="http://www.w3.org/TR/xmlschema-2/#isoformats">
* W3C XML Schema 1.0 Part 2, Appendix D, ISO 8601 Date and Time Formats</a>
* </li>
* <li>{@link XMLGregorianCalendar} Date/Time Datatype Field Mapping Between XML Schema 1.0 and Java Representation</li>
* </ul>
*
* <p>The default start instance is defined by {@link GregorianCalendar}'s use of the start of the epoch: i.e.,
* {@link java.util.Calendar#YEAR} = 1970,
* {@link java.util.Calendar#MONTH} = {@link java.util.Calendar#JANUARY},
* {@link java.util.Calendar#DATE} = 1, etc.
* This is important as there are variations in the Gregorian Calendar,
* e.g. leap years have different days in the month = {@link java.util.Calendar#FEBRUARY}
* so the result of {@link Duration#getMonths()} can be influenced.</p>
*
* <p>Any remaining milliseconds after determining the year and month are discarded.</p>
*
* @param durationInMilliseconds Milliseconds of <code>Duration</code> to create.
*
* @return New <code>Duration</code> created using the specified <code>durationInMilliseconds</code>.
*/
public Duration newDurationYearMonth(final long durationInMilliseconds) {
return newDuration(durationInMilliseconds);
}
/**
* <p>Create a <code>Duration</code> of type <code>xdt:yearMonthDuration</code> using the specified
* <code>year</code> and <code>month</code> as defined in
* <a href="http://www.w3.org/TR/xpath-datamodel#dt-yearMonthyDuration">
* XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration</a>.</p>
*
* <p>The XML Schema specification states that values can be of an arbitrary size.
* Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values.
* An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits
* if implementation capacities are exceeded.</p>
*
* <p>A <code>null</code> value indicates that field isnot set.</p>
*
* @param isPositive Set to <code>false</code> to create a negative duration. When the length
* of the duration is zero, this parameter will be ignored.
* @param year Year of <code>Duration</code>.
* @param month Month of <code>Duration</code>.
*
* @return New <code>Duration</code> created using the specified <code>year</code> and <code>month</code>.
*
* @throws IllegalArgumentException If any values would create an invalid <code>Duration</code>.
* @throws UnsupportedOperationException If implementation cannot support requested values.
*/
public Duration newDurationYearMonth(
final boolean isPositive,
final BigInteger year,
final BigInteger month) {
return newDuration(
isPositive,
year,
month,
null, // days
null, // hours
null, // minutes
null // seconds
);
}
/**
* <p>Create a <code>Duration</code> of type <code>xdt:yearMonthDuration</code> using the specified
* <code>year</code> and <code>month</code> as defined in
* <a href="http://www.w3.org/TR/xpath-datamodel#dt-yearMonthyDuration">
* XQuery 1.0 and XPath 2.0 Data Model, xdt:yearMonthDuration</a>.</p>
*
* <p>A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field isnot set.</p>
*
* @param isPositive Set to <code>false</code> to create a negative duration. When the length
* of the duration is zero, this parameter will be ignored.
* @param year Year of <code>Duration</code>.
* @param month Month of <code>Duration</code>.
*
* @return New <code>Duration</code> created using the specified <code>year</code> and <code>month</code>.
*
* @throws IllegalArgumentException If any values would create an invalid <code>Duration</code>.
*/
public Duration newDurationYearMonth(
final boolean isPositive,
final int year,
final int month) {
return newDurationYearMonth(
isPositive,
BigInteger.valueOf((long) year),
BigInteger.valueOf((long) month));
}
/**
* <p>Create a new instance of an <code>XMLGregorianCalendar</code>.</p>
*
* <p>All date/time datatype fields set to {@link DatatypeConstants#FIELD_UNDEFINED} or null.</p>
*
* @return New <code>XMLGregorianCalendar</code> with all date/time datatype fields set to
* {@link DatatypeConstants#FIELD_UNDEFINED} or null.
*/
public abstract XMLGregorianCalendar newXMLGregorianCalendar();
/**
* <p>Create a new XMLGregorianCalendar by parsing the String as a lexical representation.</p>
*
* <p>Parsing the lexical string representation is defined in
* <a href="http://www.w3.org/TR/xmlschema-2/#dateTime-order">XML Schema 1.0 Part 2, Section 3.2.[7-14].1,
* <em>Lexical Representation</em>.</a></p>
*
* <p>The string representation may not have any leading and trailing whitespaces.</p>
*
* <p>The parsing is done field by field so that
* the following holds for any lexically correct String x:</p>
* <pre>
* newXMLGregorianCalendar(x).toXMLFormat().equals(x)
* </pre>
* <p>Except for the noted lexical/canonical representation mismatches
* listed in <a href="http://www.w3.org/2001/05/xmlschema-errata#e2-45">
* XML Schema 1.0 errata, Section 3.2.7.2</a>.</p>
*
* @param lexicalRepresentation Lexical representation of one the eight XML Schema date/time datatypes.
*
* @return <code>XMLGregorianCalendar</code> created from the <code>lexicalRepresentation</code>.
*
* @throws IllegalArgumentException If the <code>lexicalRepresentation</code> is not a valid <code>XMLGregorianCalendar</code>.
* @throws NullPointerException If <code>lexicalRepresentation</code> is <code>null</code>.
*/
public abstract XMLGregorianCalendar newXMLGregorianCalendar(final String lexicalRepresentation);
/**
* <p>Create an <code>XMLGregorianCalendar</code> from a {@link GregorianCalendar}.</p>
*
* <table border="2" rules="all" cellpadding="2">
* <thead>
* <tr>
* <th align="center" colspan="2">
* Field by Field Conversion from
* {@link GregorianCalendar} to an {@link XMLGregorianCalendar}
* </th>
* </tr>
* <tr>
* <th><code>java.util.GregorianCalendar</code> field</th>
* <th><code>javax.xml.datatype.XMLGregorianCalendar</code> field</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td><code>ERA == GregorianCalendar.BC ? -YEAR : YEAR</code></td>
* <td>{@link XMLGregorianCalendar#setYear(int year)}</td>
* </tr>
* <tr>
* <td><code>MONTH + 1</code></td>
* <td>{@link XMLGregorianCalendar#setMonth(int month)}</td>
* </tr>
* <tr>
* <td><code>DAY_OF_MONTH</code></td>
* <td>{@link XMLGregorianCalendar#setDay(int day)}</td>
* </tr>
* <tr>
* <td><code>HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND</code></td>
* <td>{@link XMLGregorianCalendar#setTime(int hour, int minute, int second, BigDecimal fractional)}</td>
* </tr>
* <tr>
* <td>
* <code>(ZONE_OFFSET + DST_OFFSET) / (60*1000)</code><br/>
* <em>(in minutes)</em>
* </td>
* <td>{@link XMLGregorianCalendar#setTimezone(int offset)}<sup><em>*</em></sup>
* </td>
* </tr>
* </tbody>
* </table>
* <p><em>*</em>conversion loss of information. It is not possible to represent
* a <code>java.util.GregorianCalendar</code> daylight savings timezone id in the
* XML Schema 1.0 date/time datatype representation.</p>
*
* <p>To compute the return value's <code>TimeZone</code> field,
* <ul>
* <li>when <code>this.getTimezone() != FIELD_UNDEFINED</code>,
* create a <code>java.util.TimeZone</code> with a custom timezone id
* using the <code>this.getTimezone()</code>.</li>
* <li>else use the <code>GregorianCalendar</code> default timezone value
* for the host is defined as specified by
* <code>java.util.TimeZone.getDefault()</code>.</li></p>
*
* @param cal <code>java.util.GregorianCalendar</code> used to create <code>XMLGregorianCalendar</code>
*
* @return <code>XMLGregorianCalendar</code> created from <code>java.util.GregorianCalendar</code>
*
* @throws NullPointerException If <code>cal</code> is <code>null</code>.
*/
public abstract XMLGregorianCalendar newXMLGregorianCalendar(final GregorianCalendar cal);
/**
* <p>Constructor allowing for complete value spaces allowed by
* W3C XML Schema 1.0 recommendation for xsd:dateTime and related
* builtin datatypes. Note that <code>year</code> parameter supports
* arbitrarily large numbers and fractionalSecond has infinite
* precision.</p>
*
* <p>A <code>null</code> value indicates that field isnot set.</p>
*
* @param year of <code>XMLGregorianCalendar</code> to be created.
* @param month of <code>XMLGregorianCalendar</code> to be created.
* @param day of <code>XMLGregorianCalendar</code> to be created.
* @param hour of <code>XMLGregorianCalendar</code> to be created.
* @param minute of <code>XMLGregorianCalendar</code> to be created.
* @param second of <code>XMLGregorianCalendar</code> to be created.
* @param fractionalSecond of <code>XMLGregorianCalendar</code> to be created.
* @param timezone of <code>XMLGregorianCalendar</code> to be created.
*
* @return <code>XMLGregorianCalendar</code> created from specified values.
*
* @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field
* as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar}
* or if the composite values constitute an invalid <code>XMLGregorianCalendar</code> instance
* as determined by {@link XMLGregorianCalendar#isValid()}.
*/
public abstract XMLGregorianCalendar newXMLGregorianCalendar(
final BigInteger year,
final int month,
final int day,
final int hour,
final int minute,
final int second,
final BigDecimal fractionalSecond,
final int timezone);
/**
* <p>Constructor of value spaces that a
* <code>java.util.GregorianCalendar</code> instance would need to convert to an
* <code>XMLGregorianCalendar</code> instance.</p>
*
* <p><code>XMLGregorianCalendar eon</code> and
* <code>fractionalSecond</code> are set to <code>null</code></p>
*
* <p>A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field isnot set.</p>
*
* @param year of <code>XMLGregorianCalendar</code> to be created.
* @param month of <code>XMLGregorianCalendar</code> to be created.
* @param day of <code>XMLGregorianCalendar</code> to be created.
* @param hour of <code>XMLGregorianCalendar</code> to be created.
* @param minute of <code>XMLGregorianCalendar</code> to be created.
* @param second of <code>XMLGregorianCalendar</code> to be created.
* @param millisecond of <code>XMLGregorianCalendar</code> to be created.
* @param timezone of <code>XMLGregorianCalendar</code> to be created.
*
* @return <code>XMLGregorianCalendar</code> created from specified values.
*
* @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field
* as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar}
* or if the composite values constitute an invalid <code>XMLGregorianCalendar</code> instance
* as determined by {@link XMLGregorianCalendar#isValid()}.
*/
public XMLGregorianCalendar newXMLGregorianCalendar(
final int year,
final int month,
final int day,
final int hour,
final int minute,
final int second,
final int millisecond,
final int timezone) {
// year may be undefined
BigInteger realYear = (year != DatatypeConstants.FIELD_UNDEFINED) ? BigInteger.valueOf((long) year) : null;
// millisecond may be undefined
// millisecond must be >= 0 millisecond <= 1000
BigDecimal realMillisecond = null; // undefined value
if (millisecond != DatatypeConstants.FIELD_UNDEFINED) {
if (millisecond < 0 || millisecond > 1000) {
throw new IllegalArgumentException(
"javax.xml.datatype.DatatypeFactory#newXMLGregorianCalendar("
+ "int year, int month, int day, int hour, int minute, int second, int millisecond, int timezone)"
+ "with invalid millisecond: " + millisecond
);
}
realMillisecond = BigDecimal.valueOf((long) millisecond).movePointLeft(3);
}
return newXMLGregorianCalendar(
realYear,
month,
day,
hour,
minute,
second,
realMillisecond,
timezone
);
}
/**
* <p>Create a Java representation of XML Schema builtin datatype <code>date</code> or <code>g*</code>.</p>
*
* <p>For example, an instance of <code>gYear</code> can be created invoking this factory
* with <code>month</code> and <code>day</code> parameters set to
* {@link DatatypeConstants#FIELD_UNDEFINED}.</p>
*
* <p>A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field isnot set.</p>
*
* @param year of <code>XMLGregorianCalendar</code> to be created.
* @param month of <code>XMLGregorianCalendar</code> to be created.
* @param day of <code>XMLGregorianCalendar</code> to be created.
* @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set.
*
* @return <code>XMLGregorianCalendar</code> created from parameter values.
*
* @see DatatypeConstants#FIELD_UNDEFINED
*
* @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field
* as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar}
* or if the composite values constitute an invalid <code>XMLGregorianCalendar</code> instance
* as determined by {@link XMLGregorianCalendar#isValid()}.
*/
public XMLGregorianCalendar newXMLGregorianCalendarDate(
final int year,
final int month,
final int day,
final int timezone) {
return newXMLGregorianCalendar(
year,
month,
day,
DatatypeConstants.FIELD_UNDEFINED, // hour
DatatypeConstants.FIELD_UNDEFINED, // minute
DatatypeConstants.FIELD_UNDEFINED, // second
DatatypeConstants.FIELD_UNDEFINED, // millisecond
timezone);
}
/**
* <p>Create a Java instance of XML Schema builtin datatype <code>time</code>.</p>
*
* <p>A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field isnot set.</p>
*
* @param hours number of hours
* @param minutes number of minutes
* @param seconds number of seconds
* @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set.
*
* @return <code>XMLGregorianCalendar</code> created from parameter values.
*
* @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field
* as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar}
* or if the composite values constitute an invalid <code>XMLGregorianCalendar</code> instance
* as determined by {@link XMLGregorianCalendar#isValid()}.
*
* @see DatatypeConstants#FIELD_UNDEFINED
*/
public XMLGregorianCalendar newXMLGregorianCalendarTime(
final int hours,
final int minutes,
final int seconds,
final int timezone) {
return newXMLGregorianCalendar(
DatatypeConstants.FIELD_UNDEFINED, // Year
DatatypeConstants.FIELD_UNDEFINED, // Month
DatatypeConstants.FIELD_UNDEFINED, // Day
hours,
minutes,
seconds,
DatatypeConstants.FIELD_UNDEFINED, //Millisecond
timezone);
}
/**
* <p>Create a Java instance of XML Schema builtin datatype time.</p>
*
* <p>A <code>null</code> value indicates that field isnot set.</p>
* <p>A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field isnot set.</p>
*
* @param hours number of hours
* @param minutes number of minutes
* @param seconds number of seconds
* @param fractionalSecond value of <code>null</code> indicates that this optional field is not set.
* @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set.
*
* @return <code>XMLGregorianCalendar</code> created from parameter values.
*
* @see DatatypeConstants#FIELD_UNDEFINED
*
* @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field
* as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar}
* or if the composite values constitute an invalid <code>XMLGregorianCalendar</code> instance
* as determined by {@link XMLGregorianCalendar#isValid()}.
*/
public XMLGregorianCalendar newXMLGregorianCalendarTime(
final int hours,
final int minutes,
final int seconds,
final BigDecimal fractionalSecond,
final int timezone) {
return newXMLGregorianCalendar(
null, // year
DatatypeConstants.FIELD_UNDEFINED, // month
DatatypeConstants.FIELD_UNDEFINED, // day
hours,
minutes,
seconds,
fractionalSecond,
timezone);
}
/**
* <p>Create a Java instance of XML Schema builtin datatype time.</p>
*
* <p>A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field isnot set.</p>
*
* @param hours number of hours
* @param minutes number of minutes
* @param seconds number of seconds
* @param milliseconds number of milliseconds
* @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set.
*
* @return <code>XMLGregorianCalendar</code> created from parameter values.
*
* @see DatatypeConstants#FIELD_UNDEFINED
*
* @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field
* as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar}
* or if the composite values constitute an invalid <code>XMLGregorianCalendar</code> instance
* as determined by {@link XMLGregorianCalendar#isValid()}.
*/
public XMLGregorianCalendar newXMLGregorianCalendarTime(
final int hours,
final int minutes,
final int seconds,
final int milliseconds,
final int timezone) {
// millisecond may be undefined
// millisecond must be >= 0 millisecond <= 1000
BigDecimal realMilliseconds = null; // undefined value
if (milliseconds != DatatypeConstants.FIELD_UNDEFINED) {
if (milliseconds < 0 || milliseconds > 1000) {
throw new IllegalArgumentException(
"javax.xml.datatype.DatatypeFactory#newXMLGregorianCalendarTime("
+ "int hours, int minutes, int seconds, int milliseconds, int timezone)"
+ "with invalid milliseconds: " + milliseconds
);
}
realMilliseconds = BigDecimal.valueOf((long) milliseconds).movePointLeft(3);
}
return newXMLGregorianCalendarTime(
hours,
minutes,
seconds,
realMilliseconds,
timezone
);
}
}

View File

@ -0,0 +1,974 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
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>
* @version $Revision$, $Date$
* @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;
/**
* <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
* <tt>int</tt>, <code>Duration</code> with values beyond the
* range of <tt>int</tt> 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 <tt>F</tt> is different from
* the sign of the most significant field,
* 1 (if <tt>F</tt> is negative) or -1 (otherwise)
* will be borrowed from the next bigger unit of <tt>F</tt>.</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
* A non-null valid <code>Duration</code> object.
*
* @return
* <code>true</code> if this duration is the same length as
* <code>duration</code>.
* <code>false</code> if <code>duration</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.
* @throws NullPointerException if parameter is null.
*
* @see #compare(Duration duration)
*/
public boolean equals(final Object duration) {
if (duration == null) {
throw new NullPointerException();
}
if (!(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,99 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
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

@ -1,77 +1,44 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999-2001, Sun Microsystems,
* Inc., http://www.sun.com. For more information on the Apache Software
* Foundation, please see <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.parsers; package javax.xml.parsers;
import java.io.InputStream;
import java.io.IOException;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.xml.sax.InputSource; import javax.xml.validation.Schema;
import org.xml.sax.SAXException;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.DOMImplementation; 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 * Defines the API to obtain DOM Document instances from an XML
* document. Using this class, an application programmer can obtain a * document. Using this class, an application programmer can obtain a
* {@link org.w3c.dom.Document} from XML.<p> * {@link Document} from XML.<p>
* *
* An instance of this class can be obtained from the * An instance of this class can be obtained from the
* {@link javax.xml.parsers.DocumentBuilderFactory#newDocumentBuilder() * {@link DocumentBuilderFactory#newDocumentBuilder()} method. Once
* DocumentBuilderFactory.newDocumentBuilder} method. Once
* an instance of this class is obtained, XML can be parsed from a * an instance of this class is obtained, XML can be parsed from a
* variety of input sources. These input sources are InputStreams, * variety of input sources. These input sources are InputStreams,
* Files, URLs, and SAX InputSources.<p> * Files, URLs, and SAX InputSources.<p>
@ -80,38 +47,59 @@ import org.w3c.dom.DOMImplementation;
* does not require that the implementor of the underlying DOM * does not require that the implementor of the underlying DOM
* implementation use a SAX parser to parse XML document into a * implementation use a SAX parser to parse XML document into a
* <code>Document</code>. It merely requires that the implementation * <code>Document</code>. It merely requires that the implementation
* communicate with the application using these existing APIs. <p> * communicate with the application using these existing APIs.
* *
* An implementation of <code>DocumentBuilder</code> is <em>NOT</em> * @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* guaranteed to behave as per the specification if it is used concurrently by * @version $Revision$, $Date$
* two or more threads. It is recommended to have one instance of the
* <code>DocumentBuilder</code> per thread or it is upto the application to
* make sure about the use of <code>DocumentBuilder</code> from more than one
* thread.
*
* @since JAXP 1.0
* @version 1.0
*/ */
public abstract class DocumentBuilder { public abstract class DocumentBuilder {
/** Protected constructor */
protected DocumentBuilder () { 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>
*
* @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 * Parse the content of the given <code>InputStream</code> as an XML
* document and return a new DOM {@link org.w3c.dom.Document} object. * 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 is InputStream containing the content to be parsed.
* @return <code>Document</code> result of parsing the
* <code>InputStream</code>
* @exception IOException If any IO errors occur. * @exception IOException If any IO errors occur.
* @exception SAXException If any parse errors occur. * @exception SAXException If any parse errors occur.
* @exception IllegalArgumentException If the InputStream is null
* @see org.xml.sax.DocumentHandler * @see org.xml.sax.DocumentHandler
*/ */
public Document parse(InputStream is) public Document parse(InputStream is)
throws SAXException, IOException throws SAXException, IOException {
{
if (is == null) { if (is == null) {
throw new IllegalArgumentException("InputStream cannot be null"); throw new IllegalArgumentException("InputStream cannot be null");
} }
@ -121,45 +109,45 @@ public abstract class DocumentBuilder {
} }
/** /**
* Parse the content of the given <code>InputStream</code> as an XML * Parse the content of the given <code>InputStream</code> as an
* document and return a new DOM {@link org.w3c.dom.Document} object. * 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 is InputStream containing the content to be parsed.
* @param systemId Provide a base for resolving relative URIs. * @param systemId Provide a base for resolving relative URIs.
* @return A new DOM Document object.
* @exception IOException If any IO errors occur. * @exception IOException If any IO errors occur.
* @exception SAXException If any parse errors occur. * @exception SAXException If any parse errors occur.
* @exception IllegalArgumentException If the InputStream is null.
* @see org.xml.sax.DocumentHandler * @see org.xml.sax.DocumentHandler
* @return A new DOM Document object.
*/ */
public Document parse(InputStream is, String systemId) public Document parse(InputStream is, String systemId)
throws SAXException, IOException throws SAXException, IOException {
{
if (is == null) { if (is == null) {
throw new IllegalArgumentException("InputStream cannot be null"); throw new IllegalArgumentException("InputStream cannot be null");
} }
InputSource in = new InputSource(is); InputSource in = new InputSource(is);
in.setSystemId(systemId); in.setSystemId(systemId);
return parse(in); return parse(in);
} }
/** /**
* Parse the content of the given URI as an XML document * Parse the content of the given URI as an XML document
* and return a new DOM {@link org.w3c.dom.Document} object. * 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. * @param uri The location of the content to be parsed.
* @return A new DOM Document object.
* @exception IOException If any IO errors occur. * @exception IOException If any IO errors occur.
* @exception SAXException If any parse errors occur. * @exception SAXException If any parse errors occur.
* @exception IllegalArgumentException If the URI is null.
* @see org.xml.sax.DocumentHandler * @see org.xml.sax.DocumentHandler
* @return A new DOM Document object.
*/ */
public Document parse(String uri) public Document parse(String uri)
throws SAXException, IOException throws SAXException, IOException {
{
if (uri == null) { if (uri == null) {
throw new IllegalArgumentException("URI cannot be null"); throw new IllegalArgumentException("URI cannot be null");
} }
@ -170,39 +158,39 @@ public abstract class DocumentBuilder {
/** /**
* Parse the content of the given file as an XML document * Parse the content of the given file as an XML document
* and return a new DOM {@link org.w3c.dom.Document} object. * 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. * @param f The file containing the XML to parse.
* @exception IOException If any IO errors occur. * @exception IOException If any IO errors occur.
* @exception SAXException If any parse errors occur. * @exception SAXException If any parse errors occur.
* @exception IllegalArgumentException If the file is null.
* @see org.xml.sax.DocumentHandler * @see org.xml.sax.DocumentHandler
* @return A new DOM Document object. * @return A new DOM Document object.
*/ */
public Document parse(File f) public Document parse(File f) throws SAXException, IOException {
throws SAXException, IOException
{
if (f == null) { if (f == null) {
throw new IllegalArgumentException("File cannot be null"); throw new IllegalArgumentException("File cannot be null");
} }
String uri = "file:" + f.getAbsolutePath(); String uri = "file:" + f.getAbsolutePath();
if (File.separatorChar == '\\') { if (File.separatorChar == '\\') {
uri = uri.replace('\\', '/'); uri = uri.replace('\\', '/');
} }
InputSource in = new InputSource(uri); InputSource in = new InputSource(uri);
return parse(in); return parse(in);
} }
/** /**
* Parse the content of the given input source as an XML document * Parse the content of the given input source as an XML document
* and return a new DOM {@link org.w3c.dom.Document} object. * 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. * @param is InputSource containing the content to be parsed.
* @exception IOException If any IO errors occur. * @exception IOException If any IO errors occur.
* @exception SAXException If any parse errors occur. * @exception SAXException If any parse errors occur.
* @exception IllegalArgumentException If the InputSource is null.
* @see org.xml.sax.DocumentHandler * @see org.xml.sax.DocumentHandler
* @return A new DOM Document object. * @return A new DOM Document object.
*/ */
@ -232,7 +220,7 @@ public abstract class DocumentBuilder {
public abstract boolean isValidating(); public abstract boolean isValidating();
/** /**
* Specify the {@link org.xml.sax.EntityResolver} to be used to resolve * Specify the {@link EntityResolver} to be used to resolve
* entities present in the XML document to be parsed. Setting * entities present in the XML document to be parsed. Setting
* this to <code>null</code> will result in the underlying * this to <code>null</code> will result in the underlying
* implementation using it's own default implementation and * implementation using it's own default implementation and
@ -242,28 +230,22 @@ public abstract class DocumentBuilder {
* present in the XML document to be parsed. * present in the XML document to be parsed.
*/ */
public abstract void setEntityResolver(org.xml.sax.EntityResolver er); public abstract void setEntityResolver(EntityResolver er);
/** /**
* Specify the {@link org.xml.sax.ErrorHandler} to be used to report * Specify the {@link ErrorHandler} to be used by the parser.
* errors present in the XML document to be parsed. Setting * Setting this to <code>null</code> will result in the underlying
* this to <code>null</code> will result in the underlying
* implementation using it's own default implementation and * implementation using it's own default implementation and
* behavior. * behavior.
* *
* @param eh The <code>ErrorHandler</code> to be used to report errors * @param eh The <code>ErrorHandler</code> to be used by the parser.
* present in the XML document to be parsed.
*/ */
public abstract void setErrorHandler(org.xml.sax.ErrorHandler eh); public abstract void setErrorHandler(ErrorHandler eh);
/** /**
* Obtain a new instance of a DOM {@link org.w3c.dom.Document} object * Obtain a new instance of a DOM {@link Document} object
* to build a DOM tree with. An alternative way to create a DOM * to build a DOM tree with.
* Document object is to use the
* {@link #getDOMImplementation() getDOMImplementation}
* method to get a DOM Level 2 DOMImplementation object and then use
* DOM Level 2 methods on that object to create a DOM Document object.
* *
* @return A new instance of a DOM Document object. * @return A new instance of a DOM Document object.
*/ */
@ -271,10 +253,73 @@ public abstract class DocumentBuilder {
public abstract Document newDocument(); public abstract Document newDocument();
/** /**
* Obtain an instance of a {@link org.w3c.dom.DOMImplementation} object. * Obtain an instance of a {@link DOMImplementation} object.
* *
* @return A new instance of a <code>DOMImplementation</code>. * @return A new instance of a <code>DOMImplementation</code>.
*/ */
public abstract DOMImplementation getDOMImplementation(); 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
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @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
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @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

@ -1,78 +1,38 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999-2001, Sun Microsystems,
* Inc., http://www.sun.com. For more information on the Apache Software
* Foundation, please see <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.parsers; package javax.xml.parsers;
import javax.xml.validation.Schema;
/** /**
* Defines a factory API that enables applications to obtain a * Defines a factory API that enables applications to obtain a
* parser that produces DOM object trees from XML documents. * parser that produces DOM object trees from XML documents.
* *
* An implementation of the <code>DocumentBuilderFactory</code> class is * @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
* <em>NOT</em> guaranteed to be thread safe. It is up to the user application * @version $Revision$, $Date$
* to make sure about the use of the <code>DocumentBuilderFactory</code> from
* more than one thread. Alternatively the application can have one instance
* of the <code>DocumentBuilderFactory</code> per thread.
* An application can use the same instance of the factory to obtain one or
* more instances of the <code>DocumentBuilder</code> provided the instance
* of the factory isn't being used in more than one thread at a time.
*
* @since JAXP 1.0
* @version 1.0
*/ */
public abstract class DocumentBuilderFactory { 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 validating = false;
private boolean namespaceAware = false; private boolean namespaceAware = false;
private boolean whitespace = false; private boolean whitespace = false;
@ -80,8 +40,9 @@ public abstract class DocumentBuilderFactory {
private boolean ignoreComments = false; private boolean ignoreComments = false;
private boolean coalescing = false; private boolean coalescing = false;
protected DocumentBuilderFactory () { private boolean canonicalState = false;
protected DocumentBuilderFactory () {
} }
/** /**
@ -102,6 +63,12 @@ public abstract class DocumentBuilderFactory {
* </code> format and contains the fully qualified name of the * </code> format and contains the fully qualified name of the
* implementation class with the key being the system property defined * implementation class with the key being the system property defined
* above. * 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>
* <li> * <li>
* Use the Services API (as detailed in the JAR specification), if * Use the Services API (as detailed in the JAR specification), if
@ -118,26 +85,37 @@ public abstract class DocumentBuilderFactory {
* Once an application has obtained a reference to a * Once an application has obtained a reference to a
* <code>DocumentBuilderFactory</code> it can use the factory to * <code>DocumentBuilderFactory</code> it can use the factory to
* configure and obtain parser instances. * 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 <tt>System.err</tt> 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>
* *
* @exception FactoryConfigurationError if the implementation is not * @exception FactoryConfigurationError if the implementation is not
* available or cannot be instantiated. * available or cannot be instantiated.
*/ */
public static DocumentBuilderFactory newInstance() {
public static DocumentBuilderFactory newInstance()
throws FactoryConfigurationError
{
try { try {
return (DocumentBuilderFactory) FactoryFinder.find( return (DocumentBuilderFactory) FactoryFinder.find(
/* The default property name according to the JAXP spec */ /* The default property name according to the JAXP spec */
"javax.xml.parsers.DocumentBuilderFactory", "javax.xml.parsers.DocumentBuilderFactory",
/* The fallback implementation class name */ /* The fallback implementation class name */
null); "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
} catch (FactoryFinder.ConfigurationError e) { } catch (FactoryFinder.ConfigurationError e) {
throw new FactoryConfigurationError(e.getException(), throw new FactoryConfigurationError(e.getException(),
e.getMessage()); e.getMessage());
} }
} }
/** /**
* Creates a new instance of a {@link javax.xml.parsers.DocumentBuilder} * Creates a new instance of a {@link javax.xml.parsers.DocumentBuilder}
* using the currently configured parameters. * using the currently configured parameters.
@ -168,7 +146,24 @@ public abstract class DocumentBuilderFactory {
* Specifies that the parser produced by this code will * Specifies that the parser produced by this code will
* validate documents as they are parsed. By default the value of this * validate documents as they are parsed. By default the value of this
* is set to <code>false</code>. * 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.
* See <a href="#validationCompatibility">here</a> for more details.)
* </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 <tt>false</tt>, 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 * @param validating true if the parser produced will validate documents
* as they are parsed; false otherwise. * as they are parsed; false otherwise.
*/ */
@ -210,9 +205,11 @@ public abstract class DocumentBuilderFactory {
} }
/** /**
* Specifies that the parser produced by this code will * <p>Specifies that the parser produced by this code will
* ignore comments. By default the value of this is set to <code>false * ignore comments. By default the value of this is set to <code>false
* </code> * </code>.</p>
*
* @param ignoreComments <code>boolean</code> value to ignore comments during processing
*/ */
public void setIgnoringComments(boolean ignoreComments) { public void setIgnoringComments(boolean ignoreComments) {
@ -330,4 +327,233 @@ public abstract class DocumentBuilderFactory {
*/ */
public abstract Object getAttribute(String name) public abstract Object getAttribute(String name)
throws IllegalArgumentException; 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.
* 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>
*
* <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.
*
*
* @throws UnsupportedOperationException
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @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>
* 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.w3c.dom.DOMErrorHandler}
* (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.w3c.dom.DOMErrorHandler}
* 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 <tt>false</tt>.
*
* <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.
*
* @param schema <code>Schema</code> to use or <code>null</code> to remove a schema.
*
* @throws UnsupportedOperationException
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @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
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @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
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @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

@ -1,58 +1,21 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999-2001, Sun Microsystems,
* Inc., http://www.sun.com. For more information on the Apache Software
* Foundation, please see <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.parsers; package javax.xml.parsers;
/** /**
@ -61,12 +24,15 @@ package javax.xml.parsers;
* parser factory specified in the system properties cannot be found * parser factory specified in the system properties cannot be found
* or instantiated. * or instantiated.
* *
* @since JAXP 1.0 * @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version 1.0 * @version $Revision$, $Date$
*/ */
public class FactoryConfigurationError extends Error { public class FactoryConfigurationError extends Error {
/**
*<code>Exception</code> that represents the error.
*/
private Exception exception; private Exception exception;
/** /**
@ -74,10 +40,10 @@ public class FactoryConfigurationError extends Error {
* detail mesage. * detail mesage.
*/ */
public FactoryConfigurationError() { public FactoryConfigurationError() {
super(); super();
this.exception = null; this.exception = null;
} }
/** /**
* Create a new <code>FactoryConfigurationError</code> with * Create a new <code>FactoryConfigurationError</code> with
@ -112,7 +78,6 @@ public class FactoryConfigurationError extends Error {
* @param e The exception to be encapsulated in a * @param e The exception to be encapsulated in a
* FactoryConfigurationError * FactoryConfigurationError
* @param msg The detail message. * @param msg The detail message.
* @param e The exception to be wrapped in a FactoryConfigurationError
*/ */
public FactoryConfigurationError(Exception e, String msg) { public FactoryConfigurationError(Exception e, String msg) {
@ -152,10 +117,3 @@ public class FactoryConfigurationError extends Error {
return exception; return exception;
} }
} }

View File

@ -1,136 +1,116 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999-2001, Sun Microsystems,
* Inc., http://www.sun.com. For more information on the Apache Software
* Foundation, please see <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.parsers; package javax.xml.parsers;
import java.io.InputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.util.Properties; import java.util.Properties;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URL;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
/** /**
* This class is duplicated for each JAXP subpackage so keep it in sync. * This class is duplicated for each JAXP subpackage so keep it in
* It is package private and therefore is not exposed as part of the JAXP * sync. It is package private.
* API.
* *
* This code is designed to implement the JAXP 1.1 spec pluggability * This code is designed to implement the JAXP 1.1 spec pluggability
* feature and is designed to both compile and run on JDK version 1.1 and * feature and is designed to run on JDK version 1.1 and later including
* later. The code also runs both as part of an unbundled jar file and * JVMs that perform early linking like the Microsoft JVM in IE 5. Note
* when bundled as part of the JDK. * however that it must be compiled on a JDK version 1.2 or later system
* since it calls Thread#getContextClassLoader(). The code also runs both
* as part of an unbundled jar file and when bundled as part of the JDK.
*/ */
class FactoryFinder { class FactoryFinder {
/** Set to true for debugging */ /** Temp debug code - this will be removed after we test everything
private static final boolean debug = false; */
private static boolean debug = false;
static Properties cacheProps= new Properties();
static SecuritySupport ss = new SecuritySupport() ;
static boolean firstTime = true;
private static void debugPrintln(String msg) { // 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) { if (debug) {
System.err.println("JAXP: " + msg); System.err.println("JAXP: " + msg);
} }
} }
/** /**
* Figure out which ClassLoader to use. For JDK 1.2 and later use * Create an instance of a class using the specified ClassLoader and
* the context ClassLoader. * optionally fall back to the current ClassLoader if not found.
*/ *
private static ClassLoader findClassLoader() * @param className Name of the concrete class corresponding to the
throws ConfigurationError * service provider
{ *
Method m = null; * @param cl ClassLoader to use to load the class, null means to use
* the bootstrap ClassLoader
try { *
m = Thread.class.getMethod("getContextClassLoader", null); * @param doFallback true if the current ClassLoader should be tried as
} catch (NoSuchMethodException e) { * a fallback if the class is not found using cl
// Assume that we are running JDK 1.1, use the current ClassLoader
debugPrintln("assuming JDK 1.1");
return FactoryFinder.class.getClassLoader();
}
try {
return (ClassLoader) m.invoke(Thread.currentThread(), null);
} catch (IllegalAccessException e) {
// assert(false)
throw new ConfigurationError("Unexpected IllegalAccessException",
e);
} catch (InvocationTargetException e) {
// assert(e.getTargetException() instanceof SecurityException)
throw new ConfigurationError("Unexpected InvocationTargetException",
e);
}
}
/**
* Create an instance of a class using the specified ClassLoader
*/ */
private static Object newInstance(String className, private static Object newInstance(String className, ClassLoader cl,
ClassLoader classLoader) boolean doFallback)
throws ConfigurationError throws ConfigurationError
{ {
// assert(className != null);
try { try {
Class spiClass; Class providerClass;
if (classLoader == null) { if (cl == null) {
spiClass = Class.forName(className); // If classloader is null Use the bootstrap ClassLoader.
// Thus Class.forName(String) will use the current
// ClassLoader which will be the bootstrap ClassLoader.
providerClass = Class.forName(className);
} else { } else {
spiClass = classLoader.loadClass(className); try {
providerClass = cl.loadClass(className);
} catch (ClassNotFoundException x) {
if (doFallback) {
// Fall back to current classloader
cl = FactoryFinder.class.getClassLoader();
providerClass = cl.loadClass(className);
} else {
throw x;
}
}
} }
return spiClass.newInstance();
Object instance = providerClass.newInstance();
dPrint("created new instance of " + providerClass +
" using ClassLoader: " + cl);
return instance;
} catch (ClassNotFoundException x) { } catch (ClassNotFoundException x) {
throw new ConfigurationError( throw new ConfigurationError(
"Provider " + className + " not found", x); "Provider " + className + " not found", x);
@ -140,7 +120,7 @@ class FactoryFinder {
x); x);
} }
} }
/** /**
* Finds the implementation Class object in the specified order. Main * Finds the implementation Class object in the specified order. Main
* entry point. * entry point.
@ -151,101 +131,165 @@ class FactoryFinder {
* @param fallbackClassName Implementation class name, if nothing else * @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback. * is found. Use null to mean no fallback.
* *
* @exception FactoryFinder.ConfigurationError
*
* Package private so this code can be shared. * Package private so this code can be shared.
*/ */
static Object find(String factoryId, String fallbackClassName) static Object find(String factoryId, String fallbackClassName)
throws ConfigurationError throws ConfigurationError
{ {
debugPrintln("debug is on");
ClassLoader classLoader = findClassLoader(); // Figure out which ClassLoader to use for loading the provider
// class. If there is a Context ClassLoader then use it.
// Use the system property first
try { ClassLoader classLoader = ss.getContextClassLoader();
String systemProp =
System.getProperty( factoryId ); if (classLoader == null) {
if( systemProp!=null) { // if we have no Context ClassLoader
debugPrintln("found system property " + systemProp); // so use the current ClassLoader
return newInstance(systemProp, classLoader); classLoader = FactoryFinder.class.getClassLoader();
}
} catch (SecurityException se) {
} }
// try to read from $java.home/lib/xml.properties dPrint("find factoryId =" + factoryId);
// Use the system property first
try { try {
String javah=System.getProperty( "java.home" ); String systemProp = ss.getSystemProperty(factoryId);
if( systemProp!=null) {
dPrint("found system property, value=" + systemProp);
return newInstance(systemProp, classLoader, true );
}
} catch (SecurityException se) {
//if first option fails due to any reason we should try next option in the
//look up algorithm.
}
// try to read from $java.home/lib/jaxp.properties
try {
String javah = ss.getSystemProperty("java.home");
String configFile = javah + File.separator + String configFile = javah + File.separator +
"lib" + File.separator + "jaxp.properties"; "lib" + File.separator + "jaxp.properties";
File f=new File( configFile ); String factoryClassName = null;
if( f.exists()) { if(firstTime){
Properties props=new Properties(); synchronized(cacheProps){
props.load( new FileInputStream(f)); if(firstTime){
String factoryClassName = props.getProperty(factoryId); File f=new File( configFile );
debugPrintln("found java.home property " + factoryClassName); firstTime = false;
return newInstance(factoryClassName, classLoader); if(ss.doesFileExist(f)){
dPrint("Read properties file "+f);
//cacheProps.load( new FileInputStream(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, classLoader, true);
} }
} catch(Exception ex ) { } catch(Exception ex ) {
if( debug ) ex.printStackTrace(); if( debug ) ex.printStackTrace();
} }
String serviceId = "META-INF/services/" + factoryId; // Try Jar Service Provider Mechanism
// try to find services in CLASSPATH Object provider = findJarServiceProvider(factoryId);
try { if (provider != null) {
InputStream is=null; return provider;
if (classLoader == null) {
is=ClassLoader.getSystemResourceAsStream( serviceId );
} else {
is=classLoader.getResourceAsStream( serviceId );
}
if( is!=null ) {
debugPrintln("found " + serviceId);
// Read the service provider name in UTF-8 as specified in
// the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
// doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
// VJ++ this is apparently ASCII, which is a subset of
// UTF-8... and since the strings we'll be reading here are
// also primarily limited to the 7-bit ASCII range (at
// least, in English versions), this should work well
// enough to keep us on the air until we're ready to
// officially decommit from VJ++. [Edited comment from
// jkesselm]
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
} catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is));
}
String factoryClassName = rd.readLine();
rd.close();
if (factoryClassName != null &&
! "".equals(factoryClassName)) {
debugPrintln("loaded from services: " + factoryClassName);
return newInstance(factoryClassName, classLoader);
}
}
} catch( Exception ex ) {
if( debug ) ex.printStackTrace();
} }
if (fallbackClassName == null) { if (fallbackClassName == null) {
throw new ConfigurationError( throw new ConfigurationError(
"Provider for " + factoryId + " cannot be found", null); "Provider for " + factoryId + " cannot be found", null);
} }
debugPrintln("loaded from fallback value: " + fallbackClassName); dPrint("loaded from fallback value: " + fallbackClassName);
return newInstance(fallbackClassName, classLoader); return newInstance(fallbackClassName, classLoader, 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;
}
dPrint("found jar resource=" + serviceId +
" using ClassLoader: " + cl);
// Read the service provider name in UTF-8 as specified in
// the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
// doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
// VJ++ this is apparently ASCII, which is a subset of
// UTF-8... and since the strings we'll be reading here are
// also primarily limited to the 7-bit ASCII range (at
// least, in English versions), this should work well
// enough to keep us on the air until we're ready to
// officially decommit from VJ++. [Edited comment from
// jkesselm]
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
} 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 { static class ConfigurationError extends Error {
@ -264,4 +308,5 @@ class FactoryFinder {
return exception; return exception;
} }
} }
} }

View File

@ -1,65 +1,29 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999-2001, Sun Microsystems,
* Inc., http://www.sun.com. For more information on the Apache Software
* Foundation, please see <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.parsers; package javax.xml.parsers;
/** /**
* Indicates a serious configuration error. * Indicates a serious configuration error.
* *
* @since JAXP 1.0 * @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version 1.0 * @version $Revision$, $Date$
*/ */
public class ParserConfigurationException extends Exception { public class ParserConfigurationException extends Exception {

View File

@ -1,73 +1,37 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999-2001, Sun Microsystems,
* Inc., http://www.sun.com. For more information on the Apache Software
* Foundation, please see <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.parsers; package javax.xml.parsers;
import java.io.InputStream;
import java.io.IOException;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.validation.Schema;
import org.xml.sax.Parser;
import org.xml.sax.XMLReader;
import org.xml.sax.HandlerBase; import org.xml.sax.HandlerBase;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
import org.xml.sax.Parser;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
/** /**
@ -84,83 +48,115 @@ import org.xml.sax.SAXNotSupportedException;
* a variety of input sources. These input sources are InputStreams, * a variety of input sources. These input sources are InputStreams,
* Files, URLs, and SAX InputSources.<p> * 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 * As the content is parsed by the underlying parser, methods of the
* given {@link org.xml.sax.HandlerBase} or the * given {@link org.xml.sax.HandlerBase} or the
* {@link org.xml.sax.helpers.DefaultHandler} are called.<p> * {@link org.xml.sax.helpers.DefaultHandler} are called.<p>
* *
* Implementors of this class which wrap an underlying implementation * Implementors of this class which wrap an underlaying implementation
* can consider using the {@link org.xml.sax.helpers.ParserAdapter} * can consider using the {@link org.xml.sax.helpers.ParserAdapter}
* class to initially adapt their SAX1 impelemntation to work under * class to initially adapt their SAX1 impelemntation to work under
* this revised class.<p> * this revised class.
* *
* An implementation of <code>SAXParser</code> is <em>NOT</em> * @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* guaranteed to behave as per the specification if it is used concurrently by * @version $Revision$, $Date$
* two or more threads. It is recommended to have one instance of the
* <code>SAXParser</code> per thread or it is upto the application to
* make sure about the use of <code>SAXParser</code> from more than one
* thread.
*
* @since JAXP 1.0
* @version 1.0
*/ */
public abstract class SAXParser { public abstract class SAXParser {
/**
* <p>Protected constructor to prevent instaniation.
* Use {@link javax.xml.parsers.SAXParserFactory#newSAXParser()}.</p>
*/
protected SAXParser () { 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>
*
* @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() + "\""
);
}
/** /**
* Parse the content of the given {@link java.io.InputStream} * <p>Parse the content of the given {@link java.io.InputStream}
* instance as XML using the specified {@link org.xml.sax.HandlerBase}. * instance as XML using the specified {@link org.xml.sax.HandlerBase}.
* <i> Use of the DefaultHandler version of this method is recommended as * <i> Use of the DefaultHandler version of this method is recommended as
* the HandlerBase class has been deprecated in SAX 2.0</i> * the HandlerBase class has been deprecated in SAX 2.0</i>.</p>
* *
* @param is InputStream containing the content to be parsed. * @param is InputStream containing the content to be parsed.
* @param hb The SAX HandlerBase to use. * @param hb The SAX HandlerBase to use.
* @exception IOException If any IO errors occur. *
* @exception IllegalArgumentException If the given InputStream is null. * @throws IllegalArgumentException If the given InputStream is null.
* @exception SAXException If the underlying parser throws a * @throws SAXException If parse produces a SAX error.
* SAXException while parsing. * @throws IOException If an IO error occurs interacting with the
* <code>InputStream</code>.
*
* @see org.xml.sax.DocumentHandler * @see org.xml.sax.DocumentHandler
*/ */
public void parse(InputStream is, HandlerBase hb) public void parse(InputStream is, HandlerBase hb)
throws SAXException, IOException throws SAXException, IOException {
{
if (is == null) { if (is == null) {
throw new IllegalArgumentException("InputStream cannot be null"); throw new IllegalArgumentException("InputStream cannot be null");
} }
InputSource input = new InputSource(is); InputSource input = new InputSource(is);
this.parse(input, hb); this.parse(input, hb);
} }
/** /**
* Parse the content of the given {@link java.io.InputStream} * <p>Parse the content of the given {@link java.io.InputStream}
* instance as XML using the specified {@link org.xml.sax.HandlerBase}. * instance as XML using the specified {@link org.xml.sax.HandlerBase}.
* <i> Use of the DefaultHandler version of this method is recommended as * <i> Use of the DefaultHandler version of this method is recommended as
* the HandlerBase class has been deprecated in SAX 2.0</i> * the HandlerBase class has been deprecated in SAX 2.0</i>.</p>
* *
* @param is InputStream containing the content to be parsed. * @param is InputStream containing the content to be parsed.
* @param hb The SAX HandlerBase to use. * @param hb The SAX HandlerBase to use.
* @param systemId The systemId which is needed for resolving relative URIs. * @param systemId The systemId which is needed for resolving relative URIs.
* @exception IOException If any IO errors occur. *
* @exception IllegalArgumentException If the given InputStream is null. * @throws IllegalArgumentException If the given <code>InputStream</code> is
* @exception SAXException If the underlying parser throws a * <code>null</code>.
* SAXException while parsing. * @throws IOException If any IO error occurs interacting with the
* @see org.xml.sax.DocumentHandler * <code>InputStream</code>.
* version of this method instead. * @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler version of this method instead.
*/ */
public void parse(
public void parse(InputStream is, HandlerBase hb, String systemId) InputStream is,
throws SAXException, IOException HandlerBase hb,
{ String systemId)
throws SAXException, IOException {
if (is == null) { if (is == null) {
throw new IllegalArgumentException("InputStream cannot be null"); throw new IllegalArgumentException("InputStream cannot be null");
} }
InputSource input = new InputSource(is); InputSource input = new InputSource(is);
input.setSystemId(systemId); input.setSystemId(systemId);
this.parse(input, hb); this.parse(input, hb);
@ -173,20 +169,19 @@ public abstract class SAXParser {
* *
* @param is InputStream containing the content to be parsed. * @param is InputStream containing the content to be parsed.
* @param dh The SAX DefaultHandler to use. * @param dh The SAX DefaultHandler to use.
* @exception IOException If any IO errors occur. *
* @exception IllegalArgumentException If the given InputStream is null. * @throws IllegalArgumentException If the given InputStream is null.
* @exception SAXException If the underlying parser throws a * @throws IOException If any IO errors occur.
* SAXException while parsing. * @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler * @see org.xml.sax.DocumentHandler
*/ */
public void parse(InputStream is, DefaultHandler dh) public void parse(InputStream is, DefaultHandler dh)
throws SAXException, IOException throws SAXException, IOException {
{
if (is == null) { if (is == null) {
throw new IllegalArgumentException("InputStream cannot be null"); throw new IllegalArgumentException("InputStream cannot be null");
} }
InputSource input = new InputSource(is); InputSource input = new InputSource(is);
this.parse(input, dh); this.parse(input, dh);
} }
@ -199,21 +194,22 @@ public abstract class SAXParser {
* @param is InputStream containing the content to be parsed. * @param is InputStream containing the content to be parsed.
* @param dh The SAX DefaultHandler to use. * @param dh The SAX DefaultHandler to use.
* @param systemId The systemId which is needed for resolving relative URIs. * @param systemId The systemId which is needed for resolving relative URIs.
* @exception IOException If any IO errors occur. *
* @exception IllegalArgumentException If the given InputStream is null. * @throws IllegalArgumentException If the given InputStream is null.
* @exception SAXException If the underlying parser throws a * @throws IOException If any IO errors occur.
* SAXException while parsing. * @throws SAXException If any SAX errors occur during processing.
* @see org.xml.sax.DocumentHandler *
* version of this method instead. * @see org.xml.sax.DocumentHandler version of this method instead.
*/ */
public void parse(
public void parse(InputStream is, DefaultHandler dh, String systemId) InputStream is,
throws SAXException, IOException DefaultHandler dh,
{ String systemId)
throws SAXException, IOException {
if (is == null) { if (is == null) {
throw new IllegalArgumentException("InputStream cannot be null"); throw new IllegalArgumentException("InputStream cannot be null");
} }
InputSource input = new InputSource(is); InputSource input = new InputSource(is);
input.setSystemId(systemId); input.setSystemId(systemId);
this.parse(input, dh); this.parse(input, dh);
@ -228,20 +224,19 @@ public abstract class SAXParser {
* *
* @param uri The location of the content to be parsed. * @param uri The location of the content to be parsed.
* @param hb The SAX HandlerBase to use. * @param hb The SAX HandlerBase to use.
* @exception IOException If any IO errors occur. *
* @exception IllegalArgumentException If the uri is null. * @throws IllegalArgumentException If the uri is null.
* @exception SAXException If the underlying parser throws a * @throws IOException If any IO errors occur.
* SAXException while parsing. * @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler * @see org.xml.sax.DocumentHandler
*/ */
public void parse(String uri, HandlerBase hb) public void parse(String uri, HandlerBase hb)
throws SAXException, IOException throws SAXException, IOException {
{
if (uri == null) { if (uri == null) {
throw new IllegalArgumentException("uri cannot be null"); throw new IllegalArgumentException("uri cannot be null");
} }
InputSource input = new InputSource(uri); InputSource input = new InputSource(uri);
this.parse(input, hb); this.parse(input, hb);
} }
@ -253,20 +248,19 @@ public abstract class SAXParser {
* *
* @param uri The location of the content to be parsed. * @param uri The location of the content to be parsed.
* @param dh The SAX DefaultHandler to use. * @param dh The SAX DefaultHandler to use.
* @exception IOException If any IO errors occur. *
* @exception IllegalArgumentException If the uri is null. * @throws IllegalArgumentException If the uri is null.
* @exception SAXException If the underlying parser throws a * @throws IOException If any IO errors occur.
* SAXException while parsing. * @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler * @see org.xml.sax.DocumentHandler
*/ */
public void parse(String uri, DefaultHandler dh) public void parse(String uri, DefaultHandler dh)
throws SAXException, IOException throws SAXException, IOException {
{
if (uri == null) { if (uri == null) {
throw new IllegalArgumentException("uri cannot be null"); throw new IllegalArgumentException("uri cannot be null");
} }
InputSource input = new InputSource(uri); InputSource input = new InputSource(uri);
this.parse(input, dh); this.parse(input, dh);
} }
@ -279,20 +273,19 @@ public abstract class SAXParser {
* *
* @param f The file containing the XML to parse * @param f The file containing the XML to parse
* @param hb The SAX HandlerBase to use. * @param hb The SAX HandlerBase to use.
* @exception IOException If any IO errors occur. *
* @exception IllegalArgumentException If the File object is null. * @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 * @see org.xml.sax.DocumentHandler
* @exception SAXException If the underlying parser throws a
* SAXException while parsing.
*/ */
public void parse(File f, HandlerBase hb) public void parse(File f, HandlerBase hb)
throws SAXException, IOException throws SAXException, IOException {
{
if (f == null) { if (f == null) {
throw new IllegalArgumentException("File cannot be null"); throw new IllegalArgumentException("File cannot be null");
} }
String uri = "file:" + f.getAbsolutePath(); String uri = "file:" + f.getAbsolutePath();
if (File.separatorChar == '\\') { if (File.separatorChar == '\\') {
uri = uri.replace('\\', '/'); uri = uri.replace('\\', '/');
@ -307,20 +300,19 @@ public abstract class SAXParser {
* *
* @param f The file containing the XML to parse * @param f The file containing the XML to parse
* @param dh The SAX DefaultHandler to use. * @param dh The SAX DefaultHandler to use.
* @exception IOException If any IO errors occur. *
* @exception IllegalArgumentException If the File object is null. * @throws IllegalArgumentException If the File object is null.
* @exception SAXException If the underlying parser throws a * @throws IOException If any IO errors occur.
* SAXException while parsing. * @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler * @see org.xml.sax.DocumentHandler
*/ */
public void parse(File f, DefaultHandler dh) public void parse(File f, DefaultHandler dh)
throws SAXException, IOException throws SAXException, IOException {
{
if (f == null) { if (f == null) {
throw new IllegalArgumentException("File cannot be null"); throw new IllegalArgumentException("File cannot be null");
} }
String uri = "file:" + f.getAbsolutePath(); String uri = "file:" + f.getAbsolutePath();
if (File.separatorChar == '\\') { if (File.separatorChar == '\\') {
uri = uri.replace('\\', '/'); uri = uri.replace('\\', '/');
@ -338,20 +330,20 @@ public abstract class SAXParser {
* *
* @param is The InputSource containing the content to be parsed. * @param is The InputSource containing the content to be parsed.
* @param hb The SAX HandlerBase to use. * @param hb The SAX HandlerBase to use.
* @exception IOException If any IO errors occur. *
* @exception IllegalArgumentException If the InputSource is null. * @throws IllegalArgumentException If the <code>InputSource</code> object
* @exception SAXException If the underlying parser throws a * is <code>null</code>.
* SAXException while parsing. * @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler * @see org.xml.sax.DocumentHandler
*/ */
public void parse(InputSource is, HandlerBase hb) public void parse(InputSource is, HandlerBase hb)
throws SAXException, IOException throws SAXException, IOException {
{
if (is == null) { if (is == null) {
throw new IllegalArgumentException("InputSource cannot be null"); throw new IllegalArgumentException("InputSource cannot be null");
} }
Parser parser = this.getParser(); Parser parser = this.getParser();
if (hb != null) { if (hb != null) {
parser.setDocumentHandler(hb); parser.setDocumentHandler(hb);
@ -369,20 +361,20 @@ public abstract class SAXParser {
* *
* @param is The InputSource containing the content to be parsed. * @param is The InputSource containing the content to be parsed.
* @param dh The SAX DefaultHandler to use. * @param dh The SAX DefaultHandler to use.
* @exception IOException If any IO errors occur. *
* @exception IllegalArgumentException If the InputSource is null. * @throws IllegalArgumentException If the <code>InputSource</code> object
* @exception SAXException If the underlying parser throws a * is <code>null</code>.
* SAXException while parsing. * @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler * @see org.xml.sax.DocumentHandler
*/ */
public void parse(InputSource is, DefaultHandler dh) public void parse(InputSource is, DefaultHandler dh)
throws SAXException, IOException throws SAXException, IOException {
{
if (is == null) { if (is == null) {
throw new IllegalArgumentException("InputSource cannot be null"); throw new IllegalArgumentException("InputSource cannot be null");
} }
XMLReader reader = this.getXMLReader(); XMLReader reader = this.getXMLReader();
if (dh != null) { if (dh != null) {
reader.setContentHandler(dh); reader.setContentHandler(dh);
@ -399,8 +391,9 @@ public abstract class SAXParser {
* *
* @return The SAX parser that is encapsultated by the * @return The SAX parser that is encapsultated by the
* implementation of this class. * implementation of this class.
*
* @throws SAXException If any SAX errors occur during processing.
*/ */
public abstract org.xml.sax.Parser getParser() throws SAXException; public abstract org.xml.sax.Parser getParser() throws SAXException;
/** /**
@ -409,6 +402,8 @@ public abstract class SAXParser {
* *
* @return The XMLReader that is encapsulated by the * @return The XMLReader that is encapsulated by the
* implementation of this class. * implementation of this class.
*
* @throws SAXException If any SAX errors occur during processing.
*/ */
public abstract org.xml.sax.XMLReader getXMLReader() throws SAXException; public abstract org.xml.sax.XMLReader getXMLReader() throws SAXException;
@ -434,19 +429,19 @@ public abstract class SAXParser {
public abstract boolean isValidating(); public abstract boolean isValidating();
/** /**
* Sets the particular property in the underlying implementation of * <p>Sets the particular property in the underlying implementation of
* {@link org.xml.sax.XMLReader}. * {@link org.xml.sax.XMLReader}.
* A list of the core features and properties can be found at * A list of the core features and properties can be found at
* <a href="http://www.megginson.com/SAX/Java/features.html"> http://www.megginson.com/SAX/Java/features.html </a> * <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 name The name of the property to be set.
* @param value The value of the property to be set. * @param value The value of the property to be set.
* @exception SAXNotRecognizedException When the underlying XMLReader does *
* not recognize the property name. * @throws SAXNotRecognizedException When the underlying XMLReader does
* * not recognize the property name.
* @exception SAXNotSupportedException When the underlying XMLReader * @throws SAXNotSupportedException When the underlying XMLReader
* recognizes the property name but doesn't support the * recognizes the property name but doesn't support the property.
* property.
* *
* @see org.xml.sax.XMLReader#setProperty * @see org.xml.sax.XMLReader#setProperty
*/ */
@ -454,22 +449,81 @@ public abstract class SAXParser {
throws SAXNotRecognizedException, SAXNotSupportedException; throws SAXNotRecognizedException, SAXNotSupportedException;
/** /**
* * <p>Returns the particular property requested for in the underlying
* Returns the particular property requested for in the underlying * implementation of {@link org.xml.sax.XMLReader}.</p>
* implementation of {@link org.xml.sax.XMLReader}.
* *
* @param name The name of the property to be retrieved. * @param name The name of the property to be retrieved.
* @return Value of the requested property. * @return Value of the requested property.
* *
* @exception SAXNotRecognizedException When the underlying XMLReader does * @throws SAXNotRecognizedException When the underlying XMLReader does
* not recognize the property name. * not recognize the property name.
* * @throws SAXNotSupportedException When the underlying XMLReader
* @exception SAXNotSupportedException When the underlying XMLReader * recognizes the property name but doesn't support the property.
* recognizes the property name but doesn't support the
* property.
* *
* @see org.xml.sax.XMLReader#getProperty * @see org.xml.sax.XMLReader#getProperty
*/ */
public abstract Object getProperty(String name) public abstract Object getProperty(String name)
throws SAXNotRecognizedException, SAXNotSupportedException; 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
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @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
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @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

@ -1,88 +1,53 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999-2001, Sun Microsystems,
* Inc., http://www.sun.com. For more information on the Apache Software
* Foundation, please see <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.parsers; package javax.xml.parsers;
import javax.xml.validation.Schema;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXNotSupportedException;
/** /**
* Defines a factory API that enables applications to configure and * Defines a factory API that enables applications to configure and
* obtain a SAX based parser to parse XML documents.<p> * obtain a SAX based parser to parse XML documents.
* An implementation of the <code>SAXParserFactory</code> class is
* <em>NOT</em> guaranteed to be thread safe. It is up to the user application
* to make sure about the use of the <code>SAXParserFactory</code> from
* more than one thread. Alternatively the application can have one instance
* of the <code>SAXParserFactory</code> per thread.
* An application can use the same instance of the factory to obtain one or
* more instances of the <code>SAXParser</code> provided the instance
* of the factory isn't being used in more than one thread at a time.
* <p>
* *
* The static <code>newInstance</code> method returns a new concrete * @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
* implementation of this class. * @version $Revision$, $Date$
*
* @since JAXP 1.0
* @version 1.0
*/ */
public abstract class SAXParserFactory { 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; private boolean validating = false;
private boolean namespaceAware= false;
/**
* <p>Should Parsers be namespace aware?</p>
*/
private boolean namespaceAware = false;
/**
* <p>Protected constructor to force use of {@link #newInstance()}.</p>
*/
protected SAXParserFactory () { protected SAXParserFactory () {
} }
@ -104,6 +69,12 @@ public abstract class SAXParserFactory {
* </code> format and contains the fully qualified name of the * </code> format and contains the fully qualified name of the
* implementation class with the key being the system property defined * implementation class with the key being the system property defined
* above. * 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>
* <li> * <li>
* Use the Services API (as detailed in the JAR specification), if * Use the Services API (as detailed in the JAR specification), if
@ -120,22 +91,33 @@ public abstract class SAXParserFactory {
* Once an application has obtained a reference to a * Once an application has obtained a reference to a
* <code>SAXParserFactory</code> it can use the factory to * <code>SAXParserFactory</code> it can use the factory to
* configure and obtain parser instances. * 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 <tt>System.err</tt> 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. * @return A new instance of a SAXParserFactory.
* *
* @exception FactoryConfigurationError if the implementation is * @exception FactoryConfigurationError if the implementation is
* not available or cannot be instantiated. * not available or cannot be instantiated.
*/ */
public static SAXParserFactory newInstance() public static SAXParserFactory newInstance() {
throws FactoryConfigurationError
{
try { try {
return (SAXParserFactory) FactoryFinder.find( return (SAXParserFactory) FactoryFinder.find(
/* The default property name according to the JAXP spec */ /* The default property name according to the JAXP spec */
"javax.xml.parsers.SAXParserFactory", "javax.xml.parsers.SAXParserFactory",
/* The fallback implementation class name */ /* The fallback implementation class name */
null); "org.apache.xerces.jaxp.SAXParserFactoryImpl");
} catch (FactoryFinder.ConfigurationError e) { } catch (FactoryFinder.ConfigurationError e) {
throw new FactoryConfigurationError(e.getException(), throw new FactoryConfigurationError(e.getException(),
e.getMessage()); e.getMessage());
@ -143,13 +125,14 @@ public abstract class SAXParserFactory {
} }
/** /**
* Creates a new instance of a SAXParser using the currently * <p>Creates a new instance of a SAXParser using the currently
* configured factory parameters. * configured factory parameters.</p>
* *
* @return A new instance of a SAXParser. * @return A new instance of a SAXParser.
* *
* @exception ParserConfigurationException if a parser cannot * @exception ParserConfigurationException if a parser cannot
* be created which satisfies the requested configuration. * be created which satisfies the requested configuration.
* @exception SAXException for SAX errors.
*/ */
public abstract SAXParser newSAXParser() public abstract SAXParser newSAXParser()
@ -165,8 +148,7 @@ public abstract class SAXParserFactory {
* provide support for XML namespaces; false otherwise. * provide support for XML namespaces; false otherwise.
*/ */
public void setNamespaceAware(boolean awareness) public void setNamespaceAware(boolean awareness) {
{
this.namespaceAware = awareness; this.namespaceAware = awareness;
} }
@ -174,13 +156,29 @@ public abstract class SAXParserFactory {
* Specifies that the parser produced by this code will * Specifies that the parser produced by this code will
* validate documents as they are parsed. By default the value of this is * validate documents as they are parsed. By default the value of this is
* set to <code>false</code>. * 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.
* See <a href="#validationCompatibility">here</a> for more details.)
* </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 <tt>false</tt>, 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 * @param validating true if the parser produced by this code will
* validate documents as they are parsed; false otherwise. * validate documents as they are parsed; false otherwise.
*/ */
public void setValidating(boolean validating) public void setValidating(boolean validating) {
{
this.validating = validating; this.validating = validating;
} }
@ -210,19 +208,38 @@ public abstract class SAXParserFactory {
/** /**
* *
* Sets the particular feature in the underlying implementation of * <p>Sets the particular feature in the underlying implementation of
* org.xml.sax.XMLReader. * org.xml.sax.XMLReader.
* A list of the core features and properties can be found at * A list of the core features and properties can be found at
* <a href="http://www.megginson.com/SAX/Java/features.html"> http://www.megginson.com/SAX/Java/features.html </a> * <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 name The name of the feature to be set.
* @param value The value of the feature to be set. * @param value The value of the feature to be set.
*
* @exception ParserConfigurationException if a parser cannot
* be created which satisfies the requested configuration.
* @exception SAXNotRecognizedException When the underlying XMLReader does * @exception SAXNotRecognizedException When the underlying XMLReader does
* not recognize the property name. * not recognize the property name.
*
* @exception SAXNotSupportedException When the underlying XMLReader * @exception SAXNotSupportedException When the underlying XMLReader
* recognizes the property name but doesn't support the * recognizes the property name but doesn't support the
* property. * property.
* @throws NullPointerException If the <code>name</code> parameter is null.
* *
* @see org.xml.sax.XMLReader#setFeature * @see org.xml.sax.XMLReader#setFeature
*/ */
@ -232,22 +249,182 @@ public abstract class SAXParserFactory {
/** /**
* *
* Returns the particular property requested for in the underlying * <p>Returns the particular property requested for in the underlying
* implementation of org.xml.sax.XMLReader. * implementation of org.xml.sax.XMLReader.</p>
* *
* @param name The name of the property to be retrieved. * @param name The name of the property to be retrieved.
*
* @return Value of the requested property. * @return Value of the requested property.
* *
* @exception SAXNotRecognizedException When the underlying XMLReader does * @exception ParserConfigurationException if a parser cannot be created which satisfies the requested configuration.
* not recognize the property name. * @exception SAXNotRecognizedException When the underlying XMLReader does not recognize the property name.
* * @exception SAXNotSupportedException When the underlying XMLReader recognizes the property name but doesn't support the property.
* @exception SAXNotSupportedException When the underlying XMLReader
* recognizes the property name but doesn't support the
* property.
* *
* @see org.xml.sax.XMLReader#getProperty * @see org.xml.sax.XMLReader#getProperty
*/ */
public abstract boolean getFeature(String name) public abstract boolean getFeature(String name)
throws ParserConfigurationException, SAXNotRecognizedException, throws ParserConfigurationException, SAXNotRecognizedException,
SAXNotSupportedException; 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
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @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
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @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
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @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
* For backward compatibility, when implementations for
* earlier versions of JAXP is used, this exception will be
* thrown.
*
* @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,99 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id: SecuritySupport.java,v 1.2.24.1 2005/03/29 23:25:08 jsuttor Exp $
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() {
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();
}
}

View File

@ -1,4 +1,7 @@
<HTML><HEAD> <HTML><HEAD>
<!--
$Id$
-->
</HEAD><BODY> </HEAD><BODY>

View File

@ -1,75 +1,47 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform; package javax.xml.transform;
/** /**
* <p>To provide customized error handling, implement this interface and * <p>To provide customized error handling, implement this interface and
* use the setErrorListener method to register an instance of the implmentation * use the <code>setErrorListener</code> method to register an instance of the
* with the {@link javax.xml.transform.Transformer}. The Transformer then reports * implmentation with the {@link javax.xml.transform.Transformer}. The
* all errors and warnings through this interface.</p> * <code>Transformer</code> then reports all errors and warnings through this
* interface.</p>
* *
* <p>If an application does <em>not</em> * <p>If an application does <em>not</em> register its own custom
* register an ErrorListener, errors are reported to System.err.</p> * <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 Transformer must use this interface * <p>For transformation errors, a <code>Transformer</code> must use this
* instead of throwing an exception: it is up to the application * interface instead of throwing an <code>Exception</code>: it is up to the
* to decide whether to throw an exception for different types of * application to decide whether to throw an <code>Exception</code> for
* errors and warnings. Note however that the Transformer is not required * different types of errors and warnings. Note however that the
* to continue with the transformation after a call to fatalError.</p> * <code>Transformer</code> is not required to continue with the transformation
* after a call to {@link #fatalError(TransformerException exception)}.</p>
* *
* <p>Transformers may use this mechanism to report XML parsing errors * <p><code>Transformer</code>s may use this mechanism to report XML parsing
* as well as transformation errors.</p> * errors as well as transformation errors.</p>
*/ */
public interface ErrorListener { public interface ErrorListener {
@ -115,16 +87,16 @@ public interface ErrorListener {
throws TransformerException; throws TransformerException;
/** /**
* Receive notification of a non-recoverable error. * <p>Receive notification of a non-recoverable error.</p>
* *
* <p>The transformer must continue to try and provide normal transformation * <p>The <code>Transformer</code> must continue to try and provide normal
* after invoking this method. It should still be possible for the * 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 * application to process the document through to the end if no other errors
* are encountered, but there is no guarantee that the output will be * are encountered, but there is no guarantee that the output will be
* useable.</p> * useable.</p>
* *
* @param exception The error information encapsulated in a * @param exception The error information encapsulated in a
* transformer exception. * <code>TransformerException</code>.
* *
* @throws javax.xml.transform.TransformerException if the application * @throws javax.xml.transform.TransformerException if the application
* chooses to discontinue the transformation. * chooses to discontinue the transformation.

View File

@ -1,137 +1,116 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999-2001, Sun Microsystems,
* Inc., http://www.sun.com. For more information on the Apache Software
* Foundation, please see <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform; package javax.xml.transform;
import java.io.InputStream;
import java.io.IOException;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.util.Properties; import java.util.Properties;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URL;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
/** /**
* This class is duplicated for each JAXP subpackage so keep it in sync. * This class is duplicated for each JAXP subpackage so keep it in
* It is package private and therefore is not exposed as part of the JAXP * sync. It is package private.
* API.
* *
* This code is designed to implement the JAXP 1.1 spec pluggability * This code is designed to implement the JAXP 1.1 spec pluggability
* feature and is designed to both compile and run on JDK version 1.1 and * feature and is designed to run on JDK version 1.1 and later including
* later. The code also runs both as part of an unbundled jar file and * JVMs that perform early linking like the Microsoft JVM in IE 5. Note
* when bundled as part of the JDK. * however that it must be compiled on a JDK version 1.2 or later system
* since it calls Thread#getContextClassLoader(). The code also runs both
* as part of an unbundled jar file and when bundled as part of the JDK.
*/ */
class FactoryFinder { class FactoryFinder {
/** Set to true for debugging */ /** Temp debug code - this will be removed after we test everything
private static final boolean debug = false; */
private static boolean debug = false;
static Properties cacheProps= new Properties();
static SecuritySupport ss = new SecuritySupport() ;
static boolean firstTime = true;
private static void debugPrintln(String msg) { // 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) { if (debug) {
System.err.println("JAXP: " + msg); System.err.println("JAXP: " + msg);
} }
} }
/** /**
* Figure out which ClassLoader to use. For JDK 1.2 and later use * Create an instance of a class using the specified ClassLoader and
* the context ClassLoader. * optionally fall back to the current ClassLoader if not found.
*/ *
private static ClassLoader findClassLoader() * @param className Name of the concrete class corresponding to the
throws ConfigurationError * service provider
{ *
Method m = null; * @param cl ClassLoader to use to load the class, null means to use
* the bootstrap ClassLoader
try { *
m = Thread.class.getMethod("getContextClassLoader", null); * @param doFallback true if the current ClassLoader should be tried as
} catch (NoSuchMethodException e) { * a fallback if the class is not found using cl
// Assume that we are running JDK 1.1, use the current ClassLoader
debugPrintln("assuming JDK 1.1");
return FactoryFinder.class.getClassLoader();
}
try {
return (ClassLoader) m.invoke(Thread.currentThread(), null);
} catch (IllegalAccessException e) {
// assert(false)
throw new ConfigurationError("Unexpected IllegalAccessException",
e);
} catch (InvocationTargetException e) {
// assert(e.getTargetException() instanceof SecurityException)
throw new ConfigurationError("Unexpected InvocationTargetException",
e);
}
}
/**
* Create an instance of a class using the specified ClassLoader
*/ */
private static Object newInstance(String className, private static Object newInstance(String className, ClassLoader cl,
ClassLoader classLoader) boolean doFallback)
throws ConfigurationError throws ConfigurationError
{ {
// assert(className != null);
try { try {
Class spiClass; Class providerClass;
if (classLoader == null) { if (cl == null) {
spiClass = Class.forName(className); // If classloader is null Use the bootstrap ClassLoader.
// Thus Class.forName(String) will use the current
// ClassLoader which will be the bootstrap ClassLoader.
providerClass = Class.forName(className);
} else { } else {
spiClass = classLoader.loadClass(className); try {
providerClass = cl.loadClass(className);
} catch (ClassNotFoundException x) {
if (doFallback) {
// Fall back to current classloader
cl = FactoryFinder.class.getClassLoader();
providerClass = cl.loadClass(className);
} else {
throw x;
}
}
} }
return spiClass.newInstance();
Object instance = providerClass.newInstance();
dPrint("created new instance of " + providerClass +
" using ClassLoader: " + cl);
return instance;
} catch (ClassNotFoundException x) { } catch (ClassNotFoundException x) {
throw new ConfigurationError( throw new ConfigurationError(
"Provider " + className + " not found", x); "Provider " + className + " not found", x);
@ -141,7 +120,7 @@ class FactoryFinder {
x); x);
} }
} }
/** /**
* Finds the implementation Class object in the specified order. Main * Finds the implementation Class object in the specified order. Main
* entry point. * entry point.
@ -152,101 +131,165 @@ class FactoryFinder {
* @param fallbackClassName Implementation class name, if nothing else * @param fallbackClassName Implementation class name, if nothing else
* is found. Use null to mean no fallback. * is found. Use null to mean no fallback.
* *
* @exception FactoryFinder.ConfigurationError
*
* Package private so this code can be shared. * Package private so this code can be shared.
*/ */
static Object find(String factoryId, String fallbackClassName) static Object find(String factoryId, String fallbackClassName)
throws ConfigurationError throws ConfigurationError
{ {
debugPrintln("debug is on");
ClassLoader classLoader = findClassLoader(); // Figure out which ClassLoader to use for loading the provider
// class. If there is a Context ClassLoader then use it.
// Use the system property first
try { ClassLoader classLoader = ss.getContextClassLoader();
String systemProp =
System.getProperty( factoryId ); if (classLoader == null) {
if( systemProp!=null) { // if we have no Context ClassLoader
debugPrintln("found system property " + systemProp); // so use the current ClassLoader
return newInstance(systemProp, classLoader); classLoader = FactoryFinder.class.getClassLoader();
}
} catch (SecurityException se) {
} }
// try to read from $java.home/lib/xml.properties dPrint("find factoryId =" + factoryId);
// Use the system property first
try { try {
String javah=System.getProperty( "java.home" ); String systemProp = ss.getSystemProperty(factoryId);
if( systemProp!=null) {
dPrint("found system property, value=" + systemProp);
return newInstance(systemProp, classLoader, true );
}
} catch (SecurityException se) {
//if first option fails due to any reason we should try next option in the
//look up algorithm.
}
// try to read from $java.home/lib/jaxp.properties
try {
String javah = ss.getSystemProperty("java.home");
String configFile = javah + File.separator + String configFile = javah + File.separator +
"lib" + File.separator + "jaxp.properties"; "lib" + File.separator + "jaxp.properties";
File f=new File( configFile ); String factoryClassName = null;
if( f.exists()) { if(firstTime){
Properties props=new Properties(); synchronized(cacheProps){
props.load( new FileInputStream(f)); if(firstTime){
String factoryClassName = props.getProperty(factoryId); File f=new File( configFile );
debugPrintln("found java.home property " + factoryClassName); firstTime = false;
return newInstance(factoryClassName, classLoader); if(ss.doesFileExist(f)){
dPrint("Read properties file "+f);
//cacheProps.load( new FileInputStream(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, classLoader, true);
} }
} catch(Exception ex ) { } catch(Exception ex ) {
if( debug ) ex.printStackTrace(); if( debug ) ex.printStackTrace();
} }
String serviceId = "META-INF/services/" + factoryId; // Try Jar Service Provider Mechanism
// try to find services in CLASSPATH Object provider = findJarServiceProvider(factoryId);
try { if (provider != null) {
InputStream is=null; return provider;
if (classLoader == null) {
is=ClassLoader.getSystemResourceAsStream( serviceId );
} else {
is=classLoader.getResourceAsStream( serviceId );
}
if( is!=null ) {
debugPrintln("found " + serviceId);
// Read the service provider name in UTF-8 as specified in
// the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
// doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
// VJ++ this is apparently ASCII, which is a subset of
// UTF-8... and since the strings we'll be reading here are
// also primarily limited to the 7-bit ASCII range (at
// least, in English versions), this should work well
// enough to keep us on the air until we're ready to
// officially decommit from VJ++. [Edited comment from
// jkesselm]
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
} catch (java.io.UnsupportedEncodingException e) {
rd = new BufferedReader(new InputStreamReader(is));
}
String factoryClassName = rd.readLine();
rd.close();
if (factoryClassName != null &&
! "".equals(factoryClassName)) {
debugPrintln("loaded from services: " + factoryClassName);
return newInstance(factoryClassName, classLoader);
}
}
} catch( Exception ex ) {
if( debug ) ex.printStackTrace();
} }
if (fallbackClassName == null) { if (fallbackClassName == null) {
throw new ConfigurationError( throw new ConfigurationError(
"Provider for " + factoryId + " cannot be found", null); "Provider for " + factoryId + " cannot be found", null);
} }
debugPrintln("loaded from fallback value: " + fallbackClassName); dPrint("loaded from fallback value: " + fallbackClassName);
return newInstance(fallbackClassName, classLoader); return newInstance(fallbackClassName, classLoader, 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;
}
dPrint("found jar resource=" + serviceId +
" using ClassLoader: " + cl);
// Read the service provider name in UTF-8 as specified in
// the jar spec. Unfortunately this fails in Microsoft
// VJ++, which does not implement the UTF-8
// encoding. Theoretically, we should simply let it fail in
// that case, since the JVM is obviously broken if it
// doesn't support such a basic standard. But since there
// are still some users attempting to use VJ++ for
// development, we have dropped in a fallback which makes a
// second attempt using the platform's default encoding. In
// VJ++ this is apparently ASCII, which is a subset of
// UTF-8... and since the strings we'll be reading here are
// also primarily limited to the 7-bit ASCII range (at
// least, in English versions), this should work well
// enough to keep us on the air until we're ready to
// officially decommit from VJ++. [Edited comment from
// jkesselm]
BufferedReader rd;
try {
rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
} 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 { static class ConfigurationError extends Error {
@ -265,4 +308,5 @@ class FactoryFinder {
return exception; return exception;
} }
} }
} }

View File

@ -1,65 +1,31 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform; package javax.xml.transform;
/** /**
* Provides string constants that can be used to set * Provides string constants that can be used to set
* output properties for a Transformer, or to retrieve * output properties for a Transformer, or to retrieve
* output properties from a Transformer or Templates object. * output properties from a Transformer or Templates object.
* <p>A properties in this class are read-only.</p> * <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> * @see <a href="http://www.w3.org/TR/xslt#output">
* section 16 of the XSL Transformations (XSLT) W3C Recommendation</a>
*/ */
public class OutputKeys { public class OutputKeys {
@ -67,12 +33,12 @@ public class OutputKeys {
* Default constructor is private on purpose. This class is * Default constructor is private on purpose. This class is
* only for static variable access, and should never be constructed. * only for static variable access, and should never be constructed.
*/ */
private OutputKeys() {} private OutputKeys() { }
/** /**
* method = "xml" | "html" | "text" | <var>expanded name</var>. * method = "xml" | "html" | "text" | <var>expanded name</var>.
* *
* <p>The method attribute identifies the overall method that * <p>The value of the method property identifies the overall method that
* should be used for outputting the result tree. Other non-namespaced * should be used for outputting the result tree. Other non-namespaced
* values may be used, such as "xhtml", but, if accepted, the handling * values may be used, such as "xhtml", but, if accepted, the handling
* of such values is implementation defined. If any of the method values * of such values is implementation defined. If any of the method values
@ -81,7 +47,8 @@ public class OutputKeys {
* or {@link javax.xml.transform.Transformer#setOutputProperties} will * or {@link javax.xml.transform.Transformer#setOutputProperties} will
* throw a {@link java.lang.IllegalArgumentException}.</p> * 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> * @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"; public static final String METHOD = "method";
@ -94,11 +61,12 @@ public class OutputKeys {
* version of XML to be used for outputting the result tree. The default * 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 * value for the xml output method is 1.0. When the output method is
* "html", the version value indicates the version of the HTML. * "html", the version value indicates the version of the HTML.
* The default value for the html output method is 4.0, which specifies * 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 * that the result should be output as HTML conforming to the HTML 4.0
* Recommendation [HTML]. If the output method is "text", the version * Recommendation [HTML]. If the output method is "text", the version
* property is ignored.</p> * property is ignored.</p>
* @see <a href="http://www.w3.org/TR/xslt#output">section 16 of the XSL Transformations (XSLT) W3C Recommendation</a> * @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"; public static final String VERSION = "version";
@ -107,13 +75,14 @@ public class OutputKeys {
* *
* <p><code>encoding</code> specifies the preferred character * <p><code>encoding</code> specifies the preferred character
* encoding that the Transformer should use to encode sequences of * encoding that the Transformer should use to encode sequences of
* characters as sequences of bytes. The value of the attribute should be * characters as sequences of bytes. The value of the encoding property should be
* treated case-insensitively. The value must only contain characters in * treated case-insensitively. The value must only contain characters in
* the range #x21 to #x7E (i.e., printable ASCII characters). The value * the range #x21 to #x7E (i.e., printable ASCII characters). The value
* should either be a <code>charset</code> registered with the Internet * should either be a <code>charset</code> registered with the Internet
* Assigned Numbers Authority <a href="#IANA">[IANA]</a>, * Assigned Numbers Authority <a href="#IANA">[IANA]</a>,
* <a href="#RFC2278">[RFC2278]</a> or start with <code>X-</code>.</p> * <a href="#RFC2278">[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> * @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"; public static final String ENCODING = "encoding";
@ -123,7 +92,8 @@ public class OutputKeys {
* <p><code>omit-xml-declaration</code> specifies whether the XSLT * <p><code>omit-xml-declaration</code> specifies whether the XSLT
* processor should output an XML declaration; the value must be * processor should output an XML declaration; the value must be
* <code>yes</code> or <code>no</code>.</p> * <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> * @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"; public static final String OMIT_XML_DECLARATION = "omit-xml-declaration";
@ -133,7 +103,8 @@ public class OutputKeys {
* <p><code>standalone</code> specifies whether the Transformer * <p><code>standalone</code> specifies whether the Transformer
* should output a standalone document declaration; the value must be * should output a standalone document declaration; the value must be
* <code>yes</code> or <code>no</code>.</p> * <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> * @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"; public static final String STANDALONE = "standalone";
@ -142,13 +113,14 @@ public class OutputKeys {
* <p>See the documentation for the {@link #DOCTYPE_SYSTEM} property * <p>See the documentation for the {@link #DOCTYPE_SYSTEM} property
* for a description of what the value of the key should be.</p> * 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> * @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"; public static final String DOCTYPE_PUBLIC = "doctype-public";
/** /**
* doctype-system = <var>string</var>. * doctype-system = <var>string</var>.
* <p><code>doctype-public</code> specifies the public identifier * <p><code>doctype-system</code> specifies the system identifier
* to be used in the document type declaration.</p> * to be used in the document type declaration.</p>
* <p>If the doctype-system property is specified, the xml output method * <p>If the doctype-system property is specified, the xml output method
* should output a document type declaration immediately before the first * should output a document type declaration immediately before the first
@ -157,22 +129,23 @@ public class OutputKeys {
* output method should output PUBLIC followed by the public identifier * output method should output PUBLIC followed by the public identifier
* and then the system identifier; otherwise, it should output SYSTEM * and then the system identifier; otherwise, it should output SYSTEM
* followed by the system identifier. The internal subset should be empty. * followed by the system identifier. The internal subset should be empty.
* The doctype-public attribute should be ignored unless the doctype-system * The value of the doctype-public property should be ignored unless the doctype-system
* attribute is specified.</p> * property is specified.</p>
* <p>If the doctype-public or doctype-system attributes are specified, * <p>If the doctype-public or doctype-system properties are specified,
* then the html output method should output a document type declaration * then the html output method should output a document type declaration
* immediately before the first element. The name following &lt;!DOCTYPE * immediately before the first element. The name following &lt;!DOCTYPE
* should be HTML or html. If the doctype-public attribute is specified, * should be HTML or html. If the doctype-public property is specified,
* then the output method should output PUBLIC followed by the specified * then the output method should output PUBLIC followed by the specified
* public identifier; if the doctype-system attribute is also specified, * public identifier; if the doctype-system property is also specified,
* it should also output the specified system identifier following the * it should also output the specified system identifier following the
* public identifier. If the doctype-system attribute is specified but * public identifier. If the doctype-system property is specified but
* the doctype-public attribute is not specified, then the output method * the doctype-public property is not specified, then the output method
* should output SYSTEM followed by the specified system identifier.</p> * should output SYSTEM followed by the specified system identifier.</p>
* *
* <p><code>doctype-system</code> specifies the system identifier * <p><code>doctype-system</code> specifies the system identifier
* to be used in the document type declaration.</p> * 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> * @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"; public static final String DOCTYPE_SYSTEM = "doctype-system";
@ -181,9 +154,12 @@ public class OutputKeys {
* *
* <p><code>cdata-section-elements</code> specifies a whitespace delimited * <p><code>cdata-section-elements</code> specifies a whitespace delimited
* list of the names of elements whose text node children should be output * list of the names of elements whose text node children should be output
* using CDATA sections.</p> * 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> * @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 = public static final String CDATA_SECTION_ELEMENTS =
"cdata-section-elements"; "cdata-section-elements";
@ -194,7 +170,8 @@ public class OutputKeys {
* <p><code>indent</code> specifies whether the Transformer may * <p><code>indent</code> specifies whether the Transformer may
* add additional whitespace when outputting the result tree; the value * add additional whitespace when outputting the result tree; the value
* must be <code>yes</code> or <code>no</code>. </p> * 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> * @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"; public static final String INDENT = "indent";
@ -208,7 +185,8 @@ public class OutputKeys {
* <code>text</code>, a <code>charset</code> parameter should be added * <code>text</code>, a <code>charset</code> parameter should be added
* according to the character encoding actually used by the output * according to the character encoding actually used by the output
* method. </p> * method. </p>
* @see <a href="http://www.w3.org/TR/xslt#output">section 16 of the XSL Transformations (XSLT) W3C Recommendation</a> * @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"; public static final String MEDIA_TYPE = "media-type";
} }

View File

@ -1,61 +1,28 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform; package javax.xml.transform;
/** /**
* An object that implements this interface contains the information * <p>An object that implements this interface contains the information
* needed to build a transformation result tree. * needed to build a transformation result tree.</p>
*
* @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
*/ */
public interface Result { public interface Result {

View File

@ -0,0 +1,99 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id: SecuritySupport.java,v 1.2.24.1 2005/03/29 23:32:22 jsuttor Exp $
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() {
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();
}
}

View File

@ -1,56 +1,21 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform; package javax.xml.transform;
/** /**

View File

@ -1,56 +1,21 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform; package javax.xml.transform;
/** /**

View File

@ -1,60 +1,28 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform; package javax.xml.transform;
import java.util.Properties; import java.util.Properties;
/** /**
* An object that implements this interface is the runtime representation of processed * An object that implements this interface is the runtime representation of processed
* transformation instructions. * transformation instructions.
@ -75,7 +43,8 @@ public interface Templates {
Transformer newTransformer() throws TransformerConfigurationException; Transformer newTransformer() throws TransformerConfigurationException;
/** /**
* Get the static properties for xsl:output. The object returned will * 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 * be a clone of the internal values. Accordingly, it can be mutated
* without mutating the Templates object, and then handed in to * without mutating the Templates object, and then handed in to
* {@link javax.xml.transform.Transformer#setOutputProperties}. * {@link javax.xml.transform.Transformer#setOutputProperties}.
@ -98,9 +67,7 @@ public interface Templates {
* Value Templates</a> attribute values will * Value Templates</a> attribute values will
* be returned unexpanded (since there is no context at this point). The * be returned unexpanded (since there is no context at this point). The
* namespace prefixes inside Attribute Value Templates will be unexpanded, * namespace prefixes inside Attribute Value Templates will be unexpanded,
* so that they remain valid XPath values. (For XSLT 1.0, this is not * so that they remain valid XPath values.</p>
* a problem since Attribute Value Templates are not allowed for xsl:output
* attributes. However, the will be allowed in versions after 1.1.)</p>
* *
* @return A Properties object, never null. * @return A Properties object, never null.
*/ */

View File

@ -1,66 +1,30 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform; package javax.xml.transform;
import java.util.Properties; import java.util.Properties;
/** /**
* An instance of this abstract class can transform a * An instance of this abstract class can transform a
* source tree into a result tree. * source tree into a result tree.
* *
* <p>An instance of this class can be obtained with the <code> * <p>An instance of this class can be obtained with the
* {@link TransformerFactory#newTransformer TransformerFactory.newTransformer} * {@link TransformerFactory#newTransformer TransformerFactory.newTransformer}
* method. This instance may then be used to process XML from a * method. This instance may then be used to process XML from a
* variety of sources and write the transformation output to a * variety of sources and write the transformation output to a
@ -72,21 +36,63 @@ import java.util.Properties;
* *
* <p>A <code>Transformer</code> may be used multiple times. Parameters and * <p>A <code>Transformer</code> may be used multiple times. Parameters and
* output properties are preserved across transformations.</p> * output properties are preserved across transformations.</p>
*
* @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision$, $Date$
*/ */
public abstract class Transformer { public abstract class Transformer {
/** /**
* Default constructor is protected on purpose. * Default constructor is protected on purpose.
*/ */
protected Transformer() {} 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>
*
* @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() + "\""
);
}
/** /**
* Process the source tree to the output result. * <p>Transform the XML <code>Source</code> to a <code>Result</code>.
* @param xmlSource The input for the source tree. * Specific transformation behavior is determined by the settings of the
* @param outputTarget The output target. * <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 * @throws TransformerException If an unrecoverable error occurs
* during the course of the transformation. * during the course of the transformation.
*/ */
public abstract void transform(Source xmlSource, Result outputTarget) public abstract void transform(Source xmlSource, Result outputTarget)
throws TransformerException; throws TransformerException;
@ -97,32 +103,59 @@ public abstract class Transformer {
* <p>Pass a qualified name as a two-part string, the namespace URI * <p>Pass a qualified name as a two-part string, the namespace URI
* enclosed in curly braces ({}), followed by the local name. If the * enclosed in curly braces ({}), followed by the local name. If the
* name has a null URL, the String only contain the local name. An * 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 * application can safely check for a non-null URI by testing to see if the
* character of the name is a '{' character.</p> * first character of the name is a '{' character.</p>
* <p>For example, if a URI and local name were obtained from an element * <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;, * defined with &lt;xyz:foo
* then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that * xmlns:xyz="http://xyz.foo.com/yada/baz.html"/&gt;,
* no prefix is used.</p> * 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 * @param name The name of the parameter, which may begin with a
* in curly braces ({}). * namespace URI in curly braces ({}).
* @param value The value object. This can be any valid Java object. It is * @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 * up to the processor to provide the proper object coersion or to simply
* pass the object on for use in an extension. * pass the object on for use in an extension.
*
* @throws NullPointerException If value is null.
*/ */
public abstract void setParameter(String name, Object value); public abstract void setParameter(String name, Object value);
/** /**
* Get a parameter that was explicitly set with setParameter * Get a parameter that was explicitly set with setParameter.
* or setParameters.
* *
* <p>This method does not return a default parameter value, which * <p>This method does not return a default parameter value, which
* cannot be determined until the node context is evaluated during * cannot be determined until the node context is evaluated during
* the transformation process. * the transformation process.
* *
* @param name of <code>Object</code> to get
* @return A parameter that has been set with setParameter. * @return A parameter that has been set with setParameter.
*/ */
public abstract Object getParameter(String name); 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. * Clear all parameters set with setParameter.
@ -134,7 +167,7 @@ public abstract class Transformer {
* document(). * document().
* *
* <p>If the resolver argument is null, the URIResolver value will * <p>If the resolver argument is null, the URIResolver value will
* be cleared, and the default behavior will be used.</p> * be cleared and the transformer will no longer have a resolver.</p>
* *
* @param resolver An object that implements the URIResolver interface, * @param resolver An object that implements the URIResolver interface,
* or null. * or null.
@ -143,7 +176,7 @@ public abstract class Transformer {
/** /**
* Get an object that will be used to resolve URIs used in * Get an object that will be used to resolve URIs used in
* document(), etc. * document().
* *
* @return An object that implements the URIResolver interface, * @return An object that implements the URIResolver interface,
* or null. * or null.
@ -159,15 +192,18 @@ public abstract class Transformer {
* previously set are removed, and the value will revert to the value * previously set are removed, and the value will revert to the value
* defined in the templates object.</p> * defined in the templates object.</p>
* *
* <p>Pass a qualified property key name as a two-part string, the namespace URI * <p>Pass a qualified property key name as a two-part string, the namespace
* enclosed in curly braces ({}), followed by the local name. If the * 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 * 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 * application can safely check for a non-null URI by testing to see if the
* character of the name is a '{' character.</p> * first character of the name is a '{' character.</p>
* <p>For example, if a URI and local name were obtained from an element * <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;, * defined with &lt;xyz:foo
* then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that * xmlns:xyz="http://xyz.foo.com/yada/baz.html"/&gt;,
* no prefix is used.</p> * 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 * @param oformat A set of output properties that will be
* used to override any of the same properties in affect * used to override any of the same properties in affect
@ -176,18 +212,16 @@ public abstract class Transformer {
* @see javax.xml.transform.OutputKeys * @see javax.xml.transform.OutputKeys
* @see java.util.Properties * @see java.util.Properties
* *
* @throws IllegalArgumentException if any of the argument keys are not
* recognized and are not namespace qualified.
*/ */
public abstract void setOutputProperties(Properties oformat) public abstract void setOutputProperties(Properties oformat);
throws IllegalArgumentException;
/** /**
* Get a copy of the output properties for the transformation. * <p>Get a copy of the output properties for the transformation.</p>
* *
* <p>The properties returned should contain properties set by the user, * <p>The properties returned should contain properties set by the user,
* and properties set by the stylesheet, and these properties * 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 * 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 * XSL Transformations (XSLT) W3C Recommendation</a>. The properties that
* were specifically set by the user or the stylesheet should be in the base * were specifically set by the user or the stylesheet should be in the base
* Properties list, while the XSLT default properties that were not * Properties list, while the XSLT default properties that were not
@ -201,17 +235,20 @@ public abstract class Transformer {
* {@link #setOutputProperties}, or in the stylesheet.</p> * {@link #setOutputProperties}, or in the stylesheet.</p>
* *
* <p>Note that mutation of the Properties object returned will not * <p>Note that mutation of the Properties object returned will not
* effect the properties that the transformation contains.</p> * effect the properties that the transformer contains.</p>
* *
* <p>If any of the argument keys are not recognized and are not * <p>If any of the argument keys are not recognized and are not
* namespace qualified, the property will be ignored. In other words the * namespace qualified, the property will be ignored and not returned.
* behaviour is not orthogonal with setOutputProperties.</p> * In other words the behaviour is not orthogonal with
* {@link #setOutputProperties setOutputProperties}.</p>
* *
* @return A copy of the set of output properties in effect * @return A copy of the set of output properties in effect for
* for the next transformation. * the next transformation.
* *
* @see javax.xml.transform.OutputKeys * @see javax.xml.transform.OutputKeys
* @see java.util.Properties * @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(); public abstract Properties getOutputProperties();
@ -222,15 +259,16 @@ public abstract class Transformer {
* <p>Pass a qualified property name as a two-part string, the namespace URI * <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 * enclosed in curly braces ({}), followed by the local name. If the
* name has a null URL, the String only contain the local name. An * 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 * application can safely check for a non-null URI by testing to see if the
* character of the name is a '{' character.</p> * first character of the name is a '{' character.</p>
* <p>For example, if a URI and local name were obtained from an element * <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;, * defined with &lt;xyz:foo
* then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that * xmlns:xyz="http://xyz.foo.com/yada/baz.html"/&gt;,
* no prefix is used.</p> * 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 * <p>The Properties object that was passed to {@link #setOutputProperties}
* be effected by calling this method.</p> * won't be effected by calling this method.</p>
* *
* @param name A non-null String that specifies an output * @param name A non-null String that specifies an output
* property name, which may be namespace qualified. * property name, which may be namespace qualified.
@ -246,7 +284,7 @@ public abstract class Transformer {
/** /**
* Get an output property that is in effect for the * Get an output property that is in effect for the
* transformation. The property specified may be a property * transformer. The property specified may be a property
* that was set with setOutputProperty, or it may be a * that was set with setOutputProperty, or it may be a
* property specified in the stylesheet. * property specified in the stylesheet.
* *
@ -274,6 +312,7 @@ public abstract class Transformer {
/** /**
* Get the error event handler in effect for the transformation. * 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. * @return The current error handler, which should never be null.
*/ */

View File

@ -1,56 +1,21 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform; package javax.xml.transform;
/** /**
@ -92,9 +57,8 @@ public class TransformerConfigurationException extends TransformerException {
* given <code>Exception</code> base cause and detail message. * given <code>Exception</code> base cause and detail message.
* *
* @param e The exception to be encapsulated in a * @param e The exception to be encapsulated in a
* TransformerConfigurationException * TransformerConfigurationException
* @param msg The detail message. * @param msg The detail message.
* @param e The exception to be wrapped in a TransformerConfigurationException
*/ */
public TransformerConfigurationException(String msg, Throwable e) { public TransformerConfigurationException(String msg, Throwable e) {
super(msg, e); super(msg, e);

View File

@ -1,64 +1,26 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform; package javax.xml.transform;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import javax.xml.transform.SourceLocator;
/** /**
* This class specifies an exceptional condition that occured * This class specifies an exceptional condition that occured
* during the transformation process. * during the transformation process.
@ -335,6 +297,7 @@ public class TransformerException extends Exception {
* @param s The writer where the dump will be sent to. * @param s The writer where the dump will be sent to.
*/ */
public void printStackTrace(java.io.PrintWriter s) { public void printStackTrace(java.io.PrintWriter s) {
if (s == null) { if (s == null) {
s = new java.io.PrintWriter(System.err, true); s = new java.io.PrintWriter(System.err, true);
} }
@ -345,6 +308,7 @@ public class TransformerException extends Exception {
if (null != locInfo) { if (null != locInfo) {
s.println(locInfo); s.println(locInfo);
} }
super.printStackTrace(s); super.printStackTrace(s);
} catch (Throwable e) {} } catch (Throwable e) {}
@ -393,6 +357,7 @@ public class TransformerException extends Exception {
exception = null; exception = null;
} }
} }
s.flush(); // insure output is written
s.flush();
} }
} }

View File

@ -1,84 +1,66 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform; package javax.xml.transform;
/** /**
* A TransformerFactory instance can be used to create * <p>A TransformerFactory instance can be used to create
* {@link javax.xml.transform.Transformer} and * {@link javax.xml.transform.Transformer} and
* {@link javax.xml.transform.Templates} objects. * {@link javax.xml.transform.Templates} objects.</p>
* *
* <p>The system property that determines which Factory implementation to * <p>The system property that determines which Factory implementation
* create is named <code>"javax.xml.transform.TransformerFactory"</code>. * to create is named <code>"javax.xml.transform.TransformerFactory"</code>.
* This property names a concrete subclass of the * This property names a concrete subclass of the
* <code>TransformerFactory</code> abstract class. If the property is not * <code>TransformerFactory</code> abstract class. If the property is not
* defined, a platform default is be used.</p> * defined, a platform default is be used.</p>
* *
* An implementation of the <code>TransformerFactory</code> class is * @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* <em>NOT</em> guaranteed to be thread safe. It is up to the user application
* to make sure about the use of the <code>TransformerFactory</code> from
* more than one thread. Alternatively the application can have one instance
* of the <code>TransformerFactory</code> per thread.
* An application can use the same instance of the factory to obtain one or
* more instances of a <code>Transformer</code> or <code>Templates</code>
* provided the instance of the factory isn't being used in more than one
* thread at a time.
*/ */
public abstract class TransformerFactory { public abstract class TransformerFactory {
/** /**
* Default constructor is protected on purpose. * Default constructor is protected on purpose.
*/ */
protected TransformerFactory() {} protected TransformerFactory() { }
/**
* <p>Get current state of canonicalization.</p>
*
* @return current state canonicalization control
*/
/*
public boolean getCanonicalization() {
return canonicalState;
}
*/
/**
* <p>Set canonicalization control to <code>true</code> or
* </code>false</code>.</p>
*
* @param state of canonicalization
*/
/*
public void setCanonicalization(boolean state) {
canonicalState = state;
}
*/
/** /**
* Obtain a new instance of a <code>TransformerFactory</code>. * Obtain a new instance of a <code>TransformerFactory</code>.
@ -97,6 +79,12 @@ public abstract class TransformerFactory {
* </code> format and contains the fully qualified name of the * </code> format and contains the fully qualified name of the
* implementation class with the key being the system property defined * implementation class with the key being the system property defined
* above. * 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>
* <li> * <li>
* Use the Services API (as detailed in the JAR specification), if * Use the Services API (as detailed in the JAR specification), if
@ -114,61 +102,67 @@ public abstract class TransformerFactory {
* TransformerFactory</code> it can use the factory to configure * TransformerFactory</code> it can use the factory to configure
* and obtain parser instances. * and obtain parser instances.
* *
* @return new TransformerFactory instance, never null (unless an {@link ErrorListener} * @return new TransformerFactory instance, never null.
* is registered with the TransformerFactory, in which case an exception error sends an
* error message to the ErrorListener and returns null).
* *
* @throws TransformerFactoryConfigurationError * @throws TransformerFactoryConfigurationError Thrown if the implementation
* if the implmentation is not available or cannot be instantiated. * is not available or cannot be instantiated.
*/ */
public static TransformerFactory newInstance() public static TransformerFactory newInstance()
throws TransformerFactoryConfigurationError throws TransformerFactoryConfigurationError {
{
try { try {
return (TransformerFactory) FactoryFinder.find( return (TransformerFactory) FactoryFinder.find(
/* The default property name according to the JAXP spec */ /* The default property name according to the JAXP spec */
"javax.xml.transform.TransformerFactory", "javax.xml.transform.TransformerFactory",
/* The fallback implementation class name */ /* The fallback implementation class name, XSLTC */
null); "org.apache.xalan.xsltc.trax.TransformerFactoryImpl");
} catch (FactoryFinder.ConfigurationError e) { } catch (FactoryFinder.ConfigurationError e) {
throw new TransformerFactoryConfigurationError(e.getException(), throw new TransformerFactoryConfigurationError(
e.getMessage()); e.getException(),
e.getMessage());
} }
} }
/** /**
* Process the Source into a Transformer object. Care must * <p>Process the <code>Source</code> into a <code>Transformer</code>
* be given not to use this object in multiple threads running concurrently. * <code>Object</code>. The <code>Source</code> is an XSLT document that
* Different TransformerFactories can be used concurrently by different * conforms to <a href="http://www.w3.org/TR/xslt">
* threads. * 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 An object that holds a URI, input stream, etc. * @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 Transformer object that may be used to perform a transformation * @return A <code>Transformer</code> object that may be used to perform
* in a single thread, never null (unless an {@link ErrorListener} is registered with * a transformation in a single <code>Thread</code>, never
* the TransformerFactory, in which case an exception error sends an error message to * <code>null</code>.
* the ErrorListener and returns null).
* *
* @exception TransformerConfigurationException May throw this during the parse * @throws TransformerConfigurationException Thrown if there are errors when
* when it is constructing the Templates object and fails. * 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) public abstract Transformer newTransformer(Source source)
throws TransformerConfigurationException; throws TransformerConfigurationException;
/** /**
* Create a new Transformer object that performs a copy * <p>Create a new <code>Transformer<code> that performs a copy
* of the source to the result. * of the <code>Source</code> to the <code>Result</code>.
* * i.e. the "<em>identity transform</em>".</p>
* @param source An object that holds a URI, input stream, etc.
* *
* @return A Transformer object that may be used to perform a transformation * @return A Transformer object that may be used to perform a transformation
* in a single thread, never null (unless an {@link ErrorListener} is registered with * in a single thread, never null.
* the TransformerFactory, in which case an exception error sends an error message to
* the ErrorListener and returns null).
* *
* @exception TransformerConfigurationException May throw this during * @exception TransformerConfigurationException Thrown if it is not
* the parse when it is constructing the * possible to create a <code>Transformer</code> instance.
* Templates object and fails.
*/ */
public abstract Transformer newTransformer() public abstract Transformer newTransformer()
throws TransformerConfigurationException; throws TransformerConfigurationException;
@ -183,43 +177,50 @@ public abstract class TransformerFactory {
* *
* @param source An object that holds a URL, input stream, etc. * @param source An object that holds a URL, input stream, etc.
* *
* @return A Templates object capable of being used for transformation purposes, * @return A Templates object capable of being used for transformation
* never null (unless an {@link ErrorListener} is registered with * purposes, never null.
* the TransformerFactory, in which case an exception error sends an error message to
* the ErrorListener and returns null).
* *
* @exception TransformerConfigurationException May throw this during the parse when it * @exception TransformerConfigurationException May throw this during the
* is constructing the Templates object and fails. * parse when it is constructing the Templates object and fails.
*/ */
public abstract Templates newTemplates(Source source) public abstract Templates newTemplates(Source source)
throws TransformerConfigurationException; throws TransformerConfigurationException;
/** /**
* Get the stylesheet specification(s) associated * <p>Get the stylesheet specification(s) associated with the
* via the xml-stylesheet processing instruction (see * XML <code>Source</code> document via the
* http://www.w3.org/TR/xml-stylesheet/) with the document * <a href="http://www.w3.org/TR/xml-stylesheet/">
* document specified in the source parameter, and that match * xml-stylesheet processing instruction</a> that match the given criteria.
* the given criteria. Note that it is possible to return several * Note that it is possible to return several stylesheets, in which case
* stylesheets, in which case they are applied as if they were * they are applied as if they were a list of imports or cascades in a
* a list of imports or cascades in a single stylesheet. * single stylesheet.</p>
* *
* @param source The XML source document. * @param source The XML source document.
* @param media The media attribute to be matched. May be null, in which * @param media The media attribute to be matched. May be null, in which
* case the prefered templates will be used (i.e. alternate = no). * 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 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. * @param charset The value of the charset attribute to match. May be null.
* *
* @return A Source object suitable for passing to the TransformerFactory. * @return A <code>Source</code> <code>Object</code> suitable for passing
* * to the <code>TransformerFactory</code>.
* @throws TransformerConfigurationException. *
* @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( public abstract Source getAssociatedStylesheet(
Source source, String media, String title, String charset) Source source,
throws TransformerConfigurationException; String media,
String title,
String charset)
throws TransformerConfigurationException;
/** /**
* Set an object that is used by default during the transformation * Set an object that is used by default during the transformation
* to resolve URIs used in xsl:import, or xsl:include. * to resolve URIs used in document(), xsl:import, or xsl:include.
* *
* @param resolver An object that implements the URIResolver interface, * @param resolver An object that implements the URIResolver interface,
* or null. * or null.
@ -236,12 +237,61 @@ public abstract class TransformerFactory {
//======= CONFIGURATION METHODS ======= //======= 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. * Look up the value of a feature.
* *
* <p>The feature name is any absolute URI.</p> * <p>
* @param name The feature name, which is an absolute URI. * Feature names are fully qualified {@link java.net.URI}s.
* @return The current state of the feature (true or false). * 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); public abstract boolean getFeature(String name);
@ -249,36 +299,35 @@ public abstract class TransformerFactory {
* Allows the user to set specific attributes on the underlying * Allows the user to set specific attributes on the underlying
* implementation. An attribute in this context is defined to * implementation. An attribute in this context is defined to
* be an option that the implementation provides. * 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 name The name of the attribute.
* @param value The value 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) public abstract void setAttribute(String name, Object value);
throws IllegalArgumentException;
/** /**
* Allows the user to retrieve specific attributes on the underlying * Allows the user to retrieve specific attributes on the underlying
* implementation. * implementation.
* An <code>IllegalArgumentException</code> is thrown if the underlying
* implementation doesn't recognize the attribute.
*
* @param name The name of the attribute. * @param name The name of the attribute.
* @return value The value 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) public abstract Object getAttribute(String name);
throws IllegalArgumentException;
/** /**
* Set the error event listener for the TransformerFactory, which * Set the error event listener for the TransformerFactory, which
* is used for the processing of transformation instructions, * is used for the processing of transformation instructions,
* and not for the transformation itself. * 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. * @param listener The new error listener.
* @throws IllegalArgumentException if listener is null.
*/ */
public abstract void setErrorListener(ErrorListener listener) public abstract void setErrorListener(ErrorListener listener);
throws IllegalArgumentException;
/** /**
* Get the error event handler for the TransformerFactory. * Get the error event handler for the TransformerFactory.
@ -286,4 +335,6 @@ public abstract class TransformerFactory {
* @return The current error handler, which should never be null. * @return The current error handler, which should never be null.
*/ */
public abstract ErrorListener getErrorListener(); public abstract ErrorListener getErrorListener();
} }

View File

@ -1,56 +1,21 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform; package javax.xml.transform;
/** /**
@ -61,6 +26,10 @@ package javax.xml.transform;
*/ */
public class TransformerFactoryConfigurationError extends Error { public class TransformerFactoryConfigurationError extends Error {
/**
* <code>Exception</code> for the
* <code>TransformerFactoryConfigurationError</code>.
*/
private Exception exception; private Exception exception;
/** /**
@ -108,7 +77,6 @@ public class TransformerFactoryConfigurationError extends Error {
* @param e The exception to be encapsulated in a * @param e The exception to be encapsulated in a
* TransformerFactoryConfigurationError * TransformerFactoryConfigurationError
* @param msg The detail message. * @param msg The detail message.
* @param e The exception to be wrapped in a TransformerFactoryConfigurationError
*/ */
public TransformerFactoryConfigurationError(Exception e, String msg) { public TransformerFactoryConfigurationError(Exception e, String msg) {

View File

@ -1,56 +1,21 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform; package javax.xml.transform;
/** /**
@ -64,8 +29,8 @@ public interface URIResolver {
* an xsl:include, xsl:import, or document() function. * an xsl:include, xsl:import, or document() function.
* *
* @param href An href attribute, which may be relative or absolute. * @param href An href attribute, which may be relative or absolute.
* @param base The base URI in effect when the href attribute * @param base The base URI against which the first argument will be made
* was encountered. * absolute if the absolute URI is required.
* *
* @return A Source object, or null if the href cannot be resolved, * @return A Source object, or null if the href cannot be resolved,
* and the processor should try to resolve the URI itself. * and the processor should try to resolve the URI itself.

View File

@ -1,56 +1,21 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform.dom; package javax.xml.transform.dom;
import javax.xml.transform.SourceLocator; import javax.xml.transform.SourceLocator;

View File

@ -1,143 +1,309 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform.dom; package javax.xml.transform.dom;
import javax.xml.transform.*; import javax.xml.transform.Result;
import org.w3c.dom.Node; import org.w3c.dom.Node;
/** /**
* Acts as a holder for a transformation result tree, in the * <p>Acts as a holder for a transformation result tree in the form of a Document Object Model (DOM) tree.</p>
* form of a Document Object Model (DOM) tree. If no output DOM source is set, *
* the transformation will create a Document node as the holder * <p>If no output DOM source is set, the transformation will create a Document node as the holder for the result of the transformation,
* for the result of the transformation, which may be retrieved * which may be retrieved with {@link #getNode()}.</p>
* with getNode. *
* @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision$, $Date$
*/ */
public class DOMResult implements Result { public class DOMResult implements Result {
/** If {@link javax.xml.transform.TransformerFactory#getFeature} /** <p>If {@link javax.xml.transform.TransformerFactory#getFeature}
* returns true when passed this value as an argument, * returns <code>true</code> when passed this value as an argument,
* the Transformer supports Result output of this type. * the <code>Transformer</code> supports <code>Result</code> output of this type.</p>
*/ */
public static final String FEATURE = public static final String FEATURE = "http://javax.xml.transform.dom.DOMResult/feature";
"http://javax.xml.transform.dom.DOMResult/feature";
/** /**
* Zero-argument default constructor. * <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() {} public DOMResult() {
setNode(null);
setNextSibling(null);
setSystemId(null);
}
/** /**
* Use a DOM node to create a new output target. In practice, * <p>Use a DOM node to create a new output target.</p>
* the node should be a {@link org.w3c.dom.Document} node, *
* a {@link org.w3c.dom.DocumentFragment} node, or a * <p>In practice, the node should be
* {@link org.w3c.dom.Element} node. In other words, a node * a {@link org.w3c.dom.Document} node,
* that accepts children. * a {@link org.w3c.dom.DocumentFragment} node, or
* a {@link org.w3c.dom.Element} node.
* In other words, a node that accepts children.</p>
* *
* @param n The DOM node that will contain the result tree. * <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) { public DOMResult(Node node) {
setNode(node); setNode(node);
setNextSibling(null);
setSystemId(null);
} }
/** /**
* Create a new output target with a DOM node. In practice, * <p>Use a DOM node to create a new output target with the specified System ID.<p>
* the node should be a {@link org.w3c.dom.Document} node, *
* a {@link org.w3c.dom.DocumentFragment} node, or a * <p>In practice, the node should be
* {@link org.w3c.dom.Element} node. In other words, a node * a {@link org.w3c.dom.Document} node,
* that accepts children. * 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 node The DOM node that will contain the result tree.
* @param systemID The system identifier which may be used in association * @param systemId The system identifier which may be used in association with this node.
* with this node.
*/ */
public DOMResult(Node node, String systemID) { public DOMResult(Node node, String systemId) {
setNode(node); setNode(node);
setSystemId(systemID); setNextSibling(null);
setSystemId(systemId);
} }
/** /**
* Set the node that will contain the result DOM tree. In practice, * <p>Use a DOM node to create a new output target specifying the child node where the result nodes should be inserted before.</p>
* the node should be a {@link org.w3c.dom.Document} node, *
* <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>.
* @throws IllegalArgumentException If <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 * a {@link org.w3c.dom.DocumentFragment} node, or a
* {@link org.w3c.dom.Element} node. In other words, a node * {@link org.w3c.dom.Element} node.
* that accepts children. * In other words, a node that accepts children.</p>
* *
* @param node The node to which the transformation * <p>Use <code>nextSibling</code> to specify the child node
* will be appended. * 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>.
* @throws IllegalArgumentException If <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>.
* @throws IllegalStateException If <code>node</code> is <code>null</code> and
* <code>nextSibling</code> is not <code>null</code>.
*/ */
public void setNode(Node node) { 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; this.node = node;
} }
/** /**
* Get the node that will contain the result DOM tree. * <p>Get the node that will contain the result DOM tree.</p>
* If no node was set via setNode, the node will be *
* set by the transformation, and may be obtained from * <p>If no node was set via
* this method once the transformation is complete. * {@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 * @return The node to which the transformation will be appended.
* will be appended.
*/ */
public Node getNode() { public Node getNode() {
return node; return node;
} }
/** /**
* Method setSystemId Set the systemID that may be used in association * <p>Set the child node before which the result nodes will be inserted.</p>
* with the node. *
* <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. * @param systemId The system identifier as a URI string.
*/ */
@ -146,10 +312,15 @@ public class DOMResult implements Result {
} }
/** /**
* Get the system identifier that was set with setSystemId. * <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 that was set with setSystemId, or null * @return The system identifier.
* if setSystemId was not called.
*/ */
public String getSystemId() { public String getSystemId() {
return systemId; return systemId;
@ -160,13 +331,19 @@ public class DOMResult implements Result {
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
/** /**
* The node to which the transformation will be appended. * <p>The node to which the transformation will be appended.</p>
*/ */
private Node node; private Node node = null;
/** /**
* The systemID that may be used in association * <p>The child node before which the result nodes will be inserted.</p>
* with the node. *
* @since 1.5
*/ */
private String systemId; private Node nextSibling = null;
/**
* <p>The System ID that may be used in association with the node.</p>
*/
private String systemId = null;
} }

View File

@ -1,71 +1,53 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform.dom; package javax.xml.transform.dom;
import javax.xml.transform.*; import javax.xml.transform.Source;
import org.w3c.dom.Node; import org.w3c.dom.Node;
/** /**
* Acts as a holder for a transformation Source tree in the * <p>Acts as a holder for a transformation Source tree in the
* form of a Document Object Model (DOM) tree. * 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>
* @version $Revision$, $Date$
* @see <a href="http://www.w3.org/TR/DOM-Level-2">Document Object Model (DOM) Level 2 Specification</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 { 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} /** If {@link javax.xml.transform.TransformerFactory#getFeature}
* returns true when passed this value as an argument, * returns true when passed this value as an argument,
* the Transformer supports Source input of this type. * the Transformer supports Source input of this type.
@ -74,12 +56,15 @@ public class DOMSource implements Source {
"http://javax.xml.transform.dom.DOMSource/feature"; "http://javax.xml.transform.dom.DOMSource/feature";
/** /**
* Zero-argument default constructor. If this is used, and * <p>Zero-argument default constructor. If this constructor is used, and
* no DOM source is set, then the Transformer will * no DOM source is set using {@link #setNode(Node node)} , then the
* create an empty source Document using * <code>Transformer</code> will
* {@link javax.xml.parsers.DocumentBuilder#newDocument}. * 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() {} public DOMSource() { }
/** /**
* Create a new input source with a DOM node. The operation * Create a new input source with a DOM node. The operation
@ -128,10 +113,10 @@ public class DOMSource implements Source {
* Set the base ID (URL or system ID) from where URLs * Set the base ID (URL or system ID) from where URLs
* will be resolved. * will be resolved.
* *
* @param baseID Base URL for this DOM tree. * @param systemID Base URL for this DOM tree.
*/ */
public void setSystemId(String baseID) { public void setSystemId(String systemID) {
this.baseID = baseID; this.systemID = systemID;
} }
/** /**
@ -141,21 +126,6 @@ public class DOMSource implements Source {
* @return Base URL for this DOM tree. * @return Base URL for this DOM tree.
*/ */
public String getSystemId() { public String getSystemId() {
return this.baseID; return this.systemID;
} }
//////////////////////////////////////////////////////////////////////
// Internal state.
//////////////////////////////////////////////////////////////////////
/**
* Field node
*/
private Node node;
/**
* The base ID (URL or system ID) from where URLs
* will be resolved.
*/
String baseID;
} }

View File

@ -134,11 +134,10 @@
(DOM) Level 2 Specification</A>.</p> (DOM) Level 2 Specification</A>.</p>
</li> </li>
<li> <li>
<p> <p>
<b>SAX</b> <b>SAX</b><br>
<br>Simple API for XML, specifically referring to the Simple API for XML, specifically referring to the <a href="http://sax.sourceforge.net/">SAX 2.0.2 release</a>.
<A href="#http://www.megginson.com/SAX/SAX2">SAX 2.0 </p>
release</A>.</p>
</li> </li>
</ul> </ul>

View File

@ -1,177 +1,201 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <?xml version="1.0"?>
<html> <!-- $Id$ -->
<!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> <head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>javax.xml.transform</title> <title>javax.xml.transform</title>
</head> </head>
<body> <body>
<p>This package defines the generic APIs for processing transformation <p>This package defines the generic APIs for processing transformation
instructions, and performing a transformation from source to result. These 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 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 few assumptions as possible about the details of the source and result of a
transformation. It achieves this by defining transformation. It achieves this by defining
{@link javax.xml.transform.Source} and {@link javax.xml.transform.Source} and
{@link javax.xml.transform.Result} interfaces.</p> {@link javax.xml.transform.Result} interfaces.
<p>To define concrete classes for the user, the API defines specializations </p>
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}.
<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>
<code>
<pre> TransformerFactory tfactory = TransformerFactory.newInstance();
if (tfactory.getFeature(DOMSource.FEATURE) &amp;&amp; tfactory.getFeature(StreamResult.FEATURE)) <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},
}</pre> 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> </code>
</pre>
<h3> <h3>
<a name="qname-delimiter">Qualified Name Representation</a> <a name="qname-delimiter">Qualified Name Representation</a>
</h3> </h3>
<p> <p><a href="http://www.w3.org/TR/REC-xml-names">Namespaces</a>
<A href="http://www.w3.org/TR/REC-xml-names">Namespaces</A> present something of a problem area when dealing with XML objects. Qualified
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
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
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"
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.
among Java programs, one must provide a means to map "xyz" to a namespace. </p>
</p>
<p>One solution has been to create a "QName" object that holds the <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 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 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 in a dictionary object. Not having a string representation also makes it
difficult to specify a namespaced identity outside the context of an XML difficult to specify a namespaced identity outside the context of an XML
document.</p> document.
</p>
<p>In order to pass namespaced values to transformations, for instance
as a set of properties to the Serializer, this specification defines that a <p>In order to pass namespaced values to transformations,
String "qname" object parameter be passed as two-part string, the namespace URI for
enclosed in curly braces ({}), followed by the local name. If the qname has a instance when setting a property or a parameter on a
null URI, then the String object only contains the local name. An application {@link javax.xml.transform.Transformer} object,
can safely check for a non-null URI by testing to see if the first character of this specification defines that a
the name is a '{' character.</p> 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 <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;, 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". then the Qualified Name would be "{http://xyz.foo.com/yada/baz.html}foo".
Note that the prefix is lost.</p> Note that the prefix is lost.
</p>
<h3>Result Tree Serialization</h3> <h3>Result Tree Serialization</h3>
<p>Serialization of the result tree to a stream can be controlled with <p>Serialization of the result tree to a stream can be controlled with
the {@link javax.xml.transform.Transformer#setOutputProperties} and the the {@link javax.xml.transform.Transformer#setOutputProperties} and the
{@link javax.xml.transform.Transformer#setOutputProperty} methods. {@link javax.xml.transform.Transformer#setOutputProperty} methods.
Strings that match the <A href="http://www.w3.org/TR/xslt#output">XSLT These properties only apply to stream results, they have no effect when
specification for xsl:output attributes</A> can be referenced from the the result is a DOM tree or SAX event stream.</p>
{@link javax.xml.transform.OutputKeys} class. Other strings can be
specified as well. If the transformer does not recognize an output key, a <p>Strings that match the <a href="http://www.w3.org/TR/xslt#output">XSLT
{@link java.lang.IllegalArgumentException} is thrown, unless the specification for xsl:output attributes</a> can be referenced from the
key name is <A href="#qname-delimiter">namespace qualified</A>. Output key names that are {@link javax.xml.transform.OutputKeys} class. Other strings can be
qualified by a namespace are ignored or passed on to the serializer specified as well.
mechanism.</p> 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 <p>If all that is desired is the simple identity transformation of a
source to a result, then {@link javax.xml.transform.TransformerFactory} source to a result, then {@link javax.xml.transform.TransformerFactory}
provides a provides a
{@link javax.xml.transform.TransformerFactory#newTransformer()} method {@link javax.xml.transform.TransformerFactory#newTransformer()} method
with no arguments. This method creates a Transformer that effectively copies 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 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> events or to create an XML or HTML stream from a DOM or SAX events. </p>
<h3>Exceptions and Error Reporting</h3> <h3>Exceptions and Error Reporting</h3>
<p>The transformation API throw three types of specialized exceptions. A <p>The transformation API throw three types of specialized exceptions. A
{@link javax.xml.transform.TransformerFactoryConfigurationError} is parallel to {@link javax.xml.transform.TransformerFactoryConfigurationError} is parallel to
the {@link javax.xml.parsers.FactoryConfigurationError}, and is thrown the {@link javax.xml.parsers.FactoryConfigurationError}, and is thrown
when a configuration problem with the TransformerFactory exists. This error when a configuration problem with the TransformerFactory exists. This error
will typically be thrown when the transformation factory class specified with will typically be thrown when the transformation factory class specified with
the "javax.xml.transform.TransformerFactory" system property cannot be found or the "javax.xml.transform.TransformerFactory" system property cannot be found or
instantiated.</p> instantiated.</p>
<p>A {@link javax.xml.transform.TransformerConfigurationException} <p>A {@link javax.xml.transform.TransformerConfigurationException}
may be thrown if for any reason a Transformer can not be created. A 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 TransformerConfigurationException may be thrown if there is a syntax error in
the transformation instructions, for example when the transformation instructions, for example when
{@link javax.xml.transform.TransformerFactory#newTransformer} is {@link javax.xml.transform.TransformerFactory#newTransformer} is
called.</p> called.</p>
<p>{@link javax.xml.transform.TransformerException} is a general <p>{@link javax.xml.transform.TransformerException} is a general
exception that occurs during the course of a transformation. A transformer exception that occurs during the course of a transformation. A transformer
exception may wrap another exception, and if any of the exception may wrap another exception, and if any of the
{@link javax.xml.transform.TransformerException#printStackTrace()} {@link javax.xml.transform.TransformerException#printStackTrace()}
methods are called on it, it will produce a list of stack dumps, starting from methods are called on it, it will produce a list of stack dumps, starting from
the most recent. The transformer exception also provides a the most recent. The transformer exception also provides a
{@link javax.xml.transform.SourceLocator} object which indicates where {@link javax.xml.transform.SourceLocator} object which indicates where
in the source tree or transformation instructions the error occurred. in the source tree or transformation instructions the error occurred.
{@link javax.xml.transform.TransformerException#getMessageAndLocation()} {@link javax.xml.transform.TransformerException#getMessageAndLocation()}
may be called to get an error message with location info, and may be called to get an error message with location info, and
{@link javax.xml.transform.TransformerException#getLocationAsString()} {@link javax.xml.transform.TransformerException#getLocationAsString()}
may be called to get just the location string.</p> may be called to get just the location string.</p>
<p>Transformation warnings and errors are normally first sent to a <p>Transformation warnings and errors are sent to an
{@link javax.xml.transform.ErrorListener}, at which point the {@link javax.xml.transform.ErrorListener}, at which point the
implementor may decide to report the error or warning, and may decide to throw application may decide to report the error or warning, and may decide to throw
an exception for a non-fatal error. The error listener may be set via an <code>Exception</code> for a non-fatal error. The <code>ErrorListener</code> may be set via
{@link javax.xml.transform.TransformerFactory#setErrorListener} for {@link javax.xml.transform.TransformerFactory#setErrorListener} for
reporting errors that have to do with syntax errors in the transformation reporting errors that have to do with syntax errors in the transformation
instructions, or via instructions, or via
{@link javax.xml.transform.Transformer#setErrorListener} to report {@link javax.xml.transform.Transformer#setErrorListener} to report
errors that occur during the transformation. The error listener on both objects errors that occur during the transformation. The <code>ErrorListener</code> on both objects
should always be valid and non-null, whether set by the user or a default will always be valid and non-<code>null</code>, whether set by the application or a default
implementation provided by the processor.</p> 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> <h3>Resolution of URIs within a transformation</h3>
<p>The API provides a way for URIs referenced from within the stylesheet <p>The API provides a way for URIs referenced from within the stylesheet
instructions or within the transformation to be resolved by the calling instructions or within the transformation to be resolved by the calling
application. This can be done by creating a class that implements the 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} interface, with its one method,
{@link javax.xml.transform.URIResolver#resolve}, and use this class to {@link javax.xml.transform.URIResolver#resolve}, and use this class to
set the URI resolution for the transformation instructions or transformation set the URI resolution for the transformation instructions or transformation
with {@link javax.xml.transform.TransformerFactory#setURIResolver} or with {@link javax.xml.transform.TransformerFactory#setURIResolver} or
{@link javax.xml.transform.Transformer#setURIResolver}. The {@link javax.xml.transform.Transformer#setURIResolver}. The
<code>URIResolver.resolve</code> method takes two String arguments, the URI found in 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 stylesheet instructions or built as part of the transformation process, and the
base URI in effect when the URI passed as the first argument was encountered. base URI
The returned {@link javax.xml.transform.Source} object must be usable by against which the first argument will be made absolute if the
the transformer, as specified in its implemented features.</p> 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> </body>
</html> </html>

View File

@ -1,66 +1,32 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform.sax; package javax.xml.transform.sax;
import javax.xml.transform.*; import javax.xml.transform.Result;
import org.xml.sax.ContentHandler; import org.xml.sax.ContentHandler;
import org.xml.sax.ext.LexicalHandler; import org.xml.sax.ext.LexicalHandler;
/** /**
* Acts as an holder for a transformation Result. * <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 { public class SAXResult implements Result {
@ -75,7 +41,8 @@ public class SAXResult implements Result {
/** /**
* Zero-argument default constructor. * Zero-argument default constructor.
*/ */
public SAXResult() {} public SAXResult() {
}
/** /**
* Create a SAXResult that targets a SAX2 {@link org.xml.sax.ContentHandler}. * Create a SAXResult that targets a SAX2 {@link org.xml.sax.ContentHandler}.

View File

@ -1,67 +1,40 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform.sax; package javax.xml.transform.sax;
import javax.xml.transform.Source; import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamSource;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
/** /**
* Acts as an holder for SAX-style Source. * <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>
* @version $Revision$, $Date$
*/ */
public class SAXSource implements Source { public class SAXSource implements Source {
@ -74,12 +47,16 @@ public class SAXSource implements Source {
"http://javax.xml.transform.sax.SAXSource/feature"; "http://javax.xml.transform.sax.SAXSource/feature";
/** /**
* Zero-argument default constructor. If this constructor * <p>Zero-argument default constructor. If this constructor is used, and
* is used, and no other method is called, the * no SAX source is set using
* {@link javax.xml.transform.Transformer} * {@link #setInputSource(InputSource inputSource)} , then the
* assumes an empty input tree, with a default root node. * <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() {} public SAXSource() { }
/** /**
* Create a <code>SAXSource</code>, using an {@link org.xml.sax.XMLReader} * Create a <code>SAXSource</code>, using an {@link org.xml.sax.XMLReader}
@ -173,26 +150,33 @@ public class SAXSource implements Source {
} }
/** /**
* Get the base ID (URI or system ID) from where URIs * <p>Get the base ID (URI or system ID) from where URIs
* will be resolved. * will be resolved.</p>
* *
* @return Base URL for the Source, or null. * @return Base URL for the <code>Source</code>, or <code>null</code>.
*/ */
public String getSystemId() { public String getSystemId() {
return (null != inputSource) if (inputSource == null) {
? inputSource.getSystemId() return null;
: null; } else {
return inputSource.getSystemId();
}
} }
/** The XMLReader to be used for the source tree input. May be null. */ /**
* The XMLReader to be used for the source tree input. May be null.
*/
private XMLReader reader; private XMLReader reader;
/** The SAX InputSource to be used for the source tree input. Should not be null. */ /**
* <p>The SAX InputSource to be used for the source tree input.
* Should not be <code>null<code>.</p>
*/
private InputSource inputSource; private InputSource inputSource;
/** /**
* Attempt to obtain a SAX InputSource object from a TrAX Source * Attempt to obtain a SAX InputSource object from a Source
* object. * object.
* *
* @param source Must be a non-null Source reference. * @param source Must be a non-null Source reference.

View File

@ -1,63 +1,27 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform.sax; package javax.xml.transform.sax;
import javax.xml.transform.*; import javax.xml.transform.*;
import org.xml.sax.XMLFilter; import org.xml.sax.XMLFilter;
/** /**
* This class extends TransformerFactory to provide SAX-specific * This class extends TransformerFactory to provide SAX-specific
* factory methods. It provides two types of ContentHandlers, * factory methods. It provides two types of ContentHandlers,

View File

@ -1,63 +1,27 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform.sax; package javax.xml.transform.sax;
import javax.xml.transform.*; import javax.xml.transform.*;
import org.xml.sax.ContentHandler; import org.xml.sax.ContentHandler;
/** /**
* A SAX ContentHandler that may be used to process SAX * A SAX ContentHandler that may be used to process SAX
* parse events (parsing transformation instructions) into a Templates object. * parse events (parsing transformation instructions) into a Templates object.
@ -84,7 +48,7 @@ public interface TemplatesHandler extends ContentHandler {
* resolve relative URIs in the stylesheet. This must be * resolve relative URIs in the stylesheet. This must be
* called before the startDocument event. * called before the startDocument event.
* *
* @param baseID Base URI for this stylesheet. * @param systemID Base URI for this stylesheet.
*/ */
public void setSystemId(String systemID); public void setSystemId(String systemID);

View File

@ -1,65 +1,29 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform.sax; package javax.xml.transform.sax;
import javax.xml.transform.Result; import javax.xml.transform.Result;
import javax.xml.transform.Transformer; import javax.xml.transform.Transformer;
import org.xml.sax.ContentHandler; import org.xml.sax.ContentHandler;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.DTDHandler; import org.xml.sax.DTDHandler;
import org.xml.sax.ext.LexicalHandler;
/** /**
* A TransformerHandler * A TransformerHandler
@ -70,10 +34,11 @@ public interface TransformerHandler
extends ContentHandler, LexicalHandler, DTDHandler { extends ContentHandler, LexicalHandler, DTDHandler {
/** /**
* Enables the user of the TransformerHandler to set the * <p>Set the <code>Result</code> associated with this
* to set the Result for the transformation. * <code>TransformerHandler</code> to be used for the transformation.</p>
* *
* @param result A Result instance, should not be null. * @param result A <code>Result</code> instance, should not be
* <code>null<code>.
* *
* @throws IllegalArgumentException if result is invalid for some reason. * @throws IllegalArgumentException if result is invalid for some reason.
*/ */
@ -94,8 +59,11 @@ public interface TransformerHandler
public String getSystemId(); public String getSystemId();
/** /**
* Get the Transformer associated with this handler, which * <p>Get the <code>Transformer</code> associated with this handler, which
* is needed in order to set parameters and output properties. * is needed in order to set parameters and output properties.</p>
*
* @return <code>Transformer</code> associated with this
* <code>TransformerHandler</code>.
*/ */
public Transformer getTransformer(); public Transformer getTransformer();
} }

View File

@ -1,69 +1,35 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform.stream; package javax.xml.transform.stream;
import javax.xml.transform.*; import javax.xml.transform.Result;
import java.io.File;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.Writer; import java.io.Writer;
import java.io.File; import java.net.MalformedURLException;
/** /**
* Acts as an holder for a transformation result, * <p>Acts as an holder for a transformation result,
* which may be XML, plain Text, HTML, or some other form of markup. * 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 { public class StreamResult implements Result {
@ -77,7 +43,8 @@ public class StreamResult implements Result {
/** /**
* Zero-argument default constructor. * Zero-argument default constructor.
*/ */
public StreamResult() {} public StreamResult() {
}
/** /**
* Construct a StreamResult from a byte stream. Normally, * Construct a StreamResult from a byte stream. Normally,
@ -181,19 +148,39 @@ public class StreamResult implements Result {
} }
/** /**
* Set the system ID from a File reference. * <p>Set the system ID from a <code>File</code> reference.</p>
*
* <p>Note the use of {@link File#toURI()} and {@link File#toURL()}.
* <code>toURI()</code> is prefered and used if possible.
* To allow JAXP 1.3 to run on J2SE 1.3, <code>toURL()</code>
* is used if a {@link NoSuchMethodException} is thrown by the attempt
* to use <code>toURI()</code>.</p>
* *
* @param f Must a non-null File reference. * @param f Must a non-null File reference.
*/ */
public void setSystemId(File f) { public void setSystemId(File f) {
String fpath=f.getAbsolutePath();
if (File.separatorChar != '/') { try {
fpath = fpath.replace(File.separatorChar, '/'); // assume >= 1.4
} this.systemId = f.toURI().toString();
if( fpath.startsWith("/")) } catch (java.lang.NoSuchMethodError nme) {
this.systemId= "file://" + fpath; // running on J2SE 1.3?
else try {
this.systemId = "file:///" + fpath; this.systemId = f.toURL().toString();
} catch (MalformedURLException malformedURLException) {
this.systemId = null;
throw new RuntimeException(
"javax.xml.transform.stream.StreamResult#setSystemId(File f) with MalformedURLException: "
+ malformedURLException.toString()
);
}
} catch (Exception exception) {
throw new RuntimeException(
"javax.xml.transform.stream.StreamResult#setSystemId(File f):"
+ " unexpected Exception: " + exception.toString()
);
}
} }
/** /**

View File

@ -1,69 +1,38 @@
/* /*
* The Apache Software License, Version 1.1 * Copyright 2003-2004 The Apache Software Foundation.
* *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* *
* Copyright (c) 2001 The Apache Software Foundation. All rights * http://www.apache.org/licenses/LICENSE-2.0
* reserved.
* *
* Redistribution and use in source and binary forms, with or without * Unless required by applicable law or agreed to in writing, software
* modification, are permitted provided that the following conditions * distributed under the License is distributed on an "AS IS" BASIS,
* are met: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* 1. Redistributions of source code must retain the above copyright * limitations under the License.
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The name "Apache Software Foundation" must not be used to endorse or
* promote products derived from this software without prior written
* permission. For written permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/ */
// $Id$
package javax.xml.transform.stream; package javax.xml.transform.stream;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import javax.xml.transform.Source; import javax.xml.transform.Source;
import java.io.InputStream;
import java.io.Reader;
import java.io.File;
/** /**
* Acts as an holder for a transformation Source in the form * <p>Acts as an holder for a transformation Source in the form
* of a stream of XML markup. * 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>
* @version $Revision$, $Date$
*/ */
public class StreamSource implements Source { public class StreamSource implements Source {
@ -73,13 +42,19 @@ public class StreamSource implements Source {
*/ */
public static final String FEATURE = public static final String FEATURE =
"http://javax.xml.transform.stream.StreamSource/feature"; "http://javax.xml.transform.stream.StreamSource/feature";
/** /**
* Zero-argument default constructor. If this constructor * <p>Zero-argument default constructor. If this constructor is used, and
* is used, and no other method is called, the transformer * no Stream source is set using
* will assume an empty input tree, with a default root node. * {@link #setInputStream(java.io.InputStream inputStream)} or
*/ * {@link #setReader(java.io.Reader reader)}, then the
public StreamSource() {} * <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, * Construct a StreamSource from a byte stream. Normally,
@ -268,14 +243,14 @@ public class StreamSource implements Source {
* @param f Must a non-null File reference. * @param f Must a non-null File reference.
*/ */
public void setSystemId(File f) { public void setSystemId(File f) {
String fpath=f.getAbsolutePath(); String fpath=f.getAbsolutePath();
if (File.separatorChar != '/') { if (File.separatorChar != '/') {
fpath = fpath.replace(File.separatorChar, '/'); fpath = fpath.replace(File.separatorChar, '/');
} }
if( fpath.startsWith("/")) if( fpath.startsWith("/"))
this.systemId= "file://" + fpath; this.systemId= "file://" + fpath;
else else
this.systemId = "file:///" + fpath; this.systemId = "file:///" + fpath;
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////

View File

@ -0,0 +1,91 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
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>
* @version $Revision$, $Date$
* @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.
*
* @return
* Always return a non-null valid object.
*/
public abstract Validator newValidator();
/**
* Creates a new {@link ValidatorHandler} for this {@link Schema}.
*
* @return
* Always return a non-null valid object.
*/
public abstract ValidatorHandler newValidatorHandler();
}

View File

@ -0,0 +1,644 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
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 <tt>synchronized</tt> 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>
* @version $Revision$, $Date$
* @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 <tt>schemLanguage</tt> parameter is null.
*/
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(schemaLanguage);
}
return f;
}
/**
* <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).
* @exception org.xml.sax.SAXNotRecognizedException If the feature
* value can't be assigned or retrieved.
* @exception org.xml.sax.SAXNotSupportedException When the
* {@link SchemaFactory} recognizes the feature name but
* cannot determine its value at this time.
* @exception NullPointerException
* if 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 SchemaFactory}
* parses schemas, although {@link SchemaFactory}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 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).
*
* @exception org.xml.sax.SAXNotRecognizedException If the feature
* value can't be assigned or retrieved.
* @exception org.xml.sax.SAXNotSupportedException When the
* {@link SchemaFactory} recognizes the feature name but
* cannot set the requested value.
* @exception NullPointerException
* if 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 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.
* @exception org.xml.sax.SAXNotRecognizedException If the property
* value can't be assigned or retrieved.
* @exception org.xml.sax.SAXNotSupportedException When the
* {@link SchemaFactory} recognizes the property name but
* cannot set the requested value.
* @exception NullPointerException
* if 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 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.
* @exception org.xml.sax.SAXNotRecognizedException If the property
* value can't be assigned or retrieved.
* @exception org.xml.sax.SAXNotSupportedException When the
* XMLReader recognizes the property name but
* cannot determine its value at this time.
* @exception NullPointerException
* if 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);
}
/**
* 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 null.
*/
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 <tt>&lt;include></tt>d or <tt>&lt;import></tt>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 <tt>schema</tt> 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 <tt>schema</tt> 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 <tt>schema</tt> 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 <tt>schemas.length!=1</tt>.
*
*
* @param schemas
* inputs to be parsed. {@link SchemaFactory} is required
* to recognize {@link javax.xml.transform.sax.SAXSource},
* {@link StreamSource}, and {@link javax.xml.transform.dom.DOMSource}.
*
* @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 depends
* on the schema language that this {@link SchemaFactory} is created
* for.
*
* <p>
* Also, implementations are allowed to use implementation-specific
* property/feature to alter the semantics of this method.
*
*
* <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,397 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
package javax.xml.validation;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
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>
* @version $Revision$, $Date$
* @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 <tt>schemaLanguage</tt> 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 = loadFromProperty(schemaLanguage,resource.toExternalForm(),resource.openStream());
sf = loadFromProperty(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("org.apache.xerces.jaxp.validation.xs.SchemaFactoryImpl");
}
debugPrintln("all things were tried, but none was found. bailing out.");
return null;
}
/**
* <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.
*/
private SchemaFactory createInstance( String className ) {
try {
debugPrintln("instanciating "+className);
Class clazz;
if( classLoader!=null )
clazz = classLoader.loadClass(className);
else
clazz = Class.forName(className);
if(debug) debugPrintln("loaded it from "+which(clazz));
Object o = clazz.newInstance();
if( o instanceof SchemaFactory )
return (SchemaFactory)o;
debugPrintln(className+" is not assignable to "+SERVICE_CLASS.getName());
} catch( Throwable t ) {
debugPrintln("failed to instanciate "+className);
if(debug) t.printStackTrace();
}
return null;
}
/** 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;
}
}
/**
* 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,153 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
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) { }
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.getSystemResource(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.getSystemResources(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,180 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
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>
* @version $Revision$, $Date$
* @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 of
* the {@link org.xml.sax.ContentHandler} that the application sets to the
* {@link ValidatorHandler}.</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}.
*
* @param index
* The index of the attribute. The same index for
* the {@link org.xml.sax.Attributes} object passed to the
* <tt>startElement</tt> 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 <tt>true</tt> 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
* <tt>startElement</tt> 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 <tt>false</tt> 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
* <tt>startElement</tt> callback.
*
* @throws IndexOutOfBoundsException
* If the index is invalid.
* @throws IllegalStateException
* If this method is called from other {@link org.xml.sax.ContentHandler}
* methods.
*
* @return
* <tt>true</tt> if the attribute was present before the validator
* processes input. <tt>false</tt> if the attribute was added
* by the validator.
*/
public abstract boolean isSpecified(int index);
}

View File

@ -0,0 +1,424 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
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 is a thread-unsafe and non-reentrant object.
* 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 <tt>validate</tt>
* method is invoked, applications may not recursively call
* the <tt>validate</tt> method.
* <p>
*
* Note that while the {@link #validate(javax.xml.transform.Source)} and {@link #validate(javax.xml.transform.Source, javax.xml.transform.Result)}
* methods take a {@link Source} instance, the <code>Source</code>
* instance must be a <code>SAXSource</code> or <code>DOMSource</code>.
*
* @author <a href="mailto:Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
* @version $Revision$, $Date$
* @since 1.5
*/
public abstract class Validator {
/**
* Constructor for derived classes.
*
* <p>
* The constructor does nothing.
*
* <p>
* Derived classes must create {@link Validator} objects that have
* <tt>null</tt> {@link ErrorHandler} and
* <tt>null</tt> {@link LSResourceResolver}.
*/
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 of:
* <pre>
* validate(source,null);
* </pre>
*
* @see #setErrorHandler(ErrorHandler)
*/
public void validate(Source source) throws SAXException, IOException {
validate(source, null);
}
/**
* Validates the specified input and send the augmented validation
* result to the specified output.
*
* <p>
* This method places the following restrictions on the types of
* the {@link Source}/{@link Result} accepted.
*
* <h4>{@link Source}/{@link Result} accepted:</h4>
* <table border=1>
* <thead>
* <tr>
* <td></td>
* <td>{@link javax.xml.transform.sax.SAXSource}</td>
* <td>{@link javax.xml.transform.dom.DOMSource}</td>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td><tt>null</tt></td>
* <td>OK</td>
* <td>OK</td>
* </tr>
* <tr>
* <td>{@link javax.xml.transform.sax.SAXResult}</td>
* <td>OK</td>
* <td>Err</td>
* </tr>
* <tr>
* <td>{@link javax.xml.transform.dom.DOMResult}</td>
* <td>Err</td>
* <td>OK</td>
* </tr>
* </tbody>
* </table>
*
* <p>
* <strong>Note that {@link javax.xml.transform.stream.StreamSource} instances are not allowed.</strong> To process
* a <code>StreamSource</code>, or to validate one {@link Source} into another kind of {@link Result}, use the identity transformer
* (see {@link javax.xml.transform.TransformerFactory#newTransformer()}).
*
* <p>
* Errors found during the validation is sent to the specified
* {@link ErrorHandler}.
*
* <p>
* If a document is valid, or if a document contains some errors
* but none of them were fatal and the {@link ErrorHandler} didn't
* throw any exception, then the method returns normally.
*
* @param source
* XML to be validated. Must not be null.
*
* @param result
* The {@link Result} object that receives (possibly augmented)
* XML. This parameter can be null if the caller is not interested
* in it.
*
* Note that when a {@link javax.xml.transform.dom.DOMResult} is used,
* a validator might just pass the same DOM node from
* {@link javax.xml.transform.dom.DOMSource} to
* {@link javax.xml.transform.dom.DOMResult}
* (in which case <tt>source.getNode()==result.getNode()</tt>),
* it might copy the entire DOM tree, or it might alter the
* node given by the source.
*
* @throws IllegalArgumentException
* If the {@link Result} type doesn't match the {@link Source} type,
* or if the specified source is neither
* {@link javax.xml.transform.sax.SAXSource} nor
* {@link javax.xml.transform.dom.DOMSource}.
*
* @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 the <tt>source</tt> parameter is null.
*
* @see #validate(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).
* @exception org.xml.sax.SAXNotRecognizedException If the feature
* value can't be assigned or retrieved.
* @exception org.xml.sax.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 property 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).
*
* @exception org.xml.sax.SAXNotRecognizedException If the feature
* value can't be assigned or retrieved.
* @exception org.xml.sax.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.
* @exception org.xml.sax.SAXNotRecognizedException If the property
* value can't be assigned or retrieved.
* @exception org.xml.sax.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.
* @exception org.xml.sax.SAXNotRecognizedException If the property
* value can't be assigned or retrieved.
* @exception org.xml.sax.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,449 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
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 a thread-unsafe, non-reentrant object.
* 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>
* @version $Revision$, $Date$
* @since 1.5
*/
public abstract class ValidatorHandler implements ContentHandler {
/**
* Constructor for derived classes.
*
* <p>
* The constructor does nothing.
*
* <p>
* Derived classes must create {@link ValidatorHandler} objects that have
* <tt>null</tt> {@link ErrorHandler} and
* <tt>null</tt> {@link LSResourceResolver}.
*/
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).
* @exception org.xml.sax.SAXNotRecognizedException If the feature
* value can't be assigned or retrieved.
* @exception org.xml.sax.SAXNotSupportedException When the
* {@link ValidatorHandler} 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();
throw new SAXNotRecognizedException(name);
}
/**
* Set the value of a feature flag.
*
* <p>
* Feature can be used to control the way a {@link ValidatorHandler}
* parses schemas, although {@link ValidatorHandler}s are not required
* to recognize any specific property names.</p>
*
* <p>The feature name is any fully-qualified URI. It is
* possible for a {@link ValidatorHandler} 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).
*
* @exception org.xml.sax.SAXNotRecognizedException If the feature
* value can't be assigned or retrieved.
* @exception org.xml.sax.SAXNotSupportedException When the
* {@link ValidatorHandler} 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();
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.
*
* @exception org.xml.sax.SAXNotRecognizedException If the property
* value can't be assigned or retrieved.
* @exception org.xml.sax.SAXNotSupportedException When the
* {@link ValidatorHandler} 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();
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.
* @exception org.xml.sax.SAXNotRecognizedException If the property
* value can't be assigned or retrieved.
* @exception org.xml.sax.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();
throw new SAXNotRecognizedException(name);
}
}

View File

@ -0,0 +1,152 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
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.getSystemResource(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.getSystemResources(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,298 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
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>
*
* <table id="XPath-evaluation" 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>
*
* @author <a href="Norman.Walsh@Sun.com">Norman Walsh</a>
* @author <a href="Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision$, $Date$
* @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> 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 (node or node list, 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 (node or node list, 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,77 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
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>
* @version $Revision$, $Date$
* @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";
}

View File

@ -0,0 +1,98 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
package javax.xml.xpath;
import java.io.PrintWriter;
/**
* <code>XPathException</code> represents a generic XPath exception.</p>
*
* @author <a href="Norman.Walsh@Sun.com">Norman Walsh</a>
* @author <a href="mailto:Jeff.Suttor@Sun.COM">Jeff Suttor</a>
* @version $Revision$, $Date$
* @since 1.5
*/
public class XPathException extends Exception {
private final Throwable cause;
/**
* <p>Stream Unique Identifier.</p>
*/
private static final long serialVersionUID = -1837080260374986980L;
/**
* <p>Constructs a new <code>XPathException</code> with the specified detail <code>message</code>.</p>
*
* <p>The <code>cause</code> is not initialized.</p>
*
* <p>If <code>message</code> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</p>
*
* @param message The detail message.
*/
public XPathException(String message) {
super(message);
if ( message == null ) {
throw new NullPointerException ( "message can't be null");
}
this.cause = null;
}
/**
* <p>Constructs a new <code>XPathException</code> with the specified <code>cause</code>.</p>
*
* <p>If <code>cause</code> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</p>
*
* @param cause The cause.
*
* @throws NullPointerException if <code>cause</code> is <code>null</code>.
*/
public XPathException(Throwable cause) {
super();
this.cause = cause;
if ( cause == null ) {
throw new NullPointerException ( "cause can't be null");
}
}
public Throwable getCause() {
return cause;
}
public void printStackTrace( java.io.PrintStream s ) {
if( getCause() != null ) {
getCause().printStackTrace(s);
s.println("--------------- linked to ------------------");
}
super.printStackTrace(s);
}
public void printStackTrace() {
printStackTrace(System.err);
}
public void printStackTrace(PrintWriter s) {
if( getCause() != null ) {
getCause().printStackTrace(s);
s.println("--------------- linked to ------------------");
}
super.printStackTrace(s);
}
}

View File

@ -0,0 +1,184 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
package javax.xml.xpath;
import org.xml.sax.InputSource;
import javax.xml.namespace.QName;
/**
* <p><code>XPathExpression</code> provides access to compiled XPath expressions.</p>
*
* <table id="XPathExpression-evaluation" 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}.
* 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}.
* 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.
* </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>
*
* @author <a href="mailto:Norman.Walsh@Sun.com">Norman Walsh</a>
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision$, $Date$
* @see <a href="http://www.w3.org/TR/xpath#section-Expressions">XML Path Language (XPath) Version 1.0, Expressions</a>
* @since 1.5
*/
public interface XPathExpression {
/**
* <p>Evaluate the compiled XPath expression in the specified context and return the result as the specified type.</p>
*
* <p>See <a href="#XPathExpression-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 a <code>null</code> value is provided for
* <code>item</code>, an empty document will be used for the
* context.
* If <code>returnType</code> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</p>
*
* @param item The starting context (node or node list, for example).
* @param returnType The desired return type.
*
* @return The <code>Object</code> that is the result of evaluating the expression and converting the result to
* <code>returnType</code>.
*
* @throws XPathExpressionException If the expression cannot be evaluated.
* @throws IllegalArgumentException If <code>returnType</code> is not one of the types defined in {@link XPathConstants}.
* @throws NullPointerException If <code>returnType</code> is <code>null</code>.
*/
public Object evaluate(Object item, QName returnType)
throws XPathExpressionException;
/**
* <p>Evaluate the compiled XPath expression in the specified context and return the result as a <code>String</code>.</p>
*
* <p>This method calls {@link #evaluate(Object item, QName returnType)} with a <code>returnType</code> of
* {@link XPathConstants#STRING}.</p>
*
* <p>See <a href="#XPathExpression-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.
*
* @param item The starting context (node or node list, 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 the expression cannot be evaluated.
*/
public String evaluate(Object item)
throws XPathExpressionException;
/**
* <p>Evaluate the compiled 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(Object item, QName returnType)} on the resulting document object.</p>
*
* <p>See <a href="#XPathExpression-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>source</code> or <code>returnType</code> is <code>null</code>,
* then a <code>NullPointerException</code> is thrown.</p>
*
* @param source The <code>InputSource</code> of the document to evaluate over.
* @param returnType The desired return type.
*
* @return The <code>Object</code> that is the result of evaluating the expression and converting the result to
* <code>returnType</code>.
*
* @throws XPathExpressionException If the expression cannot be evaluated.
* @throws IllegalArgumentException If <code>returnType</code> is not one of the types defined in {@link XPathConstants}.
* @throws NullPointerException If <code>source</code> or <code>returnType</code> is <code>null</code>.
*/
public Object evaluate(InputSource source, QName returnType)
throws XPathExpressionException;
/**
* <p>Evaluate the compiled 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(InputSource source, QName returnType)} with a <code>returnType</code> of
* {@link XPathConstants#STRING}.</p>
*
* <p>See <a href="#XPathExpression-evaluation">Evaluation of XPath Expressions</a> for context item evaluation,
* variable, function and QName resolution and return type conversion.</p>
*
* <p>If <code>source</code> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</p>
*
* @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 the expression cannot be evaluated.
* @throws NullPointerException If <code>source</code> is <code>null</code>.
*/
public String evaluate(InputSource source)
throws XPathExpressionException;
}

View File

@ -0,0 +1,60 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
package javax.xml.xpath;
/**
* <code>XPathExpressionException</code> represents an error in an XPath expression.</p>
*
* @author <a href="mailto:Norman.Walsh@Sun.com">Norman Walsh</a>
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision$, $Date$
* @since 1.5
*/
public class XPathExpressionException extends XPathException {
/**
* <p>Stream Unique Identifier.</p>
*/
private static final long serialVersionUID = -1837080260374986980L;
/**
* <p>Constructs a new <code>XPathExpressionException</code> with the specified detail <code>message</code>.</p>
*
* <p>The <code>cause</code> is not initialized.</p>
*
* <p>If <code>message</code> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</p>
*
* @param message The detail message.
*/
public XPathExpressionException(String message) {
super(message);
}
/**
* <p>Constructs a new <code>XPathExpressionException</code> with the specified <code>cause</code>.</p>
*
* <p>If <code>cause</code> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</p>
*
* @param cause The cause.
*
* @throws NullPointerException if <code>cause</code> is <code>null</code>.
*/
public XPathExpressionException(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,267 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
package javax.xml.xpath;
/**
* <p>An <code>XPathFactory</code> instance can be used to create
* {@link javax.xml.xpath.XPath} objects.</p>
*
*<p>See {@link #newInstance(String uri)} for lookup mechanism.</p>
*
* @author <a href="mailto:Norman.Walsh@Sun.com">Norman Walsh</a>
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision$, $Date$
* @since 1.5
*/
public abstract class XPathFactory {
/**
* <p>The default property name according to the JAXP spec.</p>
*/
public static final String DEFAULT_PROPERTY_NAME = "javax.xml.xpath.XPathFactory";
/**
* <p>Default Object Model URI.</p>
*/
public static final String DEFAULT_OBJECT_MODEL_URI = "http://java.sun.com/jaxp/xpath/dom";
/**
*<p> Take care of restrictions imposed by java security model </p>
*/
private static SecuritySupport ss = new SecuritySupport() ;
/**
* <p>Protected constructor as {@link #newInstance()} or {@link #newInstance(String uri)}
* should be used to create a new instance of an <code>XPathFactory</code>.</p>
*/
protected XPathFactory() {
}
/**
* <p>Get a new <code>XPathFactory</code> instance using the default object model,
* {@link #DEFAULT_OBJECT_MODEL_URI},
* the W3C DOM.</p>
*
* <p>This method is functionally equivalent to:</p>
* <pre>
* newInstance(DEFAULT_OBJECT_MODEL_URI)
* </pre>
*
* <p>Since the implementation for the W3C DOM is always available, this method will never fail.</p>
*
* @return Instance of an <code>XPathFactory</code>.
*/
public static final XPathFactory newInstance() {
try {
return newInstance(DEFAULT_OBJECT_MODEL_URI);
} catch (XPathFactoryConfigurationException xpathFactoryConfigurationException) {
throw new RuntimeException(
"XPathFactory#newInstance() failed to create an XPathFactory for the default object model: "
+ DEFAULT_OBJECT_MODEL_URI
+ " with the XPathFactoryConfigurationException: "
+ xpathFactoryConfigurationException.toString()
);
}
}
/**
* <p>Get a new <code>XPathFactory</code> instance using the specified object model.</p>
*
* <p>To find a <code>XPathFactory</code> object,
* 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 {@link #DEFAULT_PROPERTY_NAME} + ":uri" is present,
* where uri 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>
* ${java.home}/lib/jaxp.properties 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>
* The class loader is asked for service provider provider-configuration files matching <code>javax.xml.xpath.XPathFactory</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:
* <pre>
* {@link #isObjectModelSupported(String objectModel)}
* </pre>
* The first service provider found in class loader order that supports the specified object model is returned.
* </li>
* <li>
* Platform default <code>XPathFactory</code> is located in a platform specific way.
* There must be a platform default XPathFactory for the W3C DOM, i.e. {@link #DEFAULT_OBJECT_MODEL_URI}.
* </li>
* </ol>
* <p>If everything fails, an <code>XPathFactoryConfigurationException</code> will be thrown.</p>
*
* <p>Tip for Trouble-shooting:</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 the URIs are properly escaped in it.
* For example:</p>
* <pre>
* http\://java.sun.com/jaxp/xpath/dom=org.acme.DomXPathFactory
* </pre>
*
* @param uri Identifies the underlying object model.
* The specification only defines the URI {@link #DEFAULT_OBJECT_MODEL_URI},
* <code>http://java.sun.com/jaxp/xpath/dom</code> for the W3C DOM,
* the org.w3c.dom package, and implementations are free to introduce other URIs for other object models.
*
* @return Instance of an <code>XPathFactory</code>.
*
* @throws XPathFactoryConfigurationException If the specified object model is unavailable.
* @throws NullPointerException If <code>uri</code> is <code>null</code>.
* @throws IllegalArgumentException If <code>uri.length() == 0</code>.
*/
public static final XPathFactory newInstance(final String uri)
throws XPathFactoryConfigurationException {
if (uri == null) {
throw new NullPointerException(
"XPathFactory#newInstance(String uri) cannot be called with uri == null"
);
}
if (uri.length() == 0) {
throw new IllegalArgumentException(
"XPathFactory#newInstance(String uri) cannot be called with uri == \"\""
);
}
ClassLoader classLoader = ss.getContextClassLoader();
if (classLoader == null) {
//use the current class loader
classLoader = XPathFactory.class.getClassLoader();
}
XPathFactory xpathFactory = new XPathFactoryFinder(classLoader).newFactory(uri);
if (xpathFactory == null) {
throw new XPathFactoryConfigurationException(
"No XPathFctory implementation found for the object model: "
+ uri
);
}
return xpathFactory;
}
/**
* <p>Is specified object model supported by this <code>XPathFactory</code>?</p>
*
* @param objectModel Specifies the object model which the returned <code>XPathFactory</code> will understand.
*
* @return <code>true</code> if <code>XPathFactory</code> supports <code>objectModel</code>, else <code>false</code>.
*
* @throws NullPointerException If <code>objectModel</code> is <code>null</code>.
* @throws IllegalArgumentException If <code>objectModel.length() == 0</code>.
*/
public abstract boolean isObjectModelSupported(String objectModel);
/**
* <p>Set a feature for this <code>XPathFactory</code> and <code>XPath</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 XPathFactoryConfigurationException} is thrown if this <code>XPathFactory</code> or the <code>XPath</code>s
* it creates cannot support the feature.
* It is possible for an <code>XPathFactory</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 <code>true</code>, any reference to an external function is an error.
* Under these conditions, the implementation must not call the {@link XPathFunctionResolver}
* and must throw an {@link XPathFunctionException}.
* </p>
*
* @param name Feature name.
* @param value Is feature state <code>true</code> or <code>false</code>.
*
* @throws XPathFactoryConfigurationException if this <code>XPathFactory</code> or the <code>XPath</code>s
* it creates cannot support this feature.
* @throws NullPointerException if <code>name</code> is <code>null</code>.
*/
public abstract void setFeature(String name, boolean value)
throws XPathFactoryConfigurationException;
/**
* <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 XPathFactoryConfigurationException} is thrown if this <code>XPathFactory</code> or the <code>XPath</code>s
* it creates cannot support the feature.
* It is possible for an <code>XPathFactory</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 XPathFactoryConfigurationException if this <code>XPathFactory</code> or the <code>XPath</code>s
* it creates cannot support this feature.
* @throws NullPointerException if <code>name</code> is <code>null</code>.
*/
public abstract boolean getFeature(String name)
throws XPathFactoryConfigurationException;
/**
* <p>Establish a default variable resolver.</p>
*
* <p>Any <code>XPath</code> objects constructed from this factory will use
* the specified resolver by default.</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 abstract void setXPathVariableResolver(XPathVariableResolver resolver);
/**
* <p>Establish a default function resolver.</p>
*
* <p>Any <code>XPath</code> objects constructed from this factory will use
* the specified resolver by default.</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 abstract void setXPathFunctionResolver(XPathFunctionResolver resolver);
/**
* <p>Return a new <code>XPath</code> using the underlying object
* model determined when the <code>XPathFactory</code> was instantiated.</p>
*
* @return New instance of an <code>XPath</code>.
*/
public abstract XPath newXPath();
}

View File

@ -0,0 +1,60 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
package javax.xml.xpath;
/**
* <code>XPathFactoryConfigurationException</code> represents a configuration error in a <code>XPathFactory</code> environment.</p>
*
* @author <a href="mailto:Norman.Walsh@Sun.com">Norman Walsh</a>
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision$, $Date$
* @since 1.5
*/
public class XPathFactoryConfigurationException extends XPathException {
/**
* <p>Stream Unique Identifier.</p>
*/
private static final long serialVersionUID = -1837080260374986980L;
/**
* <p>Constructs a new <code>XPathFactoryConfigurationException</code> with the specified detail <code>message</code>.</p>
*
* <p>The <code>cause</code> is not initialized.</p>
*
* <p>If <code>message</code> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</p>
*
* @param message The detail message.
*/
public XPathFactoryConfigurationException(String message) {
super(message);
}
/**
* <p>Constructs a new <code>XPathFactoryConfigurationException</code> with the specified <code>cause</code>.</p>
*
* <p>If <code>cause</code> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</p>
*
* @param cause The cause.
*
* @throws NullPointerException if <code>cause</code> is <code>null</code>.
*/
public XPathFactoryConfigurationException(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,372 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
package javax.xml.xpath;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
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 XPathFactory#newInstance(String)}.
*
* @author <a href="Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
* @version $Revision$, $Date$
* @since 1.5
*/
class XPathFactoryFinder {
private static SecuritySupport ss = new SecuritySupport() ;
/** debug support code. */
private static boolean debug = false;
static {
// Use try/catch block to support applets
try {
debug = ss.getSystemProperty("jaxp.debug") != null;
} catch (Exception _) {
debug = false;
}
}
/**
* <p>Cache properties for performance.</p>
*/
private static Properties cacheProps = new Properties();
/**
* <p>First time requires initialization overhead.</p>
*/
private static boolean firstTime = true;
/**
* <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 XPathFactoryFinder(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 XPathFactory} object for the specified
* schema language.</p>
*
* @param uri
* Identifies the underlying object model.
*
* @return <code>null</code> if the callee fails to create one.
*
* @throws NullPointerException
* If the parameter is null.
*/
public XPathFactory newFactory(String uri) {
if(uri==null) throw new NullPointerException();
XPathFactory f = _newFactory(uri);
if (f != null) {
debugPrintln("factory '" + f.getClass().getName() + "' was found for " + uri);
} else {
debugPrintln("unable to find a factory for " + uri);
}
return f;
}
/**
* <p>Lookup a {@link XPathFactory} for the given object model.</p>
*
* @param uri identifies the object model.
*
* @return {@link XPathFactory} for the given object model.
*/
private XPathFactory _newFactory(String uri) {
XPathFactory sf;
String propertyName = SERVICE_CLASS.getName() + ":" + uri;
// 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 META-INF/services files
Iterator sitr = createServiceFileIterator();
while(sitr.hasNext()) {
URL resource = (URL)sitr.next();
debugPrintln("looking into " + resource);
try {
//sf = loadFromProperty(uri,resource.toExternalForm(),resource.openStream());
sf = loadFromProperty(uri,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(uri.equals(XPathFactory.DEFAULT_OBJECT_MODEL_URI)) {
debugPrintln("attempting to use the platform default W3C DOM XPath lib");
return createInstance("org.apache.xpath.jaxp.XPathFactoryImpl");
}
debugPrintln("all things were tried, but none was found. bailing out.");
return null;
}
/**
* <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.
*/
private XPathFactory createInstance( String className ) {
try {
debugPrintln("instanciating "+className);
Class clazz;
if( classLoader!=null )
clazz = classLoader.loadClass(className);
else
clazz = Class.forName(className);
if(debug) debugPrintln("loaded it from "+which(clazz));
Object o = clazz.newInstance();
if( o instanceof XPathFactory )
return (XPathFactory)o;
debugPrintln(className+" is not assignable to "+SERVICE_CLASS.getName());
} catch( Throwable t ) {
debugPrintln("failed to instanciate "+className);
if(debug) t.printStackTrace();
}
return null;
}
/** 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 XPathFactory 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;
}
}
/**
* 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 = XPathFactoryFinder.class.getClassLoader();
return ss.getResourceAsURL(classLoader, SERVICE_ID);
//return (ClassLoader.getSystemResource( 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 = XPathFactory.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,50 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
package javax.xml.xpath;
import java.util.List;
/**
* <p><code>XPathFunction</code> provides access to XPath functions.</p>
*
* <p>Functions are identified by QName and arity in XPath.</p>
*
* @author <a href="mailto:Norman.Walsh@Sun.com">Norman Walsh</a>
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision$, $Date$
* @since 1.5
*/
public interface XPathFunction {
/**
* <p>Evaluate the function with the specified arguments.</p>
*
* <p>To the greatest extent possible, side-effects should be avoided in the
* definition of extension functions. The implementation evaluating an
* XPath expression is under no obligation to call extension functions in
* any particular order or any particular number of times.</p>
*
* @param args The arguments, <code>null</code> is a valid value.
*
* @return The result of evaluating the <code>XPath</code> function as an <code>Object</code>.
*
* @throws XPathFunctionException If <code>args</code> cannot be evaluated with this <code>XPath</code> function.
*/
public Object evaluate(List args)
throws XPathFunctionException;
}

View File

@ -0,0 +1,60 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
package javax.xml.xpath;
/**
* <code>XPathFunctionException</code> represents an error with an XPath function.</p>
*
* @author <a href="mailto:Norman.Walsh@Sun.com">Norman Walsh</a>
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision$, $Date$
* @since 1.5
*/
public class XPathFunctionException extends XPathExpressionException {
/**
* <p>Stream Unique Identifier.</p>
*/
private static final long serialVersionUID = -1837080260374986980L;
/**
* <p>Constructs a new <code>XPathFunctionException</code> with the specified detail <code>message</code>.</p>
*
* <p>The <code>cause</code> is not initialized.</p>
*
* <p>If <code>message</code> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</p>
*
* @param message The detail message.
*/
public XPathFunctionException(String message) {
super(message);
}
/**
* <p>Constructs a new <code>XPathFunctionException</code> with the specified <code>cause</code>.</p>
*
* <p>If <code>cause</code> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</p>
*
* @param cause The cause.
*
* @throws NullPointerException if <code>cause</code> is <code>null</code>.
*/
public XPathFunctionException(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,59 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
package javax.xml.xpath;
import javax.xml.namespace.QName;
/**
* <p><code>XPathFunctionResolver</code> provides access to the set of user defined <code>XPathFunction</code>s.</p>
*
* <p>XPath functions are resolved by name and arity.
* The resolver is not needed for XPath built-in functions and the resolver
* <strong><em>cannot</em></strong> be used to override those functions.</p>
*
* <p>In particular, the resolver is only called for functions in an another
* namespace (functions with an explicit prefix). This means that you cannot
* use the <code>XPathFunctionResolver</code> to implement specifications
* like <a href="http://www.w3.org/TR/xmldsig-core/">XML-Signature Syntax
* and Processing</a> which extend the function library of XPath 1.0 in the
* same namespace. This is a consequence of the design of the resolver.</p>
*
* <p>If you wish to implement additional built-in functions, you will have to
* extend the underlying implementation directly.</p>
*
* @author <a href="mailto:Norman.Walsh@Sun.com">Norman Walsh</a>
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision$, $Date$
* @see <a href="http://www.w3.org/TR/xpath#corelib">XML Path Language (XPath) Version 1.0, Core Function Library</a>
* @since 1.5
*/
public interface XPathFunctionResolver {
/**
* <p>Find a function in the set of available functions.</p>
*
* <p>If <code>functionName</code> or <code>arity</code> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</p>
*
* @param functionName The function name.
* @param arity The number of arguments that the returned function must accept.
*
* @return The function or <code>null</code> if no function named <code>functionName</code> with <code>arity</code> arguments exists.
*
* @throws NullPointerException If <code>functionName</code> or <code>arity</code> is <code>null</code>.
*/
public XPathFunction resolveFunction(QName functionName, int arity);
}

View File

@ -0,0 +1,50 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// $Id$
package javax.xml.xpath;
import javax.xml.namespace.QName;
/**
* <p><code>XPathVariableResolver</code> provides access to the set of user defined XPath variables.</p>
*
* <p>The <code>XPathVariableResolver</code> and the XPath evaluator must adhere to a contract that
* cannot be directly enforced by the API. Although variables may be mutable,
* that is, an application may wish to evaluate the same XPath expression more
* than once with different variable values, in the course of evaluating any
* single XPath expression, a variable's value <strong><em>must</em></strong> be immutable.</p>
*
* @author <a href="mailto:Norman.Walsh@Sun.com">Norman Walsh</a>
* @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
* @version $Revision$, $Date$
* @since 1.5
*/
public interface XPathVariableResolver {
/**
* <p>Find a variable in the set of available variables.</p>
*
* <p>If <code>variableName</code> is <code>null</code>, then a <code>NullPointerException</code> is thrown.</p>
*
* @param variableName The <code>QName</code> of the variable name.
*
* @return The variables value, or <code>null</code> if no variable named <code>variableName</code>
* exists. The value returned must be of a type appropriate for the underlying object model.
*
* @throws NullPointerException If <code>variableName</code> is <code>null</code>.
*/
public Object resolveVariable(QName variableName);
}