Example usage for javax.xml.transform.dom DOMResult getNode

List of usage examples for javax.xml.transform.dom DOMResult getNode

Introduction

In this page you can find the example usage for javax.xml.transform.dom DOMResult getNode.

Prototype

public Node getNode() 

Source Link

Document

Get the node that will contain the result DOM tree.

Usage

From source file:net.javacrumbs.airline.server.VanillaTest.java

@Test
public void testGetFlightsXml() throws AirlineException, DatatypeConfigurationException, TransformerException {
    GetFlightsRequest request = JAXB.unmarshal(getStream("request1.xml"), GetFlightsRequest.class);

    GetFlightsResponse response = endpoint.getFlights(request);

    DOMResult domResponse = new DOMResult();
    JAXB.marshal(response, domResponse);

    XMLUnit.setIgnoreWhitespace(true);/*from  www.  j  a va 2  s. c o  m*/
    XMLAssert.assertXMLEqual(getDocument("response1.xml"), (Document) domResponse.getNode());

}

From source file:org.esigate.xml.XsltRenderer.java

/** {@inheritDoc} */
@Override//from ww w  . j a va2  s  .  com
public void render(DriverRequest httpRequest, String src, Writer out) throws IOException {
    try {
        HtmlDocumentBuilder htmlDocumentBuilder = new HtmlDocumentBuilder();
        htmlDocumentBuilder.setDoctypeExpectation(DoctypeExpectation.NO_DOCTYPE_ERRORS);
        Document document = htmlDocumentBuilder.parse(new InputSource(new StringReader(src)));
        Source source = new DOMSource(document);
        DOMResult result = new DOMResult();
        transformer.transform(source, result);
        XhtmlSerializer serializer = new XhtmlSerializer(out);
        Dom2Sax dom2Sax = new Dom2Sax(serializer, serializer);
        dom2Sax.parse(result.getNode());
    } catch (TransformerException e) {
        throw new ProcessingFailedException("Failed to transform source", e);
    } catch (SAXException e) {
        throw new ProcessingFailedException("Failed serialize transformation result", e);
    }
}

From source file:org.javelin.sws.ext.bind.internal.model.ClassHierarchyTest.java

@Test
public void handleXmlAccessTypePropertyWithBase() throws Exception {
    // f3, f4, p1, p2, p3, p4 - properties and annotated fields
    System.out.println("\nD2");
    JAXBContext context = JAXBContext.newInstance(D2.class);
    context.createMarshaller().marshal(new JAXBElement<D2>(new QName("", "r"), D2.class, new D2()), System.out);
    System.out.println();/*from ww  w. j av a2  s  . co m*/

    final List<DOMResult> results = new LinkedList<DOMResult>();

    context.generateSchema(new SchemaOutputResolver() {
        @Override
        public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
            DOMResult result = new DOMResult();
            results.add(result);
            result.setSystemId(suggestedFileName);
            return result;
        }
    });

    for (DOMResult dr : results) {
        javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(
                new javax.xml.transform.dom.DOMSource(dr.getNode()),
                new javax.xml.transform.stream.StreamResult(new java.io.PrintWriter(System.out)));
    }

    JAXBContext ctx = SweJaxbContextFactory.createContext(new Class[] { D2.class }, null);
    Map<Class<?>, TypedPattern<?>> patterns = (Map<Class<?>, TypedPattern<?>>) ReflectionTestUtils.getField(ctx,
            "patterns");
    ComplexTypePattern<D2> pattern = (ComplexTypePattern<D2>) patterns.get(D2.class);
    Map<QName, PropertyMetadata<D2, ?>> elements = (Map<QName, PropertyMetadata<D2, ?>>) ReflectionTestUtils
            .getField(pattern, "elements");
    assertThat(elements.size(), equalTo(8));
    assertTrue(elements.containsKey(new QName("", "f3")));
    assertTrue(elements.containsKey(new QName("", "f4")));
    assertTrue(elements.containsKey(new QName("", "fd3")));
    assertTrue(elements.containsKey(new QName("", "fd4")));
    assertTrue(elements.containsKey(new QName("", "p1")));
    assertTrue(elements.containsKey(new QName("", "p2")));
    assertTrue(elements.containsKey(new QName("", "p3")));
    assertTrue(elements.containsKey(new QName("", "p4")));
}

From source file:net.sf.joost.emitter.DOMEmitter.java

/**
 * DefaultConstructor//  w  w  w . j ava2s.  co m
 *
 * @throws ParserConfigurationException
 *                 if an error occurs while creating
 *                 {@link javax.xml.parsers.DocumentBuilder}
 *                 DOM-DocumentBuilder
 */
public DOMEmitter(DOMResult result) throws ParserConfigurationException {
    if (DEBUG)
        log.debug("init DOMEmitter");

    Node rootNode = result.getNode();
    nextSiblingOfRootNodes = result.getNextSibling();
    if (rootNode != null) {
        // use the document of the provided node
        if (rootNode instanceof Document)
            document = (Document) rootNode;
        else
            document = rootNode.getOwnerDocument();

        stack.push(rootNode);
    } else {
        // create a new document
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = factory.newDocumentBuilder();
        document = docBuilder.newDocument();

        stack.push(document);
    }
}

From source file:com.example.switchyard.sap.Transformers.java

private Element toElement(String xml) {
    DOMResult dom = new DOMResult();
    try {/*from   w w w .  ja v a2s. c om*/
        TransformerFactory.newInstance().newTransformer().transform(new StreamSource(new StringReader(xml)),
                dom);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return ((Document) dom.getNode()).getDocumentElement();
}

From source file:org.javelin.sws.ext.bind.jaxb.JaxbTest.java

@Test
public void generateXmlSchema() throws Exception {
    JAXBContext ctx = JAXBContext.newInstance(org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2.class,
            org.javelin.sws.ext.bind.jaxb.context3a.MyClassJ3.class);

    final List<DOMResult> results = new LinkedList<DOMResult>();

    ctx.generateSchema(new SchemaOutputResolver() {
        @Override//ww w  . j  a va 2s.  c  o m
        public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException {
            log.info("file: {}, namespace: {}", suggestedFileName, namespaceUri);
            DOMResult result = new DOMResult();
            results.add(result);
            result.setSystemId(suggestedFileName);
            return result;
        }
    });

    for (DOMResult dr : results) {
        log.info("=== {} ===", dr.getSystemId());
        javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(
                new javax.xml.transform.dom.DOMSource(dr.getNode()),
                new javax.xml.transform.stream.StreamResult(new java.io.PrintWriter(System.out)));
    }
}

From source file:de.thorstenberger.taskmodel.view.webapp.filter.ExportPDFFilter.java

/**
 * <ul>/*from   w  w  w  .j a v  a2  s. c o m*/
 * <li>Strip &lt;script&gt; elements, because xml characters within these tags lead to invalid xhtml.</li>
 * <li>Xhtmlrenderer does not render form elements right (will probably support real PDF forms in the future), so we
 * need to replace select boxes with simple strings: Replace each select box with a bold string containing the
 * selected option.</li>
 * <li>Replace every input checkbox with [ ] for unchecked or [X] for checked inputs.</li>
 * </ul>
 *
 * @param xhtml
 *            xhtml as {@link Document}
 * @return
 */
private Document processDocument(final Document xhtml) {
    final String xslt = readFile(this.getClass().getResourceAsStream("adjustforpdfoutput.xslt"));
    final Source xsltSource = new StreamSource(new StringReader(xslt));
    try {
        final Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF8");

        final DOMResult result = new DOMResult();
        transformer.transform(new DOMSource(xhtml), result);
        return (Document) result.getNode();
    } catch (final TransformerConfigurationException e) {
        log.error("Internal: Wrong xslt configuration", e);
    } catch (final TransformerFactoryConfigurationError e) {
        log.error("Internal: Wrong xslt configuration", e);
    } catch (final TransformerException e) {
        log.error("Internal: Could not strip script tags from xhtml", e);
        e.printStackTrace();
    }
    // fall through in error case: return untransformed xhtml
    log.warn("Could not clean up html, using orginial instead. This might lead to missing content!");
    return xhtml;
}

From source file:org.kuali.coeus.s2sgen.impl.generate.support.S2SAdobeFormAttachmentBaseGenerator.java

/**
 * This method convert node of form in to a Document
 * /*from w w  w . j  av  a2  s .co  m*/
 * @param node n {Node} node entry.
 * @return Document containing doc information
 */

public Document nodeToDom(org.w3c.dom.Node node) throws S2SException {
    try {
        javax.xml.transform.TransformerFactory tf = javax.xml.transform.TransformerFactory.newInstance();
        javax.xml.transform.Transformer xf = tf.newTransformer();
        javax.xml.transform.dom.DOMResult dr = new javax.xml.transform.dom.DOMResult();
        xf.transform(new javax.xml.transform.dom.DOMSource(node), dr);
        return (Document) dr.getNode();

    } catch (javax.xml.transform.TransformerException ex) {
        throw new S2SException(ex.getMessage());
    }
}

From source file:eu.semaine.util.XMLTool.java

/**
 * Merge two XML files using XSLT/*  w ww. j a v a2s.c  o  m*/
 * @param xmlFileContent1, first XML file content 
 * @param xmlFileContent2, second XML file content
 * @param mergingStylesheet, the XSLT style sheet merging xml2 into xml1.
 * @param refCodeName, code name used in xsl sheet to refer xmlFile2 (example: semaine.mary.intonation ) 
 * @return output of merged xml file
 * @throws Exception
 * @throws FileNotFoundException
 */
public static Document mergeTwoXMLFiles(Document xmlFileContent1, final Document xmlFileContent2,
        Templates mergingStylesheet, final String refCodeName) throws Exception, FileNotFoundException {

    DOMSource xml1Source = new DOMSource(xmlFileContent1);
    DOMResult mergedDR = new DOMResult();
    // Transformer is not guaranteed to be thread-safe -- therefore, we
    // need one per thread.
    Transformer mergingTransformer = mergingStylesheet.newTransformer();
    mergingTransformer.setURIResolver(new URIResolver() {
        public Source resolve(String href, String base) {
            if (href == null) {
                return null;
            } else if (href.equals(refCodeName)) {
                return (new DOMSource(xmlFileContent2));
            } else {
                return null;
            }
        }
    });

    mergingTransformer.transform(xml1Source, mergedDR);
    return (Document) mergedDR.getNode();
}

From source file:com.prowidesoftware.swift.model.mx.AbstractMX.java

public Element element() {
    final HashMap<String, String> properties = new HashMap<String, String>();
    // it didn't work as expected
    // properties.put(JAXBRIContext.DEFAULT_NAMESPACE_REMAP, namespace);
    try {//from   w  w  w  .  j ava  2 s .c o  m
        JAXBContext context = JAXBContext.newInstance(getClasses(), properties);

        DOMResult res = new DOMResult();
        context.createMarshaller().marshal(this, res);
        Document doc = (Document) res.getNode();

        return (Element) doc.getFirstChild();
    } catch (Exception e) {
        log.log(Level.WARNING, "Error creating XML Document for MX", e);
        return null;
    }
}