Example usage for javax.xml.transform TransformerFactory setErrorListener

List of usage examples for javax.xml.transform TransformerFactory setErrorListener

Introduction

In this page you can find the example usage for javax.xml.transform TransformerFactory setErrorListener.

Prototype

public abstract void setErrorListener(ErrorListener listener);

Source Link

Document

Set the error event listener for the TransformerFactory, which is used for the processing of transformation instructions, and not for the transformation itself.

Usage

From source file:de.uzk.hki.da.metadata.XsltGenerator.java

/**
 * Instantiates a new xslt generator./*from www. j av a 2  s. c  o m*/
 *
 * @param xsltPath the xslt path to the edm mapping file
 * @param inputStream the input stream of the source metadata file
 * @throws FileNotFoundException 
 * @throws TransformerConfigurationException 
 */
public XsltGenerator(String xsltPath, InputStream inputStream)
        throws FileNotFoundException, TransformerConfigurationException {
    if (!new File(xsltPath).exists())
        throw new FileNotFoundException();

    try {
        String theString = IOUtils.toString(inputStream, "UTF-8");
        this.inputStream = new ByteArrayInputStream(theString.getBytes());

        xsltSource = new StreamSource(new FileInputStream(xsltPath));

        TransformerFactory transFact = TransformerFactory.newInstance(TRANSFORMER_FACTORY_CLASS, null);
        transFact.setErrorListener(new CutomErrorListener());

        transformer = null;
        transformer = transFact.newTransformer(xsltSource);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setErrorListener(new CutomErrorListener());

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.uzk.hki.da.convert.PublishXSLTConversionStrategy.java

/**
 * Sets the stylesheet./*from  w w w  . jav a  2 s . c  om*/
 *
 * @param stylesheet the new stylesheet
 * @author Sebastian Cuy
 */
public void setStylesheet(String stylesheet) {
    this.stylesheet = stylesheet;
    try {
        InputStream xsltInputStream = new FileInputStream(stylesheet);
        Source xsltSource = new StreamSource(xsltInputStream);
        TransformerFactory transFact = TransformerFactory.newInstance();
        transFact.setErrorListener(new CutomErrorListener());
        transformer = transFact.newTransformer(xsltSource);
        transformer.setErrorListener(new CutomErrorListener());
        xsltInputStream.close();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:eionet.gdem.conversion.converters.ConvertStrategy.java

/**
 * Method transforms XML source using XSL stream.
 * @param in InputStream containing source XML.
 * @param xslStream InputStream containing XSL content.
 * @param out OutputStream for conversion result.
 * @throws GDEMException In case of unexpected XML or XSL errors.
 *//*from   w  w w  . ja  v a 2 s .  com*/
protected void runXslTransformation(InputStream in, InputStream xslStream, OutputStream out)
        throws GDEMException {
    try {
        TransformerFactory tFactory = transform.getTransformerFactoryInstance();
        TransformerErrorListener errors = new TransformerErrorListener();
        tFactory.setErrorListener(errors);

        StreamSource transformerSource = new StreamSource(xslStream);
        if (getXslPath() != null) {
            transformerSource.setSystemId(getXslPath());
        }

        Transformer transformer = tFactory.newTransformer(transformerSource);
        transformer.setErrorListener(errors);

        transformer.setParameter(DD_DOMAIN_PARAM, Properties.ddURL);
        setTransformerParameters(transformer);
        long l = System.currentTimeMillis();
        transformer.transform(new StreamSource(in), new StreamResult(out));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug((new StringBuilder()).append("generate: transformation needed ")
                    .append(System.currentTimeMillis() - l).append(" ms").toString());
        }
    } catch (TransformerConfigurationException tce) {
        throw new GDEMException("Error transforming XML - incorrect stylesheet file: " + tce.toString(), tce);
    } catch (TransformerException tfe) {
        throw new GDEMException(
                "Error transforming XML - it's not probably well-formed xml file: " + tfe.toString(), tfe);
    } catch (Throwable th) {
        LOGGER.error("Error " + th.toString(), th);
        th.printStackTrace(System.out);
        throw new GDEMException("Error transforming XML: " + th.toString());
    }
}

From source file:eionet.gdem.conversion.converters.ConvertStrategy.java

/**
 * Method transforms XML source to PDF using XSL-FO stream.
 * @param in InputStream containing source XML.
 * @param xsl InputStream containing XSL-FO content.
 * @param out OutputStream for conversion result.
 * @throws GDEMException In case of unexpected XML or XSL errors.
 *//*w  ww  . ja  v  a2 s.c om*/
protected void runFOPTransformation(InputStream in, InputStream xsl, OutputStream out) throws GDEMException {
    try {
        Driver driver = new Driver();
        driver.setRenderer(Driver.RENDER_PDF);
        driver.setOutputStream(out);
        Result res = new SAXResult(driver.getContentHandler());
        Source src = new StreamSource(in);
        TransformerFactory transformerFactory = transform.getTransformerFactoryInstance();
        TransformerErrorListener errors = new TransformerErrorListener();

        transformerFactory.setErrorListener(errors);
        StreamSource transformerSource = new StreamSource(xsl);
        if (getXslPath() != null) {
            transformerSource.setSystemId(getXslPath());
        }

        Transformer transformer = transformerFactory.newTransformer(transformerSource);
        setTransformerParameters(transformer);
        transformer.setErrorListener(errors);

        long l = System.currentTimeMillis();
        transformer.transform(src, res);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug((new StringBuilder()).append("generate: transformation needed ")
                    .append(System.currentTimeMillis() - l).append(" ms").toString());
        }

    } catch (TransformerConfigurationException tce) {
        throw new GDEMException("Error transforming XML to PDF - incorrect stylesheet file: " + tce.toString(),
                tce);
    } catch (TransformerException tfe) {
        throw new GDEMException(
                "Error transforming XML to PDF - it's not probably well-formed xml file: " + tfe.toString(),
                tfe);
    } catch (Throwable e) {
        LOGGER.error("Error " + e.toString(), e);
        throw new GDEMException("Error transforming XML to PDF " + e.toString());
    }
}

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

TransformerFactory configure(TransformerFactory tf) throws TransformerConfigurationException {
    for (KeyValuePair kp : getTransformerFactoryAttributes()) {
        tf.setAttribute(kp.getKey(), kp.getValue());
    }/*from  w w  w  .  j  av a 2  s .c o m*/
    for (KeyValuePair kp : getTransformerFactoryFeatures()) {
        tf.setFeature(kp.getKey(), BooleanUtils.toBoolean(kp.getValue()));
    }
    tf.setErrorListener(new DefaultErrorListener(failOnRecoverableError()));
    return tf;
}

From source file:net.sf.joost.plugins.traxfilter.THResolver.java

private void setupTransformerFactory(TransformerFactory factory, ErrorListener errorListener,
        URIResolver uriResolver) {
    if (errorListener != null)
        factory.setErrorListener(errorListener);
    if (uriResolver != null)
        factory.setURIResolver(uriResolver);
}

From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java

/**
 * @throws XtentisException//  w  ww .j  a va2 s . c om
 * 
 * @ejb.interface-method view-type = "local"
 * @ejb.facade-method
 */
public void init(TransformerPluginContext context, String compiledParameters) throws XtentisException {
    try {
        if (!configurationLoaded) {
            loadConfiguration();
        }
        // fetech the parameters
        CompiledParameters parameters = CompiledParameters.deserialize(compiledParameters);

        // get the xslt compiled style sheet and the Transformer
        /**
         * Unfortunately this does not work for the moment PreparedStylesheet preparedStyleSheet
         * =parameters.getPreparedStyleSheet(); Transformer transformer = preparedStyleSheet.newTransformer();
         **/
        // As a replacement in the meantime
        setCompilationErrors(""); //$NON-NLS-1$

        // USE SAXON for XSLT 2.0 Support
        TransformerFactory transFactory = new net.sf.saxon.TransformerFactoryImpl();
        transFactory.setErrorListener(new ErrorListener() {

            public void error(TransformerException exception) throws TransformerException {
                add2CompilationErrors(exception.getLocalizedMessage());
            }

            public void fatalError(TransformerException exception) throws TransformerException {
                add2CompilationErrors(exception.getLocalizedMessage());
            }

            public void warning(TransformerException exception) throws TransformerException {
                String err = "XSLT Plugin: Warning during the compilation of the XSLT"; //$NON-NLS-1$
                LOG.warn(err, exception);
            }
        });
        transFactory.setAttribute(FeatureKeys.VERSION_WARNING, Boolean.valueOf(false));
        if (!"".equals(getCompilationErrors())) { //$NON-NLS-1$
            String err = "XSLT Plugin: Errors occurred during the compilation of the XSLT:" //$NON-NLS-1$
                    + getCompilationErrors();
            LOG.error(err);
            throw new XtentisException(err);
        }
        Transformer transformer = transFactory
                .newTransformer(new StreamSource(new StringReader(parameters.getXslt())));

        // Pass Parameters to the XSLT processor
        String username = LocalUser.getLocalUser().getUsername();
        transformer.setParameter("USERNAME", username); //$NON-NLS-1$
        transformer.setErrorListener(new ErrorListener() {

            public void error(TransformerException exception) throws TransformerException {
                String err = "XSLT Plugin: An error occured during the XSLT transformation"; //$NON-NLS-1$
                LOG.error(err, exception);
                throw new TransformerException(err);
            }

            public void fatalError(TransformerException exception) throws TransformerException {
                String err = "XSLT Plugin: A fatal error occured during the XSLT transformation"; //$NON-NLS-1$
                LOG.error(err, exception);
                throw new TransformerException(err);
            }

            public void warning(TransformerException exception) throws TransformerException {
                String err = "XSLT Plugin: Warning during the XSLT transformation"; //$NON-NLS-1$
                LOG.warn(err, exception);
            }
        });

        // Insert all this in the context
        context.put(TRANSFORMER, transformer);
        context.put(OUTPUT_METHOD, parameters.getOutputMethod());

    } catch (Exception e) {
        String err = compilationErrors;
        if (err == null || err.length() == 0) {
            err = "Could not init the XSLT Plugin"; //$NON-NLS-1$
        }
        LOG.error(err, e);
        throw new XtentisException(err);
    }

}

From source file:com.flexoodb.common.FlexUtils.java

public String transform(ErrorListener listener, Object xsl, Object xml) {
    String result = "Unable to transform";
    // get the XSL file
    try {//from   w  w w.  j  ava  2  s  .c  o m
        TransformerFactory tFactory = TransformerFactory.newInstance();
        if (listener != null)
            tFactory.setErrorListener(listener);

        StreamSource stylesource = null;
        if (xsl instanceof File) {
            stylesource = new StreamSource(new FileInputStream((File) xsl));
        } else {
            stylesource = new StreamSource(new ByteArrayInputStream(((String) xsl).getBytes()));
        }

        Source source = null;
        if (xml instanceof File) {
            source = new StreamSource(new FileInputStream((File) xml));
        } else {
            source = new StreamSource(new ByteArrayInputStream(((String) xml).getBytes()));
        }

        if (stylesource != null) {
            Transformer transformer = tFactory.newTransformer(stylesource);
            // create a receiver object of the transformation.
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            StreamResult res = new StreamResult(out);
            // transform!
            transformer.transform(source, res);
            // done!
            //result = out.toString().trim();
            result = replaceString(replaceString(out.toString(), " &lt;", "<"), "/&gt;", "/>");

        }
    } catch (Exception e) {
        // return error.
        result = e.getMessage();
    }

    return result;
}

From source file:org.alfresco.repo.template.XSLTProcessor.java

/**
 * @param templateSource/*from  w ww  .j a  va  2 s  .  c  om*/
 * @param model
 * @param out
 */
private void process(TemplateSource templateSource, Object model, Writer out) {
    if ((model == null) || !XSLTemplateModel.class.isAssignableFrom(model.getClass())) {
        throw new IllegalArgumentException("\"model\" must be an XSLTemplateModel object: " + model);
    }

    XSLTemplateModel xsltModel = (XSLTemplateModel) model;
    System.setProperty("org.apache.xalan.extensions.bsf.BSFManager", BSFManager.class.getName());

    Document xslTemplate;
    try {
        xslTemplate = XMLUtil.parse(templateSource.getReader(defaultEncoding));
    } catch (IOException ex) {
        throw new TemplateException(MSG_UNABLE_TO_READ_TEMPLATE, new Object[] { ex.getMessage() }, ex);
    } catch (SAXException sax) {
        throw new TemplateException(MSG_UNABLE_TO_PARSE_TEMPLATE, new Object[] { sax.getMessage() }, sax);
    } finally {
        try {
            templateSource.close();
        } catch (IOException ex) {
            // There's little to be done here. Log it and carry on
            log.warn("Error while trying to close template stream", ex);
        }
    }

    List<String> scriptIds = addScripts(xsltModel, xslTemplate);
    addParameters(xsltModel, xslTemplate);

    final LinkedList<TransformerException> errors = new LinkedList<TransformerException>();
    final ErrorListener errorListener = new ErrorListener() {
        public void error(final TransformerException te) throws TransformerException {
            log.debug("error " + te.getMessageAndLocation());
            errors.add(te);
        }

        public void fatalError(final TransformerException te) throws TransformerException {
            log.debug("fatalError " + te.getMessageAndLocation());
            throw te;
        }

        public void warning(final TransformerException te) throws TransformerException {
            log.debug("warning " + te.getMessageAndLocation());
            errors.add(te);
        }
    };

    final TemplateSource resourceSource = templateSource;
    final URIResolver uriResolver = new URIResolver() {
        public Source resolve(final String href, String base) throws TransformerException {
            if (log.isDebugEnabled()) {
                log.debug("request to resolve href " + href + " using base " + base);
            }
            InputStream in = null;
            try {
                in = resourceSource.getResource(href);
                if (in == null) {
                    throw new TransformerException("unable to resolve href " + href);
                }

                Document d = XMLUtil.parse(in);
                if (log.isDebugEnabled()) {
                    log.debug("loaded " + XMLUtil.toString(d));
                }
                return new DOMSource(d);
            } catch (TransformerException ex) {
                throw ex;
            } catch (Exception e) {
                throw new TransformerException("unable to load " + href, e);
            }
        }
    };

    Source xmlSource = this.getXMLSource(xsltModel);

    Transformer t = null;
    try {
        final TransformerFactory tf = TransformerFactory.newInstance();
        tf.setErrorListener(errorListener);
        tf.setURIResolver(uriResolver);

        if (log.isDebugEnabled()) {
            log.debug("xslTemplate: \n" + XMLUtil.toString(xslTemplate));
        }

        t = tf.newTransformer(new DOMSource(xslTemplate));

        if (errors.size() != 0) {
            final StringBuilder msg = new StringBuilder("errors encountered creating tranformer ... \n");
            for (TransformerException te : errors) {
                msg.append(te.getMessageAndLocation()).append("\n");
            }
            throw new TemplateException(msg.toString());
        }

        t.setErrorListener(errorListener);
        t.setURIResolver(uriResolver);
        t.setParameter("versionParam", "2.0");
    } catch (TransformerConfigurationException tce) {
        log.error(tce);
        throw new TemplateException(tce.getMessage(), tce);
    }

    try {
        t.transform(xmlSource, new StreamResult(out));
    } catch (TransformerException te) {
        log.error(te.getMessageAndLocation());
        throw new TemplateException(te.getMessageAndLocation(), te);
    } catch (Exception e) {
        log.error("unexpected error " + e);
        throw new TemplateException(e.getMessage(), e);
    } finally {
        //Clear out any scripts that were created for this transform
        if (!scriptIds.isEmpty()) {
            XSLTProcessorMethodInvoker.removeMethods(scriptIds);
        }
    }

    if (errors.size() != 0) {
        final StringBuilder msg = new StringBuilder("errors encountered during transformation ... \n");
        for (TransformerException te : errors) {
            msg.append(te.getMessageAndLocation()).append("\n");
        }
        throw new TemplateException(msg.toString());
    }
}

From source file:org.alfresco.web.forms.XSLTRenderingEngine.java

public void render(final Map<QName, Object> model, final RenderingEngineTemplate ret, final Result result)
        throws IOException, RenderingEngine.RenderingException, SAXException {
    System.setProperty("org.apache.xalan.extensions.bsf.BSFManager", BSFManager.class.getName());
    Document xslTemplate = null;/*from   w w w  . jav  a2s. c  o m*/
    try {
        xslTemplate = XMLUtil.parse(ret.getInputStream());
    } catch (final SAXException sax) {
        throw new RenderingEngine.RenderingException(sax);
    }
    this.addScripts(model, xslTemplate);
    this.addParameters(model, xslTemplate);

    final LinkedList<TransformerException> errors = new LinkedList<TransformerException>();
    final ErrorListener errorListener = new ErrorListener() {
        public void error(final TransformerException te) throws TransformerException {
            LOGGER.debug("error " + te.getMessageAndLocation());
            errors.add(te);
        }

        public void fatalError(final TransformerException te) throws TransformerException {
            LOGGER.debug("fatalError " + te.getMessageAndLocation());
            throw te;
        }

        public void warning(final TransformerException te) throws TransformerException {
            LOGGER.debug("warning " + te.getMessageAndLocation());
            errors.add(te);
        }
    };

    // create a uri resolver to resolve document() calls to the virtualized
    // web application
    final URIResolver uriResolver = new URIResolver() {
        public Source resolve(final String href, String base) throws TransformerException {
            LOGGER.debug("request to resolve href " + href + " using base " + base);
            final RenderingEngine.TemplateResourceResolver trr = (RenderingEngine.TemplateResourceResolver) model
                    .get(RenderingEngineTemplateImpl.PROP_RESOURCE_RESOLVER);

            InputStream in = null;
            try {
                in = trr.resolve(href);
            } catch (Exception e) {
                throw new TransformerException("unable to load " + href, e);
            }

            if (in == null) {
                throw new TransformerException("unable to resolve href " + href);
            }

            try {
                final Document d = XMLUtil.parse(in);
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("loaded " + XMLUtil.toString(d));
                return new DOMSource(d);
            } catch (Exception e) {
                throw new TransformerException("unable to load " + href, e);
            }
        }
    };

    Source xmlSource = this.getXMLSource(model);

    Transformer t = null;
    try {
        final TransformerFactory tf = TransformerFactory.newInstance();
        tf.setErrorListener(errorListener);
        tf.setURIResolver(uriResolver);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("xslTemplate: \n" + XMLUtil.toString(xslTemplate));
        }

        t = tf.newTransformer(new DOMSource(xslTemplate));

        if (errors.size() != 0) {
            final StringBuilder msg = new StringBuilder("errors encountered creating tranformer ... \n");
            for (TransformerException te : errors) {
                msg.append(te.getMessageAndLocation()).append("\n");
            }
            throw new RenderingEngine.RenderingException(msg.toString());
        }

        t.setErrorListener(errorListener);
        t.setURIResolver(uriResolver);
        t.setParameter("versionParam", "2.0");
    } catch (TransformerConfigurationException tce) {
        LOGGER.error(tce);
        throw new RenderingEngine.RenderingException(tce);
    }

    try {
        t.transform(xmlSource, result);
    } catch (TransformerException te) {
        LOGGER.error(te.getMessageAndLocation());
        throw new RenderingEngine.RenderingException(te);
    } catch (Exception e) {
        LOGGER.error("unexpected error " + e);
        throw new RenderingEngine.RenderingException(e);
    }

    if (errors.size() != 0) {
        final StringBuilder msg = new StringBuilder("errors encountered during transformation ... \n");
        for (TransformerException te : errors) {
            msg.append(te.getMessageAndLocation()).append("\n");
        }
        throw new RenderingEngine.RenderingException(msg.toString());
    }
}