Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   * Copyright (c) 1997-2013 Oracle and/or its affiliates. All rights reserved.
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License.  You can
  * obtain a copy of the License at
  * or packager/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at packager/legal/LICENSE.txt.
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [year] [name of copyright owner]"
  * Contributor(s):
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
 import org.xml.sax.*;
 import java.util.*;

Vivek Pandey
 public class DOMForest {
To correctly feed documents to a schema parser, we need to remember which documents (of the forest) were given as the root documents, and which of them are read as included/imported documents.

Set of system ids as strings.

     protected final Set<StringrootDocuments = new HashSet<String>();

Contains wsdl:import(s)
     protected final Set<StringexternalReferences = new HashSet<String>();

actual data storage map<SystemId,Document>.
     protected final Map<StringDocumentcore = new HashMap<StringDocument>();
     protected final ErrorReceiver errorReceiver;
     private final DocumentBuilder documentBuilder;
    private final SAXParserFactory parserFactory;

inlined schema elements inside wsdl:type section
    protected final List<ElementinlinedSchemaElements = new ArrayList<Element>();

Stores location information for all the trees in this forest.
    public final LocatorTable locatorTable = new LocatorTable();
    protected final EntityResolver entityResolver;
Stores all the outer-most <jaxb:bindings> customizations.
    public final Set<ElementouterMostBindings = new HashSet<Element>();

Schema language dependent part of the processing.
    protected final InternalizationLogic logic;
    protected final WsimportOptions options;
    public DOMForest(InternalizationLogic logic, @NotNull EntityResolver entityResolverWsimportOptions optionsErrorReceiver errReceiver) {
        this. = options;
        this. = entityResolver;
        this. = errReceiver;
        this. = logic;
        try {
            // secure xml processing can be switched off if input requires it
            boolean secureProcessingEnabled = options == null || !options.disableSecureXmlProcessing;
            DocumentBuilderFactory dbf = XmlUtil.newDocumentBuilderFactory(secureProcessingEnabled);
            this. = dbf.newDocumentBuilder();
            this. = XmlUtil.newSAXParserFactory(secureProcessingEnabled);
        } catch (ParserConfigurationException e) {
            throw new AssertionError(e);
    public List<ElementgetInlinedSchemaElement() {
        return ;
    public @NotNull Document parse(InputSource sourceboolean rootthrows SAXExceptionIOException {
        if (source.getSystemId() == null)
            throw new IllegalArgumentException();
        return parse(source.getSystemId(), sourceroot);

Parses an XML at the given location ( and XMLs referenced by it) into DOM trees and stores them to this forest.

the parsed DOM document object.
    public Document parse(String systemIdboolean rootthrows SAXExceptionIOException{
        systemId = normalizeSystemId(systemId);
        InputSource is = null;
        // allow entity resolver to find the actual byte stream.
        is = .resolveEntity(nullsystemId);
        if (is == null)
            is = new InputSource(systemId);
        else {
        if (.containsKey(systemId)) {
            // this document has already been parsed. Just ignore.
            return .get(systemId);
        // but we still use the original system Id as the key.
        return parse(systemIdisroot);
    protected Map<String,StringresolvedCache = new HashMap<String,String>();
        return ;
Parses the given document and add it to the DOM forest.

null if there was a parse error. otherwise non-null.
    private @NotNull Document parse(String systemIdInputSource inputSourceboolean rootthrows SAXExceptionIOException{
        Document dom = .newDocument();
        systemId = normalizeSystemId(systemId);
        // put into the map before growing a tree, to
        // prevent recursive reference from causing infinite loop.
        if (root)
        try {
            XMLReader reader = createReader(dom);
            InputStream is = null;
            if(inputSource.getByteStream() == null){
                inputSource = .resolveEntity(nullsystemId);
            Element doc = dom.getDocumentElement();
            if (doc == null) {
                return null;
            NodeList schemas = doc.getElementsByTagNameNS(."schema");
            for (int i = 0; i < schemas.getLength(); i++) {
        } catch (ParserConfigurationException e) {
            throw new SAXException(e.getMessage());
        return dom;
    public void addExternalReferences(String ref) {
        if (!.contains(ref))
    public Set<StringgetExternalReferences() {
        return ;
    public interface Handler extends ContentHandler {
Gets the DOM that was built.
        public Document getDocument();

Returns a org.xml.sax.XMLReader to parse a document into this DOM forest.

This version requires that the DOM object to be created and registered to the map beforehand.

        XMLReader reader = .newSAXParser().getXMLReader();
        DOMBuilder dombuilder = new DOMBuilder(dom);
        try {
        } catch(SAXException e) {
        ContentHandler handler = new WhitespaceStripper(dombuilder);
        handler = new VersionChecker(handler);
        // insert the reference finder so that
        // included/imported schemas will be also parsed
        if ( != null)
        if ( != null)
        return reader;
    private String normalizeSystemId(String systemId) {
        try {
            systemId = new URI(systemId).normalize().toString();
        } catch (URISyntaxException e) {
            // leave the system ID untouched. In my experience URI is often too strict
        return systemId;
    boolean isExtensionMode() {
        return .isExtensionMode();

Gets the DOM tree associated with the specified system ID, or null if none is found.
    public Document get(String systemId) {
        Document doc = .get(systemId);
        if (doc == null && systemId.startsWith("file:/") && !systemId.startsWith("file://")) {
            // As of JDK1.4, method returns URLs like
            // "file:/abc/def/ghi" which is an incorrect file protocol URL according to RFC1738.
            // Some other correctly functioning parts return the correct URLs ("file:///abc/def/ghi"),
            // and this descripancy breaks DOM look up by system ID.
            // this extra check solves this problem.
            doc = .get("file://" + systemId.substring(5));
        if (doc == null && systemId.startsWith("file:")) {
            // on Windows, filenames are case insensitive.
            // perform case-insensitive search for improved user experience
            String systemPath = getPath(systemId);
            for (String key : .keySet()) {
                if (key.startsWith("file:") && getPath(key).equalsIgnoreCase(systemPath)) {
                    doc = .get(key);
        return doc;

Strips off the leading 'file:///' portion from an URL.
    private String getPath(String key) {
        key = key.substring(5); // skip 'file:'
        while (key.length() > 0 && key.charAt(0) == '/')
            key = key.substring(1);
        return key;

Gets all the system IDs of the documents.
    public String[] listSystemIDs() {
        return .keySet().toArray(new String[.keySet().size()]);

Gets the system ID from which the given DOM is parsed.

Poor-man's base URI.

    public String getSystemId(Document dom) {
        for (Map.Entry<StringDocumente : .entrySet()) {
            if (e.getValue() == dom)
                return e.getKey();
        return null;

Gets the first one (which is more or less random) in rootDocuments.
    public String getFirstRootDocument() {
        if(.isEmpty()) return null;
        return .iterator().next();
    public Set<StringgetRootDocuments() {
        return ;

Dumps the contents of the forest to the specified stream.

This is a debug method. As such, error handling is sloppy.

    public void dump(OutputStream outthrows IOException {
        try {
            // create identity transformer
            // secure xml processing can be switched off if input requires it
            boolean secureProcessingEnabled =  == null || !.;
            TransformerFactory tf = XmlUtil.newTransformerFactory(secureProcessingEnabled);
            Transformer it = tf.newTransformer();
            for (Map.Entry<StringDocumente : .entrySet()) {
                out.write(("---<< " + e.getKey() + '\n').getBytes());
                DataWriter dw = new DataWriter(new OutputStreamWriter(out), null);
                dw.setIndentStep("  ");
                it.transform(new DOMSource(e.getValue()),
                        new SAXResult(dw));
        } catch (TransformerException e) {
New to GrepCode? Check out our FAQ X