Example usage for org.jdom2.transform JDOMResult JDOMResult

List of usage examples for org.jdom2.transform JDOMResult JDOMResult

Introduction

In this page you can find the example usage for org.jdom2.transform JDOMResult JDOMResult.

Prototype

public JDOMResult() 

Source Link

Document

Public default constructor.

Usage

From source file:de.rallye.api.LandingPage.java

License:Open Source License

@GET
@Produces("image/png")
@Path("timetable/{groupsCode}")
public StreamingOutput getTimeTable(@PathParam("groupsCode") final String groupsCode) {

    StreamingOutput stream = new StreamingOutput() {
        @Override//  ww  w. j  a  v  a  2  s. c o  m
        public void write(OutputStream os) throws IOException, WebApplicationException {
            try {
                Document doc = new SAXBuilder()
                        .build(StadtRallye.class.getResourceAsStream("timetable/stundenplan.xml"));
                replaceKgRooms(doc, groupsCode);
                Source xmlFile = new JDOMSource(doc);
                final JDOMResult htmlResult = new JDOMResult();
                Transformer transformer = TransformerFactory.newInstance().newTransformer(
                        new StreamSource(StadtRallye.class.getResourceAsStream("timetable/stundenplan.xsl")));
                transformer.transform(xmlFile, htmlResult);

                PipedInputStream svgIn = new PipedInputStream();
                final PipedOutputStream svgOut = new PipedOutputStream(svgIn);

                new Thread(new Runnable() {
                    public void run() {

                        XMLOutputter xmlOutputter = new XMLOutputter();
                        try {
                            xmlOutputter.output(htmlResult.getDocument(), svgOut);
                            svgOut.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (Throwable e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

                // Create a PNG transcoder
                PNGTranscoder t = new PNGTranscoder();

                // Create the transcoder input.
                //String svgURI = new File(args[0]).toURL().toString();
                TranscoderInput input = new TranscoderInput(svgIn);

                // Create the transcoder output.
                TranscoderOutput output = new TranscoderOutput(os);

                SVGConverter x;

                // Save the image.
                t.transcode(input, output);
                svgIn.close();

                // Flush and close the stream.
                os.flush();
                os.close();

            } catch (JDOMException e) {
                e.printStackTrace();
            } catch (TransformerConfigurationException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            } catch (TranscoderException e) {
                e.printStackTrace();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    };
    return stream;

    //return StadtRallye.class.getResourceAsStream("timetable/stundenplan.xml");
}

From source file:edu.unc.lib.deposit.normalize.Proquest2N3BagJob.java

License:Apache License

/**
 * Transform the given root element from the data document into MODS and stores it as the metadata for the object
 * being ingested//from ww  w. ja  v a 2s .  c o m
 *
 * @param primaryPID
 * @param dataRoot
 * @param modified
 * @throws TransformerException
 * @throws FileNotFoundException
 * @throws IOException
 */
private Document extractMods(PID primaryPID, Element dataRoot, DateTime modified)
        throws TransformerException, FileNotFoundException, IOException {

    int month = modified.getMonthOfYear();
    String gradSemester;

    if (month >= 2 && month <= 6) {
        gradSemester = "Spring";
    } else if (month >= 7 && month <= 9) {
        gradSemester = "Summer";
    } else {
        gradSemester = "Winter";
    }

    JDOMResult mods = new JDOMResult();
    // Transform the metadata into MODS
    synchronized (proquest2ModsTransformer) {
        proquest2ModsTransformer.setParameter("graduationSemester", gradSemester + " " + modified.getYear());
        proquest2ModsTransformer.transform(new JDOMSource(dataRoot), mods);
    }

    // Create the description folder and write the MODS out to it
    final File modsFolder = getDescriptionDir();
    modsFolder.mkdir();

    File modsFile = new File(modsFolder, primaryPID.getUUID() + ".xml");

    try (FileOutputStream fos = new FileOutputStream(modsFile)) {
        new XMLOutputter(Format.getPrettyFormat()).output(mods.getDocument(), fos);
    }

    return mods.getDocument();
}

From source file:org.apache.marmotta.platform.sparql.services.sparqlio.sparqlhtml.SPARQLBooleanHTMLWriter.java

License:Apache License

@Override
public void handleBoolean(boolean value) throws QueryResultHandlerException {
    try {/*from ww  w . j a va 2s. c  o  m*/
        // Create a SPARQL/XML representation that will be transformed to HTML using a stylesheet
        ByteArrayOutputStream xmlOut = new ByteArrayOutputStream();
        QueryResultIO.writeBoolean(value, BooleanQueryResultFormat.SPARQL, xmlOut);
        byte[] queryResult = xmlOut.toByteArray();

        // get server uri
        String server_uri = CDIContext.getInstance(ConfigurationService.class).getServerUri();

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));

        Source input = new StreamSource(new ByteArrayInputStream(queryResult));

        Source s_stylesheet = new StreamSource(SPARQLBooleanHTMLWriter.class.getResourceAsStream("style.xsl"));
        Templates stylesheet = TransformerFactory.newInstance().newTemplates(s_stylesheet);
        Transformer transformer = stylesheet.newTransformer();
        transformer.setParameter("serverurl", server_uri);

        JDOMResult result = new JDOMResult();
        transformer.transform(input, result);
        Document output = result.getDocument();

        XMLOutputter printer = new XMLOutputter(Format.getPrettyFormat());
        printer.output(output, writer);
        writer.flush();
    } catch (TransformerConfigurationException e) {
        log.error("could not compile stylesheet for rendering SPARQL results; result display not available!");
        throw new QueryResultHandlerException(
                "could not compile stylesheet for rendering SPARQL results; result display not available!", e);
    } catch (Exception ex) {
        throw new QueryResultHandlerException("error while transforming XML results to HTML", ex);
    } finally {
        // writer.close();
    }
}

From source file:org.apache.marmotta.platform.sparql.services.sparqlio.sparqlhtml.SPARQLResultsHTMLWriterXSL.java

License:Apache License

/**
 * Indicates the end of a sequence of solutions.
 *///from ww w .  j a  v a2 s .co  m
@Override
public void endQueryResult() throws TupleQueryResultHandlerException {
    writer.endQueryResult();

    // get server uri
    String server_uri = CDIContext.getInstance(ConfigurationService.class).getServerUri();

    byte[] queryResult = xmlOut.toByteArray();

    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
    try {
        Source input = new StreamSource(new ByteArrayInputStream(queryResult));

        Transformer transformer = stylesheet.newTransformer();
        transformer.setParameter("serverurl", server_uri);

        JDOMResult result = new JDOMResult();
        transformer.transform(input, result);
        Document output = result.getDocument();

        XMLOutputter printer = new XMLOutputter(Format.getPrettyFormat());
        printer.output(output, writer);
        writer.flush();

    } catch (Exception ex) {
        throw new TupleQueryResultHandlerException("error while transforming XML results to HTML", ex);
    } finally {
        try {
            writer.close();
        } catch (IOException e) {
        }
    }

}

From source file:org.mycore.common.content.MCRJAXBContent.java

License:Open Source License

@Override
public Document asXML() throws JDOMException, IOException, SAXParseException {
    JDOMResult result = new JDOMResult();
    try {//from  w  w w .  j  a v  a 2  s.co m
        Marshaller marshaller = getMarshaller();
        marshaller.marshal(jaxbObject, result);
    } catch (JAXBException e) {
        throw new IOException(e);
    }
    return result.getDocument();
}

From source file:org.mycore.common.content.transformer.MCRXSL2XMLTransformer.java

License:Open Source License

@Override
protected MCRContent getTransformedContent(MCRContent source, XMLReader reader,
        TransformerHandler transformerHandler) throws IOException, SAXException {
    JDOMResult result = new JDOMResult();
    transformerHandler.setResult(result);
    // Parse the source XML, and send the parse events to the
    // TransformerHandler.
    reader.parse(source.getInputSource());
    Document resultDoc = getDocument(result);
    if (resultDoc == null) {
        throw new MCRConfigurationException("Stylesheets " + Arrays.asList(templateSources).toString()
                + " does not return any content for " + source.getSystemId());
    }//from w  w w.  ja v a2 s .c o  m
    return new MCRJDOMContent(resultDoc);
}

From source file:org.mycore.common.xml.MCRXSLTransformation.java

License:Open Source License

/**
 * transforms a jdom Document via XSLT./*from www.  j  a  v  a2 s .c o  m*/
 * 
 * @param in Document input
 * @param transformer Transformer handling the transformation process
 * @return the transformation result as jdom Document
 * @throws TransformerException if transformation fails
 */
public static Document transform(Document in, Transformer transformer) throws TransformerException {
    JDOMResult out = new JDOMResult();
    transformer.transform(new JDOMSource(in), out);
    return out.getDocument();
}

From source file:org.mycore.frontend.cli.MCRObjectCommands.java

License:Open Source License

/**
 * Does a xsl transform with the given mycore object.
 * <p>//  w ww  . j a  v a  2 s .c o  m
 * To use this command create a new xsl file and copy following xslt code into it.
 * </p>
 *
 * <pre>
 * {@code
 * <?xml version="1.0" encoding="utf-8"?>
 * <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 *
 *   <xsl:template match='@*|node()'>
 *     <!-- default template: just copy -->
 *     <xsl:copy>
 *       <xsl:apply-templates select='@*|node()' />
 *     </xsl:copy>
 *   </xsl:template>
 *
 * </xsl:stylesheet>
 * }
 * </pre>
 * <p>
 * Insert a new template match, for example:
 * </p>
 *
 * <pre>
 * {@code
 * <xsl:template match="metadata/mainTitle/@heritable">
 *   <xsl:attribute name="heritable"><xsl:value-of select="'true'"/></xsl:attribute>
 * </xsl:template>
 * }
 * </pre>
 *
 * @param objectId
 *            object to transform
 * @param xslFilePath
 *            path to xsl file
 * @throws URISyntaxException if xslFilePath is not a valid file or URL
 * @throws MCRActiveLinkException see {@link MCRMetadataManager#update(MCRObject)}
 * @throws MCRPersistenceException see {@link MCRMetadataManager#update(MCRObject)}
 * @throws MCRAccessException see {@link MCRMetadataManager#update(MCRObject)}
 */
@MCRCommand(syntax = "xslt {0} with file {1}", help = "transforms a mycore object {0} with the given file or URL {1}", order = 280)
public static void xslt(String objectId, String xslFilePath)
        throws IOException, JDOMException, SAXException, URISyntaxException, TransformerException,
        MCRPersistenceException, MCRActiveLinkException, MCRAccessException {
    File xslFile = new File(xslFilePath);
    URL xslURL;
    if (!xslFile.exists()) {
        try {
            xslURL = new URL(xslFilePath);
        } catch (MalformedURLException e) {
            LOGGER.error("XSL parameter is not a file or URL: " + xslFilePath);
            return;
        }
    } else {
        xslURL = xslFile.toURI().toURL();
    }
    MCRObjectID mcrId = MCRObjectID.getInstance(objectId);
    Document document = MCRXMLMetadataManager.instance().retrieveXML(mcrId);
    // do XSL transform
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setErrorListener(MCRErrorListener.getInstance());
    transformerFactory.setURIResolver(MCRURIResolver.instance());
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    xmlReader.setEntityResolver(MCREntityResolver.instance());
    SAXSource styleSource = new SAXSource(xmlReader, new InputSource(xslURL.toURI().toString()));
    Transformer transformer = transformerFactory.newTransformer(styleSource);
    for (Entry<String, String> property : MCRConfiguration.instance().getPropertiesMap().entrySet()) {
        transformer.setParameter(property.getKey(), property.getValue());
    }
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    JDOMResult result = new JDOMResult();
    transformer.transform(new JDOMSource(document), result);
    Document resultDocument = Objects.requireNonNull(result.getDocument(),
            "Could not get transformation result");
    // update on diff
    if (!MCRXMLHelper.deepEqual(document, resultDocument)) {
        MCRMetadataManager.update(new MCRObject(resultDocument));
    }
}

From source file:org.springframework.ws.server.endpoint.AbstractJDomPayloadEndpoint.java

License:Apache License

/**
 * Returns the payload element of the given source.
 *
 * <p>Default implementation checks whether the source is a {@link DOMSource}, and uses a {@link DOMBuilder} to create
 * a JDOM {@link Element}. In all other cases, or when {@linkplain #setAlwaysTransform(boolean) alwaysTransform} is
 * {@code true}, the source is transformed into a {@link JDOMResult}, which is more expensive. If the passed source
 * is {@code null}, {@code null} is returned.
 *
 * @param source the source to return the root element of; can be {@code null}
 * @return the document element// w w  w  .jav  a  2s  .c  om
 * @throws TransformerException in case of errors
 */
protected Element getDocumentElement(Source source) throws TransformerException {
    if (source == null) {
        return null;
    }
    if (!alwaysTransform && source instanceof DOMSource) {
        Node node = ((DOMSource) source).getNode();
        DOMBuilder domBuilder = new DOMBuilder();
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            return domBuilder.build((org.w3c.dom.Element) node);
        } else if (node.getNodeType() == Node.DOCUMENT_NODE) {
            Document document = domBuilder.build((org.w3c.dom.Document) node);
            return document.getRootElement();
        }
    }
    // we have no other option than to transform
    JDOMResult jdomResult = new JDOMResult();
    transform(source, jdomResult);
    return jdomResult.getDocument().getRootElement();
}

From source file:org.springframework.ws.server.endpoint.adapter.method.dom.JDomPayloadMethodProcessor.java

License:Apache License

@Override
protected Element resolveRequestPayloadArgument(MethodParameter parameter, Source requestPayload)
        throws Exception {
    if (requestPayload instanceof DOMSource) {
        Node node = ((DOMSource) requestPayload).getNode();
        DOMBuilder domBuilder = new DOMBuilder();
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            return domBuilder.build((org.w3c.dom.Element) node);
        } else if (node.getNodeType() == Node.DOCUMENT_NODE) {
            Document document = domBuilder.build((org.w3c.dom.Document) node);
            return document.getRootElement();
        }//from w  ww.  ja  v a2s  . c  om
    }
    // we have no other option than to transform
    JDOMResult jdomResult = new JDOMResult();
    transform(requestPayload, jdomResult);
    return jdomResult.getDocument().getRootElement();
}