325N/A/*
325N/A * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
325N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
325N/A *
325N/A * This code is free software; you can redistribute it and/or modify it
325N/A * under the terms of the GNU General Public License version 2 only, as
325N/A * published by the Free Software Foundation. Oracle designates this
325N/A * particular file as subject to the "Classpath" exception as provided
325N/A * by Oracle in the LICENSE file that accompanied this code.
325N/A *
325N/A * This code is distributed in the hope that it will be useful, but WITHOUT
325N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
325N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
325N/A * version 2 for more details (a copy is included in the LICENSE file that
325N/A * accompanied this code).
325N/A *
325N/A * You should have received a copy of the GNU General Public License version
325N/A * 2 along with this work; if not, write to the Free Software Foundation,
325N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
325N/A *
325N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
325N/A * or visit www.oracle.com if you need additional information or have any
325N/A * questions.
325N/A */
325N/A
325N/Apackage com.sun.tools.internal.ws.wsdl.parser;
325N/A
325N/Aimport com.sun.istack.internal.NotNull;
325N/Aimport com.sun.tools.internal.ws.resources.WscompileMessages;
325N/Aimport com.sun.tools.internal.ws.wscompile.AbortException;
325N/Aimport com.sun.tools.internal.ws.wscompile.DefaultAuthenticator;
325N/Aimport com.sun.tools.internal.ws.wscompile.ErrorReceiver;
325N/Aimport com.sun.tools.internal.ws.wscompile.WsimportOptions;
325N/Aimport com.sun.tools.internal.ws.wsdl.document.schema.SchemaConstants;
325N/Aimport com.sun.tools.internal.xjc.reader.internalizer.LocatorTable;
325N/Aimport com.sun.xml.internal.bind.marshaller.DataWriter;
325N/Aimport com.sun.xml.internal.ws.util.JAXWSUtils;
325N/Aimport org.w3c.dom.Document;
325N/Aimport org.w3c.dom.Element;
325N/Aimport org.w3c.dom.NodeList;
325N/Aimport org.xml.sax.ContentHandler;
325N/Aimport org.xml.sax.*;
325N/Aimport org.xml.sax.helpers.XMLFilterImpl;
325N/A
325N/Aimport javax.xml.parsers.DocumentBuilder;
325N/Aimport javax.xml.parsers.DocumentBuilderFactory;
325N/Aimport javax.xml.parsers.ParserConfigurationException;
325N/Aimport javax.xml.parsers.SAXParserFactory;
325N/Aimport javax.xml.transform.Transformer;
325N/Aimport javax.xml.transform.TransformerException;
325N/Aimport javax.xml.transform.TransformerFactory;
325N/Aimport javax.xml.transform.dom.DOMSource;
325N/Aimport javax.xml.transform.sax.SAXResult;
325N/Aimport javax.net.ssl.HttpsURLConnection;
325N/Aimport javax.net.ssl.HostnameVerifier;
325N/Aimport javax.net.ssl.SSLSession;
325N/Aimport java.io.IOException;
325N/Aimport java.io.InputStream;
325N/Aimport java.io.OutputStream;
325N/Aimport java.io.OutputStreamWriter;
325N/Aimport java.net.*;
325N/Aimport java.util.*;
325N/A
325N/A/**
325N/A * @author Vivek Pandey
325N/A */
325N/Apublic class DOMForest {
325N/A /**
325N/A * To correctly feed documents to a schema parser, we need to remember
325N/A * which documents (of the forest) were given as the root
325N/A * documents, and which of them are read as included/imported
325N/A * documents.
325N/A * <p/>
325N/A * <p/>
325N/A * Set of system ids as strings.
325N/A */
325N/A protected final Set<String> rootDocuments = new HashSet<String>();
325N/A
325N/A /**
325N/A * Contains wsdl:import(s)
325N/A */
325N/A protected final Set<String> externalReferences = new HashSet<String>();
325N/A
325N/A /**
325N/A * actual data storage map&lt;SystemId,Document>.
325N/A */
325N/A protected final Map<String, Document> core = new HashMap<String, Document>();
325N/A protected final ErrorReceiver errorReceiver;
325N/A
325N/A private final DocumentBuilder documentBuilder;
325N/A private final SAXParserFactory parserFactory;
325N/A
325N/A /**
325N/A * inlined schema elements inside wsdl:type section
325N/A */
325N/A protected final List<Element> inlinedSchemaElements = new ArrayList<Element>();
325N/A
325N/A
325N/A /**
325N/A * Stores location information for all the trees in this forest.
325N/A */
325N/A public final LocatorTable locatorTable = new LocatorTable();
325N/A
325N/A protected final EntityResolver entityResolver;
325N/A /**
325N/A * Stores all the outer-most &lt;jaxb:bindings> customizations.
325N/A */
325N/A public final Set<Element> outerMostBindings = new HashSet<Element>();
325N/A
325N/A /**
325N/A * Schema language dependent part of the processing.
325N/A */
325N/A protected final InternalizationLogic logic;
325N/A protected final WsimportOptions options;
325N/A
325N/A public DOMForest(InternalizationLogic logic, @NotNull EntityResolver entityResolver, WsimportOptions options, ErrorReceiver errReceiver) {
325N/A this.options = options;
325N/A this.entityResolver = entityResolver;
325N/A this.errorReceiver = errReceiver;
325N/A this.logic = logic;
325N/A try {
325N/A DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
325N/A dbf.setNamespaceAware(true);
325N/A this.documentBuilder = dbf.newDocumentBuilder();
325N/A
325N/A this.parserFactory = SAXParserFactory.newInstance();
325N/A this.parserFactory.setNamespaceAware(true);
325N/A } catch (ParserConfigurationException e) {
325N/A throw new AssertionError(e);
325N/A }
325N/A }
325N/A
325N/A public List<Element> getInlinedSchemaElement() {
325N/A return inlinedSchemaElements;
325N/A }
325N/A
325N/A public @NotNull Document parse(InputSource source, boolean root) throws SAXException, IOException {
325N/A if (source.getSystemId() == null)
325N/A throw new IllegalArgumentException();
325N/A return parse(source.getSystemId(), source, root);
325N/A }
325N/A
325N/A /**
325N/A * Parses an XML at the given location (
325N/A * and XMLs referenced by it) into DOM trees
325N/A * and stores them to this forest.
325N/A *
325N/A * @return the parsed DOM document object.
325N/A */
325N/A public Document parse(String systemId, boolean root) throws SAXException, IOException{
325N/A
325N/A systemId = normalizeSystemId(systemId);
325N/A
325N/A InputSource is = null;
325N/A
325N/A // allow entity resolver to find the actual byte stream.
325N/A is = entityResolver.resolveEntity(null, systemId);
325N/A if (is == null)
325N/A is = new InputSource(systemId);
325N/A else {
325N/A resolvedCache.put(systemId, is.getSystemId());
325N/A systemId=is.getSystemId();
325N/A }
325N/A
325N/A if (core.containsKey(systemId)) {
325N/A // this document has already been parsed. Just ignore.
325N/A return core.get(systemId);
325N/A }
325N/A
325N/A if(!root)
325N/A addExternalReferences(systemId);
325N/A
325N/A // but we still use the original system Id as the key.
325N/A return parse(systemId, is, root);
325N/A }
325N/A protected Map<String,String> resolvedCache = new HashMap<String,String>();
325N/A
325N/A public Map<String,String> getReferencedEntityMap() {
325N/A return resolvedCache;
325N/A }
325N/A /**
325N/A * Parses the given document and add it to the DOM forest.
325N/A *
325N/A * @return null if there was a parse error. otherwise non-null.
325N/A */
325N/A private @NotNull Document parse(String systemId, InputSource inputSource, boolean root) throws SAXException, IOException{
325N/A Document dom = documentBuilder.newDocument();
325N/A
325N/A systemId = normalizeSystemId(systemId);
325N/A
325N/A // put into the map before growing a tree, to
325N/A // prevent recursive reference from causing infinite loop.
325N/A core.put(systemId, dom);
325N/A
325N/A dom.setDocumentURI(systemId);
325N/A if (root)
325N/A rootDocuments.add(systemId);
325N/A
325N/A try {
325N/A XMLReader reader = createReader(dom);
325N/A
325N/A InputStream is = null;
325N/A if(inputSource.getByteStream() == null){
325N/A inputSource = entityResolver.resolveEntity(null, systemId);
325N/A }
325N/A reader.parse(inputSource);
325N/A Element doc = dom.getDocumentElement();
325N/A if (doc == null) {
325N/A return null;
325N/A }
325N/A NodeList schemas = doc.getElementsByTagNameNS(SchemaConstants.NS_XSD, "schema");
325N/A for (int i = 0; i < schemas.getLength(); i++) {
325N/A inlinedSchemaElements.add((Element) schemas.item(i));
325N/A }
325N/A } catch (ParserConfigurationException e) {
325N/A errorReceiver.error(e);
325N/A throw new SAXException(e.getMessage());
325N/A }
325N/A resolvedCache.put(systemId, dom.getDocumentURI());
325N/A return dom;
325N/A }
325N/A
325N/A public void addExternalReferences(String ref) {
325N/A if (!externalReferences.contains(ref))
325N/A externalReferences.add(ref);
325N/A }
325N/A
325N/A
325N/A public Set<String> getExternalReferences() {
325N/A return externalReferences;
325N/A }
325N/A
325N/A
325N/A
325N/A public interface Handler extends ContentHandler {
325N/A /**
325N/A * Gets the DOM that was built.
325N/A */
325N/A public Document getDocument();
325N/A }
325N/A
325N/A /**
325N/A * Returns a {@link org.xml.sax.XMLReader} to parse a document into this DOM forest.
325N/A * <p/>
325N/A * This version requires that the DOM object to be created and registered
325N/A * to the map beforehand.
325N/A */
325N/A private XMLReader createReader(Document dom) throws SAXException, ParserConfigurationException {
325N/A XMLReader reader = parserFactory.newSAXParser().getXMLReader();
325N/A DOMBuilder dombuilder = new DOMBuilder(dom, locatorTable, outerMostBindings);
325N/A try {
325N/A reader.setProperty("http://xml.org/sax/properties/lexical-handler", dombuilder);
325N/A } catch(SAXException e) {
325N/A errorReceiver.debug(e.getMessage());
325N/A }
325N/A
325N/A ContentHandler handler = new WhitespaceStripper(dombuilder, errorReceiver, entityResolver);
325N/A handler = new VersionChecker(handler, errorReceiver, entityResolver);
325N/A
325N/A // insert the reference finder so that
325N/A // included/imported schemas will be also parsed
325N/A XMLFilterImpl f = logic.createExternalReferenceFinder(this);
325N/A f.setContentHandler(handler);
325N/A if (errorReceiver != null)
325N/A f.setErrorHandler(errorReceiver);
325N/A f.setEntityResolver(entityResolver);
325N/A
325N/A reader.setContentHandler(f);
325N/A if (errorReceiver != null)
325N/A reader.setErrorHandler(errorReceiver);
325N/A reader.setEntityResolver(entityResolver);
325N/A return reader;
325N/A }
325N/A
325N/A private String normalizeSystemId(String systemId) {
325N/A try {
325N/A systemId = new URI(systemId).normalize().toString();
325N/A } catch (URISyntaxException e) {
325N/A // leave the system ID untouched. In my experience URI is often too strict
325N/A }
325N/A return systemId;
325N/A }
325N/A
325N/A boolean isExtensionMode() {
325N/A return options.isExtensionMode();
325N/A }
325N/A
325N/A
325N/A /**
325N/A * Gets the DOM tree associated with the specified system ID,
325N/A * or null if none is found.
325N/A */
325N/A public Document get(String systemId) {
325N/A Document doc = core.get(systemId);
325N/A
325N/A if (doc == null && systemId.startsWith("file:/") && !systemId.startsWith("file://")) {
325N/A // As of JDK1.4, java.net.URL.toExternal method returns URLs like
325N/A // "file:/abc/def/ghi" which is an incorrect file protocol URL according to RFC1738.
325N/A // Some other correctly functioning parts return the correct URLs ("file:///abc/def/ghi"),
325N/A // and this descripancy breaks DOM look up by system ID.
325N/A
325N/A // this extra check solves this problem.
325N/A doc = core.get("file://" + systemId.substring(5));
325N/A }
325N/A
325N/A if (doc == null && systemId.startsWith("file:")) {
325N/A // on Windows, filenames are case insensitive.
325N/A // perform case-insensitive search for improved user experience
325N/A String systemPath = getPath(systemId);
325N/A for (String key : core.keySet()) {
325N/A if (key.startsWith("file:") && getPath(key).equalsIgnoreCase(systemPath)) {
325N/A doc = core.get(key);
325N/A break;
325N/A }
325N/A }
325N/A }
325N/A
325N/A return doc;
325N/A }
325N/A
325N/A /**
325N/A * Strips off the leading 'file:///' portion from an URL.
325N/A */
325N/A private String getPath(String key) {
325N/A key = key.substring(5); // skip 'file:'
325N/A while (key.length() > 0 && key.charAt(0) == '/')
325N/A key = key.substring(1);
325N/A return key;
325N/A }
325N/A
325N/A /**
325N/A * Gets all the system IDs of the documents.
325N/A */
325N/A public String[] listSystemIDs() {
325N/A return core.keySet().toArray(new String[core.keySet().size()]);
325N/A }
325N/A
325N/A /**
325N/A * Gets the system ID from which the given DOM is parsed.
325N/A * <p/>
325N/A * Poor-man's base URI.
325N/A */
325N/A public String getSystemId(Document dom) {
325N/A for (Map.Entry<String, Document> e : core.entrySet()) {
325N/A if (e.getValue() == dom)
325N/A return e.getKey();
325N/A }
325N/A return null;
325N/A }
325N/A
325N/A /**
325N/A * Gets the first one (which is more or less random) in {@link #rootDocuments}.
325N/A */
325N/A public String getFirstRootDocument() {
325N/A if(rootDocuments.isEmpty()) return null;
325N/A return rootDocuments.iterator().next();
325N/A }
325N/A
325N/A public Set<String> getRootDocuments() {
325N/A return rootDocuments;
325N/A }
325N/A
325N/A /**
325N/A * Dumps the contents of the forest to the specified stream.
325N/A * <p/>
325N/A * This is a debug method. As such, error handling is sloppy.
325N/A */
325N/A public void dump(OutputStream out) throws IOException {
325N/A try {
325N/A // create identity transformer
325N/A Transformer it = TransformerFactory.newInstance().newTransformer();
325N/A
325N/A for (Map.Entry<String, Document> e : core.entrySet()) {
325N/A out.write(("---<< " + e.getKey() + '\n').getBytes());
325N/A
325N/A DataWriter dw = new DataWriter(new OutputStreamWriter(out), null);
325N/A dw.setIndentStep(" ");
325N/A it.transform(new DOMSource(e.getValue()),
325N/A new SAXResult(dw));
325N/A
325N/A out.write("\n\n\n".getBytes());
325N/A }
325N/A } catch (TransformerException e) {
325N/A e.printStackTrace();
325N/A }
325N/A }
325N/A
325N/A}