Search in sources :

Example 76 with DOMSource

use of javax.xml.transform.dom.DOMSource in project j2objc by google.

the class DTMManagerDefault method getDTMHandleFromNode.

/**
   * Given a W3C DOM node, try and return a DTM handle.
   * Note: calling this may be non-optimal, and there is no guarantee that
   * the node will be found in any particular DTM.
   *
   * @param node Non-null reference to a DOM node.
   *
   * @return a valid DTM handle.
   */
public synchronized int getDTMHandleFromNode(org.w3c.dom.Node node) {
    if (null == node)
        //"node must be non-null for getDTMHandleFromNode!");
        throw new IllegalArgumentException(XMLMessages.createXMLMessage(XMLErrorResources.ER_NODE_NON_NULL, null));
    if (node instanceof org.apache.xml.dtm.ref.DTMNodeProxy)
        return ((org.apache.xml.dtm.ref.DTMNodeProxy) node).getDTMNodeNumber();
    else {
        // Find the DOM2DTMs wrapped around this Document (if any)
        // and check whether they contain the Node in question.
        //
        // NOTE that since a DOM2DTM may represent a subtree rather
        // than a full document, we have to be prepared to check more
        // than one -- and there is no guarantee that we will find
        // one that contains ancestors or siblings of the node we're
        // seeking.
        //
        // %REVIEW% We could search for the one which contains this
        // node at the deepest level, and thus covers the widest
        // subtree, but that's going to entail additional work
        // checking more DTMs... and getHandleOfNode is not a
        // cheap operation in most implementations.
        //
        // TODO: %REVIEW% If overflow addressing, we may recheck a DTM
        // already examined. Ouch. But with the increased number of DTMs,
        // scanning back to check this is painful. 
        // POSSIBLE SOLUTIONS: 
        //   Generate a list of _unique_ DTM objects?
        //   Have each DTM cache last DOM node search?
        int max = m_dtms.length;
        for (int i = 0; i < max; i++) {
            DTM thisDTM = m_dtms[i];
            if ((null != thisDTM) && thisDTM instanceof DOM2DTM) {
                int handle = ((DOM2DTM) thisDTM).getHandleOfNode(node);
                if (handle != DTM.NULL)
                    return handle;
            }
        }
        // Not found; generate a new DTM.
        //
        // %REVIEW% Is this really desirable, or should we return null
        // and make folks explicitly instantiate from a DOMSource? The
        // latter is more work but gives the caller the opportunity to
        // explicitly add the DTM to a DTMManager... and thus to know when
        // it can be discarded again, which is something we need to pay much
        // more attention to. (Especially since only DTMs which are assigned
        // to a manager can use the overflow addressing scheme.)
        //
        // %BUG% If the source node was a DOM2DTM$defaultNamespaceDeclarationNode
        // and the DTM wasn't registered with this DTMManager, we will create
        // a new DTM and _still_ not be able to find the node (since it will
        // be resynthesized). Another reason to push hard on making all DTMs
        // be managed DTMs.
        // Since the real root of our tree may be a DocumentFragment, we need to
        // use getParent to find the root, instead of getOwnerDocument.  Otherwise
        // DOM2DTM#getHandleOfNode will be very unhappy.
        Node root = node;
        Node p = (root.getNodeType() == Node.ATTRIBUTE_NODE) ? ((org.w3c.dom.Attr) root).getOwnerElement() : root.getParentNode();
        for (; p != null; p = p.getParentNode()) {
            root = p;
        }
        DOM2DTM dtm = (DOM2DTM) getDTM(new javax.xml.transform.dom.DOMSource(root), false, null, true, true);
        int handle;
        if (node instanceof org.apache.xml.dtm.ref.dom2dtm.DOM2DTMdefaultNamespaceDeclarationNode) {
            // Can't return the same node since it's unique to a specific DTM, 
            // but can return the equivalent node -- find the corresponding 
            // Document Element, then ask it for the xml: namespace decl.
            handle = dtm.getHandleOfNode(((org.w3c.dom.Attr) node).getOwnerElement());
            handle = dtm.getAttributeNode(handle, node.getNamespaceURI(), node.getLocalName());
        } else
            handle = ((DOM2DTM) dtm).getHandleOfNode(node);
        if (DTM.NULL == handle)
            //"Could not resolve the node to a handle!");
            throw new RuntimeException(XMLMessages.createXMLMessage(XMLErrorResources.ER_COULD_NOT_RESOLVE_NODE, null));
        return handle;
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DOM2DTM(org.apache.xml.dtm.ref.dom2dtm.DOM2DTM) Node(org.w3c.dom.Node) SAX2RTFDTM(org.apache.xml.dtm.ref.sax2dtm.SAX2RTFDTM) DOM2DTM(org.apache.xml.dtm.ref.dom2dtm.DOM2DTM) SAX2DTM(org.apache.xml.dtm.ref.sax2dtm.SAX2DTM) DTM(org.apache.xml.dtm.DTM)

Example 77 with DOMSource

use of javax.xml.transform.dom.DOMSource in project j2objc by google.

the class TransformerIdentityImpl method transform.

/**
   * Process the source tree to the output result.
   * @param source  The input for the source tree.
   *
   * @param outputTarget The output target.
   *
   * @throws TransformerException If an unrecoverable error occurs
   * during the course of the transformation.
   */
public void transform(Source source, Result outputTarget) throws TransformerException {
    createResultContentHandler(outputTarget);
    /*
     * According to JAXP1.2, new SAXSource()/StreamSource()
     * should create an empty input tree, with a default root node. 
     * new DOMSource()creates an empty document using DocumentBuilder.
     * newDocument(); Use DocumentBuilder.newDocument() for all 3 situations,
     * since there is no clear spec. how to create an empty tree when
     * both SAXSource() and StreamSource() are used.
     */
    if ((source instanceof StreamSource && source.getSystemId() == null && ((StreamSource) source).getInputStream() == null && ((StreamSource) source).getReader() == null) || (source instanceof SAXSource && ((SAXSource) source).getInputSource() == null && ((SAXSource) source).getXMLReader() == null) || (source instanceof DOMSource && ((DOMSource) source).getNode() == null)) {
        try {
            DocumentBuilderFactory builderF = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = builderF.newDocumentBuilder();
            String systemID = source.getSystemId();
            source = new DOMSource(builder.newDocument());
            // Copy system ID from original, empty Source to new Source
            if (systemID != null) {
                source.setSystemId(systemID);
            }
        } catch (ParserConfigurationException e) {
            throw new TransformerException(e.getMessage());
        }
    }
    try {
        if (source instanceof DOMSource) {
            DOMSource dsource = (DOMSource) source;
            m_systemID = dsource.getSystemId();
            Node dNode = dsource.getNode();
            if (null != dNode) {
                try {
                    if (dNode.getNodeType() == Node.ATTRIBUTE_NODE)
                        this.startDocument();
                    try {
                        if (dNode.getNodeType() == Node.ATTRIBUTE_NODE) {
                            String data = dNode.getNodeValue();
                            char[] chars = data.toCharArray();
                            characters(chars, 0, chars.length);
                        } else {
                            org.apache.xml.serializer.TreeWalker walker;
                            walker = new org.apache.xml.serializer.TreeWalker(this, m_systemID);
                            walker.traverse(dNode);
                        }
                    } finally {
                        if (dNode.getNodeType() == Node.ATTRIBUTE_NODE)
                            this.endDocument();
                    }
                } catch (SAXException se) {
                    throw new TransformerException(se);
                }
                return;
            } else {
                String messageStr = XSLMessages.createMessage(XSLTErrorResources.ER_ILLEGAL_DOMSOURCE_INPUT, null);
                throw new IllegalArgumentException(messageStr);
            }
        }
        InputSource xmlSource = SAXSource.sourceToInputSource(source);
        if (null == xmlSource) {
            //"Can't transform a Source of type "
            throw new TransformerException(XSLMessages.createMessage(XSLTErrorResources.ER_CANNOT_TRANSFORM_SOURCE_TYPE, new Object[] { source.getClass().getName() }));
        //+ source.getClass().getName() + "!");
        }
        if (null != xmlSource.getSystemId())
            m_systemID = xmlSource.getSystemId();
        XMLReader reader = null;
        boolean managedReader = false;
        try {
            if (source instanceof SAXSource) {
                reader = ((SAXSource) source).getXMLReader();
            }
            if (null == reader) {
                try {
                    reader = XMLReaderManager.getInstance().getXMLReader();
                    managedReader = true;
                } catch (SAXException se) {
                    throw new TransformerException(se);
                }
            } else {
                try {
                    reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
                } catch (org.xml.sax.SAXException se) {
                // We don't care.
                }
            }
            // Get the input content handler, which will handle the 
            // parse events and create the source tree. 
            ContentHandler inputHandler = this;
            reader.setContentHandler(inputHandler);
            if (inputHandler instanceof org.xml.sax.DTDHandler)
                reader.setDTDHandler((org.xml.sax.DTDHandler) inputHandler);
            try {
                if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
                    reader.setProperty("http://xml.org/sax/properties/lexical-handler", inputHandler);
                if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
                    reader.setProperty("http://xml.org/sax/properties/declaration-handler", inputHandler);
            } catch (org.xml.sax.SAXException se) {
            }
            try {
                if (inputHandler instanceof org.xml.sax.ext.LexicalHandler)
                    reader.setProperty("http://xml.org/sax/handlers/LexicalHandler", inputHandler);
                if (inputHandler instanceof org.xml.sax.ext.DeclHandler)
                    reader.setProperty("http://xml.org/sax/handlers/DeclHandler", inputHandler);
            } catch (org.xml.sax.SAXNotRecognizedException snre) {
            }
            reader.parse(xmlSource);
        } catch (org.apache.xml.utils.WrappedRuntimeException wre) {
            Throwable throwable = wre.getException();
            while (throwable instanceof org.apache.xml.utils.WrappedRuntimeException) {
                throwable = ((org.apache.xml.utils.WrappedRuntimeException) throwable).getException();
            }
            throw new TransformerException(wre.getException());
        } catch (org.xml.sax.SAXException se) {
            throw new TransformerException(se);
        } catch (IOException ioe) {
            throw new TransformerException(ioe);
        } finally {
            if (managedReader) {
                XMLReaderManager.getInstance().releaseXMLReader(reader);
            }
        }
    } finally {
        if (null != m_outputStream) {
            try {
                m_outputStream.close();
            } catch (IOException ioe) {
            }
            m_outputStream = null;
        }
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Node(org.w3c.dom.Node) ContentHandler(org.xml.sax.ContentHandler) SAXException(org.xml.sax.SAXException) DeclHandler(org.xml.sax.ext.DeclHandler) LexicalHandler(org.xml.sax.ext.LexicalHandler) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException) XMLReader(org.xml.sax.XMLReader) StreamSource(javax.xml.transform.stream.StreamSource) IOException(java.io.IOException) SAXSource(javax.xml.transform.sax.SAXSource) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SAXException(org.xml.sax.SAXException) DTDHandler(org.xml.sax.DTDHandler)

Example 78 with DOMSource

use of javax.xml.transform.dom.DOMSource in project graphhopper by graphhopper.

the class GraphHopperServlet method errorsToXML.

protected String errorsToXML(Collection<Throwable> list) {
    if (list.isEmpty())
        throw new RuntimeException("errorsToXML should not be called with an empty list");
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();
        Element gpxElement = doc.createElement("gpx");
        gpxElement.setAttribute("creator", "GraphHopper");
        gpxElement.setAttribute("version", "1.1");
        doc.appendChild(gpxElement);
        Element mdElement = doc.createElement("metadata");
        gpxElement.appendChild(mdElement);
        Element extensionsElement = doc.createElement("extensions");
        mdElement.appendChild(extensionsElement);
        Element messageElement = doc.createElement("message");
        extensionsElement.appendChild(messageElement);
        messageElement.setTextContent(list.iterator().next().getMessage());
        Element hintsElement = doc.createElement("hints");
        extensionsElement.appendChild(hintsElement);
        for (Throwable t : list) {
            Element error = doc.createElement("error");
            hintsElement.appendChild(error);
            error.setAttribute("message", t.getMessage());
            error.setAttribute("details", t.getClass().getName());
        }
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));
        return writer.toString();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StringWriter(java.io.StringWriter) StreamResult(javax.xml.transform.stream.StreamResult) DocumentBuilder(javax.xml.parsers.DocumentBuilder) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Example 79 with DOMSource

use of javax.xml.transform.dom.DOMSource in project groovy-core by groovy.

the class XmlUtil method serialize.

/**
     * Write a pretty version of the Element to the OutputStream.
     *
     * @param element the Element to serialize
     * @param os      the OutputStream to write to
     */
public static void serialize(Element element, OutputStream os) {
    Source source = new DOMSource(element);
    serialize(source, os);
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource)

Example 80 with DOMSource

use of javax.xml.transform.dom.DOMSource in project groovy-core by groovy.

the class XmlUtil method serialize.

/**
     * Return a pretty String version of the Element.
     *
     * @param element the Element to serialize
     * @return the pretty String representation of the Element
     */
public static String serialize(Element element) {
    StringWriter sw = new StringWriter();
    serialize(new DOMSource(element), sw);
    return sw.toString();
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource)

Aggregations

DOMSource (javax.xml.transform.dom.DOMSource)392 StreamResult (javax.xml.transform.stream.StreamResult)231 Transformer (javax.xml.transform.Transformer)204 Document (org.w3c.dom.Document)161 TransformerFactory (javax.xml.transform.TransformerFactory)112 TransformerException (javax.xml.transform.TransformerException)107 DocumentBuilder (javax.xml.parsers.DocumentBuilder)102 StringWriter (java.io.StringWriter)97 IOException (java.io.IOException)93 Element (org.w3c.dom.Element)81 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)77 Source (javax.xml.transform.Source)67 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)62 SAXException (org.xml.sax.SAXException)56 File (java.io.File)55 InputSource (org.xml.sax.InputSource)50 StreamSource (javax.xml.transform.stream.StreamSource)47 Node (org.w3c.dom.Node)45 InputStream (java.io.InputStream)35 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)35