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

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

Introduction

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

Prototype

public DOMResult() 

Source Link

Document

Zero-argument default constructor.

Usage

From source file:org.biopax.validator.api.ValidatorUtils.java

protected static DOMResult marshal(Object obj) {
    DOMResult domResult = new DOMResult();
    try {/*from   w ww . ja va 2 s  .c  o  m*/
        getMarshaller().marshal(obj, domResult);
    } catch (Exception e) {
        throw new RuntimeException("Cannot serialize object: " + obj, e);
    }
    return domResult;
}

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

/**
 * <ul>/* w w w  . ja v a  2s. c  om*/
 * <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: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  a  v  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: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;//from w  w  w .  j ava2  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: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();//w ww. ja  v  a2  s .c  o  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:cz.cas.lib.proarc.common.export.mets.JhoveUtility.java

/**
 * Merges the mix from the device and from the image
 *
 * @param source//from  w w w  .  j  a va2  s  . c  om
 * @param deviceMix
 */
public static void mergeMix(Mix source, MixType deviceMix) {
    if (deviceMix != null) {
        if (deviceMix.getImageCaptureMetadata() != null) {
            DOMResult domResult = new DOMResult();
            MixUtils.marshal(domResult, new JAXBElement<ImageCaptureMetadataType>(new QName("uri", "local"),
                    ImageCaptureMetadataType.class, deviceMix.getImageCaptureMetadata()), true);
            ImageCaptureMetadataType imageCaptureMtd = MixUtils.unmarshal(new DOMSource(domResult.getNode()),
                    ImageCaptureMetadataType.class);
            source.setImageCaptureMetadata(imageCaptureMtd);
        }
    }

}

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

private DOMResult performStage(Source input, URL preprocessorUrl)
        throws TransformerException, ParserConfigurationException, SchematronInitializationException {

    Source preprocessorSource = new StreamSource(preprocessorUrl.toString());

    Transformer transformer = transformerFactory.newTransformer(preprocessorSource);

    // Setup an error listener to catch warnings and errors generated during transformation
    transformer.setErrorListener(new Listener());

    // Transform the input using the preprocessor's transformer, capturing the output in a DOM
    DOMResult domResult = new DOMResult();
    transformer.transform(input, domResult);

    return domResult;
}

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

@Test
public void testCreateCejshElement_UnknownIssn() throws Exception {
    CejshConfig conf = new CejshConfig();
    CejshBuilder cb = new CejshBuilder(conf);
    Document articleDoc = cb.getDocumentBuilder()
            .parse(CejshBuilderTest.class.getResource("article_mods.xml").toExternalForm());
    final String pkgIssn = "XXX-XXX";
    Issue issue = new Issue();
    issue.setIssn(pkgIssn);//  w ww . j  a va 2 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));
    DOMResult cejshResult = new DOMResult();
    cb.createCejshXml(new DOMSource(articleCollectionDoc), cejshResult);
    //        dump(new DOMSource(cejshResult.getNode()));

    // issn must match some cejsh_journals.xml/cejsh/journal[@issn=$issn]
    assertEquals(1, cb.getTranformationErrors().size());
    assertTrue(cb.getTranformationErrors().get(0),
            cb.getTranformationErrors().get(0).startsWith("ERROR: Missing journalId"));
}

From source file:ddf.security.pdp.realm.xacml.processor.BalanaClient.java

/**
 * Adds namespaces and namespace prefixes to the XACML response returned by the Balana PDP. The
 * Balana PDP returns a response with no namespaces, so we need to add them to unmarshal the
 * response.//w w  w.jav a2 s.co m
 *
 * @param xacmlResponse The XACML response as a string.
 * @return DOM representation of the XACML response with namespaces and namespace prefixes.
 * @throws PdpException
 */
private DOMResult addNamespaceAndPrefixes(String xacmlResponse) throws PdpException {
    XMLReader xmlReader = null;

    try {
        xmlReader = new XMLFilterImpl(XMLReaderFactory.createXMLReader()) {
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                super.startElement(XACML30_NAMESPACE, localName, XACML_PREFIX + ":" + qName, attributes);
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                super.endElement(XACML30_NAMESPACE, localName, XACML_PREFIX + ":" + qName);
            }
        };
    } catch (SAXException e) {
        String message = "Unable to read XACML response:\n" + xacmlResponse;
        LOGGER.error(message);
        throw new PdpException(message, e);
    }

    DOMResult domResult;
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(BalanaClient.class.getClassLoader());
    try {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();

        domResult = new DOMResult();

        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(new SAXSource(xmlReader, new InputSource(new StringReader(xacmlResponse))),
                domResult);
    } catch (TransformerException e) {
        String message = "Unable to transform XACML response:\n" + xacmlResponse;
        LOGGER.error(message);
        throw new PdpException(message, e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }

    return domResult;
}

From source file:XMLUtils.java

public static Node fromSource(Source src) throws Exception {

    Transformer trans = TransformerFactory.newInstance().newTransformer();
    DOMResult res = new DOMResult();
    trans.transform(src, res);/*from   w  w  w  .j a va  2s  .  co m*/
    return res.getNode();
}