Example usage for javax.xml.transform.stream StreamSource StreamSource

List of usage examples for javax.xml.transform.stream StreamSource StreamSource

Introduction

In this page you can find the example usage for javax.xml.transform.stream StreamSource StreamSource.

Prototype

public StreamSource(Reader reader, String systemId) 

Source Link

Document

Construct a StreamSource from a character reader.

Usage

From source file:com.google.code.docbook4j.XslURIResolver.java

public Source resolve(String href, String base) throws TransformerException {

    log.debug("Resolving href={} for base={}", href, base);

    if (href == null || href.trim().length() == 0)
        return null;

    if (docbookXslBase == null && href.startsWith("res:") && href.endsWith("docbook.xsl")) {
        try {/*w ww.  jav  a 2s.  c o m*/
            docbookXslBase = FileObjectUtils.resolveFile(href).getParent().getURL().toExternalForm();
        } catch (FileSystemException e) {
            docbookXslBase = null;
        }
    }

    String normalizedBase = null;
    if (base != null) {
        try {
            normalizedBase = FileObjectUtils.resolveFile(base).getParent().getURL().toExternalForm();
        } catch (FileSystemException e) {
            normalizedBase = null;
        }
    }

    try {

        FileObject urlFileObject = FileObjectUtils.resolveFile(href, normalizedBase);

        if (!urlFileObject.exists())
            throw new FileSystemException("File object not found: " + urlFileObject);

        return new StreamSource(urlFileObject.getContent().getInputStream(),
                urlFileObject.getURL().toExternalForm());

    } catch (FileSystemException e) {

        // not exists for given base? try with docbook base...
        try {
            if (docbookXslBase != null) {
                FileObject urlFileObject = FileObjectUtils.resolveFile(href, docbookXslBase);
                return new StreamSource(urlFileObject.getContent().getInputStream(),
                        urlFileObject.getURL().toExternalForm());
            }

        } catch (FileSystemException e1) {
            // do nothing.
        }

        log.error("Error resolving href=" + href + " for base=" + base, e);
    }

    return null;

}

From source file:com.twinsoft.convertigo.engine.print.PrintHTML.java

@Override
public String print(String location) throws IOException, EngineException, SAXException,
        TransformerFactoryConfigurationError, TransformerException, ParserConfigurationException {
    super.print(location);
    out.close();//www.j  a v a 2 s.com

    updateStatus("Create Ressources Directory", 70);

    //get the dom
    Document fopResult = XMLUtils.parseDOM(outputFile);
    Element root = fopResult.getDocumentElement();
    String templateFileName = Engine.TEMPLATES_PATH + "/doc/doc.html.xsl";
    File htmlFile = new File(templateFileName);
    Source xsltSrc = new StreamSource(new FileInputStream(htmlFile), localizedDir);

    //create the ressources repository               
    String ressourcesFolder = outputFolder + "/ressources";
    File repository = new File(ressourcesFolder);
    if (!repository.exists()) {
        repository.mkdir();
    }

    //export images
    NodeList images = fopResult.getElementsByTagName("image");
    Node image;
    String attrImg, attrImgName;
    InputStream imagesIn;
    OutputStream imagesOut;
    for (int i = 0; i < images.getLength(); i++) {
        image = images.item(i);
        attrImg = image.getAttributes().getNamedItem("url").getTextContent();
        attrImgName = attrImg.replaceAll("(.*)/", "");
        image.getAttributes().getNamedItem("url").setTextContent(attrImgName);
        imagesIn = new FileInputStream(attrImg);
        imagesOut = new FileOutputStream(ressourcesFolder + "/" + attrImgName);
        org.apache.commons.io.IOUtils.copy(imagesIn, imagesOut);
        imagesIn.close();
        imagesOut.close();
    }

    //export css
    FileInputStream cssIn = new FileInputStream(Engine.TEMPLATES_PATH + "/doc/style.css");
    FileOutputStream cssOut = new FileOutputStream(ressourcesFolder + "/style.css");
    org.apache.commons.io.IOUtils.copy(cssIn, cssOut);
    cssIn.close();
    cssOut.close();

    updateStatus("HTML Transformation", 85);

    // transformation of the dom
    Transformer xslt = TransformerFactory.newInstance().newTransformer(xsltSrc);
    Element xsl = fopResult.createElement("xsl");
    xslt.transform(new DOMSource(fopResult), new DOMResult(xsl));
    fopResult.removeChild(root);
    fopResult.appendChild(xsl.getFirstChild());

    //write the dom
    String newOutputFileName = outputFolder + "/" + projectName + ".html";
    outputFile = new File(newOutputFileName);
    out = new FileOutputStream(outputFile);
    out = new java.io.BufferedOutputStream(out);
    OutputStreamWriter output = new OutputStreamWriter(out);
    output.write(XMLUtils.prettyPrintDOM(fopResult));
    output.close();

    //remove the temp file
    new File(outputFileName).delete();

    updateStatus("Printing finished", 100);

    return newOutputFileName;
}

From source file:dk.statsbiblioteket.util.xml.XSLT.java

/**
 * Creates a new transformer based on the given XSLTLocation.
 * Useful for e.g. using Saxon instead of the default Xalan.
 *
 * @param factory the factory to use for creating the transformer.
 * @param xslt the location of the XSLT.
 * @return a Transformer based on the given XSLT.
 * @throws javax.xml.transform.TransformerException thrown if for some
 *          reason a Transformer could not be instantiated.
 *          This is normally due to problems with the {@code xslt} URL
 * @see #getLocalTransformer for reusing Transformers.
 *///  w  ww  .  j  a v  a 2s.c  om
public static Transformer createTransformer(TransformerFactory factory, URL xslt) throws TransformerException {
    log.trace("createTransformer: Requesting and compiling XSLT from '" + xslt + "'");
    final long startTime = System.nanoTime();

    InputStream in = null;
    Transformer transformer;
    try {
        if (xslt == null) {
            throw new NullPointerException("xslt URL is null");
        }
        in = xslt.openStream();
        transformer = factory.newTransformer(new StreamSource(in, xslt.toString()));
        transformer.setErrorListener(getErrorListener());
    } catch (TransformerException e) {
        throw new TransformerException(String.format(
                "Unable to instantiate Transformer, a system configuration error for XSLT at '%s'", xslt), e);
    } catch (MalformedURLException e) {
        throw new TransformerException(String.format("The URL to the XSLT is not a valid URL: '%s'", xslt), e);
    } catch (IOException e) {
        throw new TransformerException(
                String.format("Unable to open the XSLT resource due to IOException '%s'", xslt), e);
    } catch (Exception e) {
        throw new TransformerException(String.format("Unable to open the XSLT resource '%s'", xslt), e);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            log.warn("Non-fatal IOException while closing stream to '" + xslt + "'");
        }
    }
    log.debug("createTransformer: Requested and compiled XSLT from '" + xslt + "' in "
            + (System.nanoTime() - startTime) / 1000000 + "ms");
    return transformer;
}

From source file:eu.europa.ejusticeportal.dss.controller.config.Config.java

/**
 * //from   ww  w . j ava  2  s. c  o m
 * The default constructor for SigningContextRepositoryXmlImpl.
 */
private Config() {

    InputStream is = null;
    try {
        is = Config.class.getClassLoader().getResourceAsStream("signingcontext-v1.xsd");
        StreamSource source = new StreamSource(is, CardProfileNamespace.NS);
        schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(source);

    } catch (SAXException e) {
        LOGGER.error("Unable to load XML validation schema - validation of configuration xml will not be done.",
                e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.adaptris.util.text.xml.Resolver.java

/**
 * @see URIResolver#resolve(java.lang.String, java.lang.String)
 *///from  w w  w  .ja v  a2 s  .com
@Override
public Source resolve(String href, String base) throws TransformerException {
    debugLog("Resolving [{}][{}]", href, base);
    StreamSource result = null;
    try {
        URL myUrl = null;
        try {
            myUrl = new URL(href);
        } catch (Exception ex) {
            // Indicates that the URL was probably relative and therefore Malformed
            int end = base.lastIndexOf('/');
            String url = base.substring(0, end + 1);
            myUrl = new URL(url + href);
        }
        StreamSource ret = new StreamSource(retrieveAndCache(new URLString(myUrl)), myUrl.toExternalForm());
        result = ret;
    } catch (Exception e) {
        debugLog("Couldn't handle [{}][{}], fallback to default parser behaviour", href, base);
        result = null;
    }
    return result;
}