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:com.prowidesoftware.swift.model.mx.BusinessHeader.java

/**
 * Gets the header as an Element object.
 *  /*from  w  w  w  . ja va  2 s .c o m*/
 * @return Element this header parsed into Element or null if header is null
 * @since 7.8
 */
public Element element() {
    Object header = null;
    if (this.businessApplicationHeader != null) {
        header = this.businessApplicationHeader;
    } else if (this.applicationHeader != null) {
        header = this.applicationHeader;
    } else {
        return null;
    }
    try {
        JAXBContext context = JAXBContext.newInstance(header.getClass());
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        DOMResult res = new DOMResult();
        marshaller.marshal(_element(header), res);
        Document doc = (Document) res.getNode();
        return (Element) doc.getFirstChild();

    } catch (JAXBException e) {
        log.log(Level.SEVERE, "Error writing XML:" + e + "\n for header: " + header);
    }
    return null;
}

From source file:be.e_contract.mycarenet.ehbox.EHealthBoxConsultationClient.java

private Element toElement(Source source) {
    if (source instanceof DOMSource) {
        DOMSource domSource = (DOMSource) source;
        return (Element) domSource.getNode();
    }/*from ww  w.  j ava 2  s  . co  m*/
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = transformerFactory.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    }
    DOMResult domResult = new DOMResult();
    try {
        transformer.transform(source, domResult);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
    Document document = (Document) domResult.getNode();
    return (Element) document.getDocumentElement();
}

From source file:eu.domibus.ebms3.receiver.MSHWebservice.java

/**
 * Handles Receipt generation for a incoming message
 *
 * @param request          the incoming message
 * @param legConfiguration processing information of the message
 * @param duplicate        indicates whether or not the message is a duplicate
 * @return the response message to the incoming request message
 * @throws EbMS3Exception if generation of receipt was not successful
 *//*from   w  w w  . j a  v a2s . c  o m*/
private SOAPMessage generateReceipt(SOAPMessage request, LegConfiguration legConfiguration, Boolean duplicate)
        throws EbMS3Exception {
    SOAPMessage responseMessage = null;

    assert legConfiguration != null;

    if (legConfiguration.getReliability() == null) {
        return responseMessage;
    }

    if (ReplyPattern.RESPONSE.equals(legConfiguration.getReliability().getReplyPattern())) {
        MSHWebservice.LOG.debug("Checking reliability for incoming message");
        try {
            responseMessage = this.messageFactory.createMessage();
            Source messageToReceiptTransform = new StreamSource(
                    this.getClass().getClassLoader().getResourceAsStream("./xslt/GenerateAS4Receipt.xsl"));
            Transformer transformer = this.transformerFactory.newTransformer(messageToReceiptTransform);
            Source requestMessage = request.getSOAPPart().getContent();
            transformer.setParameter("messageid", this.messageIdGenerator.generateMessageId());
            transformer.setParameter("timestamp", this.timestampDateFormatter.generateTimestamp());
            transformer.setParameter("nonRepudiation",
                    Boolean.toString(legConfiguration.getReliability().isNonRepudiation()));

            DOMResult domResult = new DOMResult();

            transformer.transform(requestMessage, domResult);
            responseMessage.getSOAPPart().setContent(new DOMSource(domResult.getNode()));

            //                transformer.transform(requestMessage, new DOMResult(responseMessage.getSOAPPart().getEnvelope()));
        } catch (TransformerConfigurationException | SOAPException e) {
            // this cannot happen
            assert false;
            throw new RuntimeException(e);
        } catch (TransformerException e) {
            throw new EbMS3Exception(EbMS3Exception.EbMS3ErrorCode.EBMS_0201,
                    "Could not generate Receipt. Check security header and non-repudiation settings", null, e,
                    MSHRole.RECEIVING);
        }
    }

    return responseMessage;
}

From source file:org.geowebcache.config.XMLConfiguration.java

private static Node applyTransform(Node oldRootNode, String xslFilename) {
    DOMResult result = new DOMResult();
    Transformer transformer;//from w  w  w  .ja v a  2s  .c  o  m

    InputStream is = XMLConfiguration.class.getResourceAsStream(xslFilename);

    try {
        transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(is));
        transformer.transform(new DOMSource(oldRootNode), result);
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    }

    return result.getNode();
}

From source file:cz.cas.lib.proarc.common.export.cejsh.CejshBuilderTest.java

@Test
public void testCreateCejshXml_TitleVolume() throws Exception {
    CejshConfig conf = new CejshConfig();
    CejshBuilder cb = new CejshBuilder(conf);
    Document articleDoc = cb.getDocumentBuilder()
            .parse(CejshBuilderTest.class.getResource("article_mods.xml").toExternalForm());
    // issn must match some cejsh_journals.xml/cejsh/journal[@issn=$issn]
    final String pkgIssn = "0231-5955";
    Title title = new Title();
    title.setIssn(pkgIssn);/*w w  w . j av a  2  s . c om*/
    Volume volume = new Volume();
    volume.setVolumeId("uuid-volume");
    volume.setVolumeNumber("volume1");
    volume.setYear("1985");
    Article article = new Article(null, articleDoc.getDocumentElement(), null);
    cb.setTitle(title);
    cb.setVolume(volume);

    Document articleCollectionDoc = cb.mergeElements(Collections.singletonList(article));
    DOMSource cejshSource = new DOMSource(articleCollectionDoc);
    DOMResult cejshResult = new DOMResult();
    //        dump(cejshSource);

    TransformErrorListener xslError = cb.createCejshXml(cejshSource, cejshResult);
    assertEquals(Collections.emptyList(), xslError.getErrors());
    final Node cejshRootNode = cejshResult.getNode();
    //        dump(new DOMSource(cejshRootNode));

    List<String> errors = cb.validateCejshXml(new DOMSource(cejshRootNode));
    assertEquals(Collections.emptyList(), errors);

    XPath xpath = ProarcXmlUtils.defaultXPathFactory().newXPath();
    xpath.setNamespaceContext(new SimpleNamespaceContext().add("b", CejshBuilder.NS_BWMETA105));
    assertNotNull(
            xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.ebfd7bf2-169d-476e-a230-0cc39f01764c']",
                    cejshRootNode, XPathConstants.NODE));
    assertEquals("volume1", xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.uuid-volume']/b:name",
            cejshRootNode, XPathConstants.STRING));
    //        assertEquals("issue1", xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.uuid-issue']/b:name", cejshRootNode, XPathConstants.STRING));
    assertEquals("1985", xpath.evaluate(
            "/b:bwmeta/b:element[@id='bwmeta1.element.9358223b-b135-388f-a71e-24ac2c8422c7-1985']/b:name",
            cejshRootNode, XPathConstants.STRING));
}

From source file:cz.cas.lib.proarc.common.export.cejsh.CejshBuilderTest.java

@Test
public void testCreateCejshXml_TitleVolumeIssue() throws Exception {
    CejshConfig conf = new CejshConfig();
    CejshBuilder cb = new CejshBuilder(conf);
    Document articleDoc = cb.getDocumentBuilder()
            .parse(CejshBuilderTest.class.getResource("article_mods.xml").toExternalForm());
    // issn must match some cejsh_journals.xml/cejsh/journal[@issn=$issn]
    final String pkgIssn = "0231-5955";
    Issue issue = new Issue();
    issue.setIssn(pkgIssn);/* www.j av  a2  s .  co  m*/
    issue.setIssueId("uuid-issue");
    issue.setIssueNumber("issue1");
    Volume volume = new Volume();
    volume.setVolumeId("uuid-volume");
    volume.setVolumeNumber("volume1");
    volume.setYear("1985");
    Article article = new Article(null, articleDoc.getDocumentElement(), null);
    cb.setIssue(issue);
    cb.setVolume(volume);

    Document articleCollectionDoc = cb.mergeElements(Collections.singletonList(article));
    DOMSource cejshSource = new DOMSource(articleCollectionDoc);
    DOMResult cejshResult = new DOMResult();
    //        dump(cejshSource);

    TransformErrorListener xslError = cb.createCejshXml(cejshSource, cejshResult);
    assertEquals(Collections.emptyList(), xslError.getErrors());
    final Node cejshRootNode = cejshResult.getNode();
    //        dump(new DOMSource(cejshRootNode));

    List<String> errors = cb.validateCejshXml(new DOMSource(cejshRootNode));
    assertEquals(Collections.emptyList(), errors);

    XPath xpath = ProarcXmlUtils.defaultXPathFactory().newXPath();
    xpath.setNamespaceContext(new SimpleNamespaceContext().add("b", CejshBuilder.NS_BWMETA105));
    assertNotNull(
            xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.ebfd7bf2-169d-476e-a230-0cc39f01764c']",
                    cejshRootNode, XPathConstants.NODE));
    assertEquals("volume1", xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.uuid-volume']/b:name",
            cejshRootNode, XPathConstants.STRING));
    assertEquals("issue1", xpath.evaluate("/b:bwmeta/b:element[@id='bwmeta1.element.uuid-issue']/b:name",
            cejshRootNode, XPathConstants.STRING));
    assertEquals("1985", xpath.evaluate(
            "/b:bwmeta/b:element[@id='bwmeta1.element.9358223b-b135-388f-a71e-24ac2c8422c7-1985']/b:name",
            cejshRootNode, XPathConstants.STRING));
}

From source file:ddf.services.schematron.SchematronValidationService.java

private Templates compileSchematronRules(String schematronFileName) throws SchematronInitializationException {

    Templates template;/* www. ja v  a2  s. c om*/
    File schematronFile = new File(schematronFileName);
    if (!schematronFile.exists()) {
        throw new SchematronInitializationException("Could not locate schematron file " + schematronFileName);
    }

    try {
        URL schUrl = schematronFile.toURI().toURL();
        Source schSource = new StreamSource(schUrl.toString());

        // Stage 1: Perform inclusion expansion on Schematron schema file
        DOMResult stage1Result = performStage(schSource,
                getClass().getClassLoader().getResource("iso-schematron/iso_dsdl_include.xsl"));
        DOMSource stage1Output = new DOMSource(stage1Result.getNode());

        // Stage 2: Perform abstract expansion on output file from Stage 1
        DOMResult stage2Result = performStage(stage1Output,
                getClass().getClassLoader().getResource("iso-schematron/iso_abstract_expand.xsl"));
        DOMSource stage2Output = new DOMSource(stage2Result.getNode());

        // Stage 3: Compile the .sch rules that have been prepocessed by Stages 1 and 2 (i.e.,
        // the output of Stage 2)
        DOMResult stage3Result = performStage(stage2Output,
                getClass().getClassLoader().getResource("iso-schematron/iso_svrl_for_xslt2.xsl"));
        DOMSource stage3Output = new DOMSource(stage3Result.getNode());

        // Setting the system ID let's us resolve relative paths in the schematron files.
        // We need the URL string so that the string is properly formatted (e.g. space = %20).
        stage3Output.setSystemId(schUrl.toString());
        template = transformerFactory.newTemplates(stage3Output);
    } catch (Exception e) {
        throw new SchematronInitializationException(
                "Error trying to create SchematronValidationService using sch file " + schematronFileName, e);
    }

    return template;
}

From source file:ddf.security.pdp.xacml.processor.BalanaPdp.java

/**
 * Unmarshalls the XACML response./*w w  w  .  java2s . com*/
 * 
 * @param xacmlResponse
 *            The XACML response with all namespaces and namespace prefixes added.
 * @return The XACML response.
 * @throws PdpException
 */
private ResponseType unmarshal(DOMResult xacmlResponse) throws PdpException {
    JAXBElement<ResponseType> xacmlResponseTypeElement = null;

    try {
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

        xacmlResponseTypeElement = unmarshaller.unmarshal(xacmlResponse.getNode(), ResponseType.class);
    } catch (JAXBException e) {
        String message = "Unable to unmarshal XACML response.";
        LOGGER.error(message);
        throw new PdpException(message, e);
    }

    return xacmlResponseTypeElement.getValue();
}

From source file:de.intevation.test.irixservice.UploadReportTest.java

@Test(expected = UploadReportException.class)
public void testInvalidDokpool() throws UploadReportException, JAXBException {
    ReportType report = getReportFromFile(VALID_REPORT);
    DokpoolMeta meta = new DokpoolMeta();
    meta.setDokpoolContentType("Invalid doc");
    DOMResult res = new DOMResult();
    Element ele = null;//  w  w w.j  a  va  2  s  .  c  o m
    JAXBContext jaxbContext = JAXBContext.newInstance(DokpoolMeta.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    jaxbMarshaller.marshal(meta, res);
    ele = ((Document) res.getNode()).getDocumentElement();

    report.getAnnexes().getAnnotation().get(0).getAny().add(ele);
    testObj.uploadReport(report);
}

From source file:com.predic8.membrane.core.interceptor.schemavalidation.SchematronValidator.java

public SchematronValidator(ResolverMap resourceResolver, String schematron,
        ValidatorInterceptor.FailureHandler failureHandler, Router router, BeanFactory beanFactory)
        throws Exception {
    this.failureHandler = failureHandler;

    //works as standalone "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"
    TransformerFactory fac;/*from ww w  . j ava  2 s  . c om*/
    try {
        fac = beanFactory.getBean("transformerFactory", TransformerFactory.class);
    } catch (NoSuchBeanDefinitionException e) {
        throw new RuntimeException(
                "Please define a bean called 'transformerFactory' in monitor-beans.xml, e.g. with "
                        + "<spring:bean id=\"transformerFactory\" class=\"com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl\" />",
                e);
    }
    fac.setURIResolver(new URIResolver() {
        @Override
        public Source resolve(String href, String base) throws TransformerException {
            return new StreamSource(SchematronValidator.class.getResourceAsStream(href));
        }
    });
    Transformer t = fac.newTransformer(
            new StreamSource(SchematronValidator.class.getResourceAsStream("conformance1-5.xsl")));

    // transform schematron-XML into XSLT
    DOMResult r = new DOMResult();
    t.transform(new StreamSource(router.getResolverMap().resolve(schematron)), r);

    // build XSLT transformers
    fac.setURIResolver(null);
    int concurrency = Runtime.getRuntime().availableProcessors() * 2;
    transformers = new ArrayBlockingQueue<Transformer>(concurrency);
    for (int i = 0; i < concurrency; i++) {
        Transformer transformer = fac.newTransformer(new DOMSource(r.getNode()));
        transformer.setErrorListener(new NullErrorListener()); // silence console logging
        transformers.put(transformer);
    }

    xmlInputFactory = XMLInputFactory.newInstance();
    xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
    xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
}