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

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

Introduction

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

Prototype

public void setSystemId(File f) 

Source Link

Document

Set the system ID from a File reference.

Usage

From source file:org.apache.bsf.engines.xslt.XSLTEngine.java

/**
 * Evaluate an expression. In this case, an expression is assumed
 * to be a stylesheet of the template style (see the XSLT spec).
 *///  ww w  . j  a v  a  2s. c om
public Object eval(String source, int lineNo, int columnNo, Object oscript) throws BSFException {
    // get the style base URI (the place from where Xerces XSLT will
    // look for imported/included files and referenced docs): if a
    // bean named "xslt:styleBaseURI" is registered, then cvt it
    // to a string and use that. Otherwise use ".", which means the
    // base is the directory where the process is running from
    Object sbObj = mgr.lookupBean("xslt:styleBaseURI");
    String styleBaseURI = (sbObj == null) ? "." : sbObj.toString();

    // Locate the stylesheet.
    StreamSource styleSource;

    styleSource = new StreamSource(new StringReader(oscript.toString()));
    styleSource.setSystemId(styleBaseURI);

    try {
        transformer = tFactory.newTransformer(styleSource);
    } catch (Exception e) {
        logger.error("Exception from Xerces XSLT:", e);
        throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "Exception from Xerces XSLT: " + e, e);
    }

    // get the src to work on: if a bean named "xslt:src" is registered
    // and its a Node, then use it as the source. If its not a Node, then
    // if its a URL parse it, if not treat it as a file and make a URL and
    // parse it and go. If no xslt:src is found, use an empty document
    // (stylesheet is treated as a literal result element stylesheet)
    Object srcObj = mgr.lookupBean("xslt:src");
    Object xis = null;
    if (srcObj != null) {
        if (srcObj instanceof Node) {
            xis = new DOMSource((Node) srcObj);
        } else {
            try {
                String mesg = "as anything";
                if (srcObj instanceof Reader) {
                    xis = new StreamSource((Reader) srcObj);
                    mesg = "as a Reader";
                } else if (srcObj instanceof File) {
                    xis = new StreamSource((File) srcObj);
                    mesg = "as a file";
                } else {
                    String srcObjstr = srcObj.toString();
                    xis = new StreamSource(new StringReader(srcObjstr));
                    if (srcObj instanceof URL) {
                        mesg = "as a URL";
                    } else {
                        ((StreamSource) xis).setPublicId(srcObjstr);
                        mesg = "as an XML string";
                    }
                }

                if (xis == null) {
                    throw new Exception("Unable to get input from '" + srcObj + "' " + mesg);
                }
            } catch (Exception e) {
                throw new BSFException(BSFException.REASON_EXECUTION_ERROR,
                        "BSF:XSLTEngine: unable to get " + "input from '" + srcObj + "' as XML", e);
            }
        }
    } else {
        // create an empty document - real src must come into the 
        // stylesheet using "doc(...)" [see XSLT spec] or the stylesheet
        // must be of literal result element type
        xis = new StreamSource();
    }

    // set all declared beans as parameters.
    for (int i = 0; i < declaredBeans.size(); i++) {
        BSFDeclaredBean b = (BSFDeclaredBean) declaredBeans.elementAt(i);
        transformer.setParameter(b.name, new XObject(b.bean));
    }

    // declare a "bsf" parameter which is the BSF handle so that 
    // the script can do BSF stuff if it wants to
    transformer.setParameter("bsf", new XObject(new BSFFunctions(mgr, this)));

    // do it
    try {
        DOMResult result = new DOMResult();
        transformer.transform((StreamSource) xis, result);
        return new XSLTResultNode(result.getNode());
    } catch (Exception e) {
        throw new BSFException(BSFException.REASON_EXECUTION_ERROR, "exception while eval'ing XSLT script" + e,
                e);
    }
}

From source file:org.projectforge.framework.renderer.PdfRenderer.java

public byte[] render(final String stylesheet, final String groovyXml, final Map<String, Object> data) {
    final PFUserDO user = ThreadLocalUserContext.getUser();
    data.put("createdLabel", ThreadLocalUserContext.getLocalizedString("created"));
    data.put("loggedInUser", user);
    data.put("baseDir", configurationService.getResourceDir());
    data.put("logoFile", configurationService.getResourceDir() + "/images/" + logoFileName);
    data.put("appId", AppVersion.APP_ID);
    data.put("appVersion", AppVersion.NUMBER);
    data.put("organization", StringUtils.defaultString(
            Configuration.getInstance().getStringValue(ConfigurationParam.ORGANIZATION), AppVersion.APP_ID));
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    log.info("stylesheet=" + stylesheet + ", jellyXml=" + groovyXml + ", baseDir="
            + configurationService.getResourceDir() + ", fontBaseDir=" + getFontResourcePath());

    // configure fopFactory as desired
    final FopFactory fopFactory = FopFactory.newInstance();

    try {/*www .  j av a 2 s.com*/
        fopFactory.getFontManager().setFontBaseURL(getFontResourcePath());
    } catch (final MalformedURLException ex) {
        log.error(ex.getMessage(), ex);
    }

    final FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
    try {
        foUserAgent.getFactory().getFontManager().setFontBaseURL(getFontResourcePath());
    } catch (final MalformedURLException ex) {
        log.error(ex.getMessage(), ex);
    }
    // configure foUserAgent as desired

    InputStream xsltInputStream = null;
    try {
        // Construct fop with desired output format
        final Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, baos);

        // Setup XSLT
        final TransformerFactory factory = TransformerFactory.newInstance();
        Object[] result = configurationService.getResourceAsInputStream(stylesheet);
        xsltInputStream = (InputStream) result[0];
        final StreamSource xltStreamSource = new StreamSource(xsltInputStream);
        final String url = (String) result[1];
        if (url == null) {
            log.error("Url of xsl resource is null.");
            throw new InternalErrorException();
        }
        xltStreamSource.setSystemId(url);

        final Transformer transformer = factory.newTransformer(xltStreamSource);

        // Set the value of a <param> in the stylesheet
        for (final Map.Entry<String, Object> entry : data.entrySet()) {
            transformer.setParameter(entry.getKey(), entry.getValue());
        }

        // First run jelly through xmlData:
        result = configurationService.getResourceContentAsString(groovyXml);
        final GroovyEngine groovyEngine = new GroovyEngine(configurationService, data,
                ThreadLocalUserContext.getLocale(), ThreadLocalUserContext.getTimeZone());
        final String groovyXmlInput = groovyEngine.preprocessGroovyXml((String) result[0]);
        final String xmlData = groovyEngine.executeTemplate(groovyXmlInput);

        // Setup input for XSLT transformation
        final StringReader xmlDataReader = new StringReader(xmlData);
        final Source src = new StreamSource(xmlDataReader);

        // Resulting SAX events (the generated FO) must be piped through to FOP
        final Result res = new SAXResult(fop.getDefaultHandler());

        // Start XSLT transformation and FOP processing
        transformer.transform(src, res);
    } catch (final FOPException ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    } catch (final TransformerConfigurationException ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    } catch (final TransformerException ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    } finally {
        try {
            baos.close();
        } catch (final IOException ex) {
            log.error(ex.getMessage(), ex);
            throw new RuntimeException(ex);
        }
        IOUtils.closeQuietly(xsltInputStream);
    }
    return baos.toByteArray();
}

From source file:org.projectforge.renderer.PdfRenderer.java

public byte[] render(final String stylesheet, final String groovyXml, final Map<String, Object> data) {
    // initialize();
    final PFUserDO user = PFUserContext.getUser();
    data.put("createdLabel", PFUserContext.getLocalizedString("created"));
    data.put("loggedInUser", user);
    data.put("baseDir", configXml.getResourcePath());
    data.put("appId", AppVersion.APP_ID);
    data.put("appVersion", AppVersion.NUMBER);
    data.put("organization", StringUtils.defaultString(
            Configuration.getInstance().getStringValue(ConfigurationParam.ORGANIZATION), AppVersion.APP_ID));
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    log.info("stylesheet=" + stylesheet + ", jellyXml=" + groovyXml + ", baseDir=" + configXml.getResourcePath()
            + ", fontBaseDir=" + getFontResourcePath());
    // fopRenderer.processFo(styleSheet, xmlData, data, new PdfFopOutput(baos));
    // return baos.toByteArray();

    // configure fopFactory as desired
    final FopFactory fopFactory = FopFactory.newInstance();
    // Configuration cfg = fopFactory.getUserConfig();

    try {//from  w ww .j a  va2s.c o m
        fopFactory.getFontManager().setFontBaseURL(getFontResourcePath());
    } catch (final MalformedURLException ex) {
        log.error(ex.getMessage(), ex);
    }
    /*
     * try { fopFactory.setUserConfig(baseDir + "/fop.config"); } catch (SAXException ex) { log.error(ex.getMessage(), ex); throw new
     * RuntimeException(ex); } catch (IOException ex) { log.error(ex.getMessage(), ex); throw new RuntimeException(ex); }
     */
    final FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
    try {
        foUserAgent.getFactory().getFontManager().setFontBaseURL(getFontResourcePath());
    } catch (final MalformedURLException ex) {
        log.error(ex.getMessage(), ex);
    }
    // configure foUserAgent as desired

    try {
        // Construct fop with desired output format
        final Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, baos);

        // Setup XSLT
        final TransformerFactory factory = TransformerFactory.newInstance();
        Object[] result = configXml.getInputStream(stylesheet);
        final InputStream xsltInputStream = (InputStream) result[0];
        final StreamSource xltStreamSource = new StreamSource(xsltInputStream);
        final String url = (String) result[1];
        if (url == null) {
            log.error("Url of xsl resource is null.");
            throw new InternalErrorException();
        }
        xltStreamSource.setSystemId(url);

        final Transformer transformer = factory.newTransformer(xltStreamSource);

        // Set the value of a <param> in the stylesheet
        for (final Map.Entry<String, Object> entry : data.entrySet()) {
            transformer.setParameter(entry.getKey(), entry.getValue());
        }

        // First run jelly through xmlData:
        result = configXml.getContent(groovyXml);
        final GroovyEngine groovyEngine = new GroovyEngine(data, PFUserContext.getLocale(),
                PFUserContext.getTimeZone());
        final String groovyXmlInput = groovyEngine.preprocessGroovyXml((String) result[0]);
        final String xmlData = groovyEngine.executeTemplate(groovyXmlInput);

        // Setup input for XSLT transformation
        final StringReader xmlDataReader = new StringReader(xmlData);
        final Source src = new StreamSource(xmlDataReader);

        // Resulting SAX events (the generated FO) must be piped through to FOP
        final Result res = new SAXResult(fop.getDefaultHandler());

        // Start XSLT transformation and FOP processing
        transformer.transform(src, res);
    } catch (final FOPException ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    } catch (final TransformerConfigurationException ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    } catch (final TransformerException ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    } finally {
        try {
            baos.close();
        } catch (final IOException ex) {
            log.error(ex.getMessage(), ex);
            throw new RuntimeException(ex);
        }
    }
    return baos.toByteArray();
}