Example usage for javax.xml.transform TransformerException TransformerException

List of usage examples for javax.xml.transform TransformerException TransformerException

Introduction

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

Prototype

public TransformerException(String message, SourceLocator locator) 

Source Link

Document

Create a new TransformerException from a message and a Locator.

Usage

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

private static ErrorListener getErrorListener() {
    if (ERRORLISTENER == null) {
        ERRORLISTENER = new ErrorListener() {
            @Override//from  w  w  w. j a  va 2 s .co  m
            public void warning(TransformerException exception) throws TransformerException {
                warnlog.debug("A transformer warning occured", exception);
            }

            @Override
            public void error(TransformerException exception) throws TransformerException {
                throw new TransformerException("A Transformer error occured", exception);
            }

            @Override
            public void fatalError(TransformerException exception) throws TransformerException {
                throw new TransformerException("A Transformer exception occurred", exception);
            }
        };
    }
    return ERRORLISTENER;
}

From source file:net.sf.joost.trax.TransformerImpl.java

/**
 * Transforms a xml-source : SAXSource, DOMSource, StreamSource to SAXResult,
 * DOMResult and StreamResult//from ww  w  . j a va  2  s  . c  o m
 *
 * @param xmlSource A <code>Source</code>
 * @param result A <code>Result</code>
 * @throws TransformerException
 */
public void transform(Source xmlSource, Result result) throws TransformerException {

    StxEmitter out = null;
    SAXSource saxSource = null;

    // should be synchronized
    synchronized (reentryGuard) {
        if (DEBUG)
            log.debug("perform transformation from " + "xml-source(SAXSource, DOMSource, StreamSource) "
                    + "to SAXResult, DOMResult or StreamResult");
        try {

            // init StxEmitter
            out = TrAXHelper.initStxEmitter(result, processor, null);
            out.setSystemId(result.getSystemId());

            this.processor.setContentHandler(out);
            this.processor.setLexicalHandler(out);

            // register ErrorListener
            if (this.errorListener != null) {
                this.processor.setErrorListener(errorListener);
            }

            // construct from source a SAXSource
            saxSource = TrAXHelper.getSAXSource(xmlSource, errorListener);

            InputSource isource = saxSource.getInputSource();

            if (isource != null) {
                if (DEBUG)
                    log.debug("perform transformation");

                if (saxSource.getXMLReader() != null) {
                    // should not be an DOMSource
                    if (xmlSource instanceof SAXSource) {

                        XMLReader xmlReader = ((SAXSource) xmlSource).getXMLReader();

                        /**
                         * URIs for Identifying Feature Flags and Properties :
                         * There is no fixed set of features or properties
                         * available for SAX2, except for two features that all XML
                         * parsers must support. Implementors are free to define
                         * new features and properties as needed, using URIs to
                         * identify them.
                         *
                         * All XML readers are required to recognize the
                         * "http://xml.org/sax/features/namespaces" and the
                         * "http://xml.org/sax/features/namespace-prefixes"
                         * features (at least to get the feature values, if not set
                         * them) and to support a true value for the namespaces
                         * property and a false value for the namespace-prefixes
                         * property. These requirements ensure that all SAX2 XML
                         * readers can provide the minimal required Namespace
                         * support for higher-level specs such as RDF, XSL, XML
                         * Schemas, and XLink. XML readers are not required to
                         * recognize or support any other features or any
                         * properties.
                         *
                         * For the complete list of standard SAX2 features and
                         * properties, see the {@link org.xml.sax} Package
                         * Description.
                         */
                        if (xmlReader != null) {
                            try {
                                // set the required
                                // "http://xml.org/sax/features/namespaces" Feature
                                xmlReader.setFeature(FEAT_NS, true);
                                // set the required
                                // "http://xml.org/sax/features/namespace-prefixes"
                                // Feature
                                xmlReader.setFeature(FEAT_NSPREFIX, false);
                                // maybe there would be other features
                            } catch (SAXException sE) {
                                getErrorListener().warning(new TransformerException(sE.getMessage(), sE));
                            }
                        }
                    }
                    // set the the SAXSource as the parent of the STX-Processor
                    this.processor.setParent(saxSource.getXMLReader());
                }

                // perform transformation
                this.processor.parse(isource);
            } else {
                TransformerException tE = new TransformerException(
                        "InputSource is null - could not perform transformation");
                getErrorListener().fatalError(tE);
            }
            // perform result
            performResults(result, out);
        } catch (SAXException ex) {
            TransformerException tE;
            Exception emb = ex.getException();
            if (emb instanceof TransformerException) {
                tE = (TransformerException) emb;
            } else {
                tE = new TransformerException(ex.getMessage(), ex);
            }
            getErrorListener().fatalError(tE);
        } catch (IOException ex) {
            // will this ever happen?
            getErrorListener().fatalError(new TransformerException(ex.getMessage(), ex));
        }
    }
}

From source file:org.walkmod.conf.providers.YAMLConfigurationProvider.java

public void write(JsonNode node) throws TransformerException {
    if (node != null) {
        File cfg = new File(fileName);

        FileOutputStream fos = null;
        try {//w  w w. j  av  a2  s  . c  o  m
            fos = new FileOutputStream(cfg);
            JsonGenerator generator = mapper.getFactory().createGenerator(fos);

            generator.useDefaultPrettyPrinter();
            mapper.writeTree(generator, node);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new TransformerException("Error writting the configuration", e);
                }
            }
        }
    }
}

From source file:com.rest4j.generator.Generator.java

@Override
public Source resolve(String href, String base) throws TransformerException {
    String uri = href;//from  w  ww.  j  a  v a 2s  .c o  m
    URL found = tryFind(href);
    if (found == null) {
        try {
            URL url;

            if (base == null) {
                found = new URL(uri);
            } else {
                URL baseURL = new URL(base);
                found = (href.length() == 0 ? baseURL : new URL(baseURL, uri));
            }
        } catch (java.net.MalformedURLException mue) {
            // try to make an absolute URI from the current base
            String absBase = makeAbsolute(base);
            if (!absBase.equals(base)) {
                // don't bother if the absBase isn't different!
                return resolve(href, absBase);
            } else {
                throw new TransformerException("Malformed URL " + href + "(base " + base + ")", mue);
            }
        }
    }

    SAXSource source = new SAXSource();
    source.setInputSource(new InputSource(found.toString()));
    return source;
}

From source file:org.ambraproject.article.service.XslIngestArchiveProcessor.java

/**
 * Run the zip file through the xsl stylesheet
 *
 * @param zip          the zip archive containing the items to ingest
 * @param zipInfo      the document describing the zip archive (adheres to zip.dtd)
 * @param articleXml      the stylesheet to run on <var>zipInfo</var>; this is the main script
 * @param doiUrlPrefix DOI URL prefix/*from w  w w  .  j  a  va  2  s. c om*/
 * @return a document describing the fedora objects to create (must adhere to fedora.dtd)
 * @throws javax.xml.transform.TransformerException
 *          if an error occurs during the processing
 */
private Document transformZip(ZipFile zip, String zipInfo, Document articleXml, String doiUrlPrefix)
        throws TransformerException, URISyntaxException {
    Transformer t = getTranslet(articleXml);
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    t.setURIResolver(new ZipURIResolver(zip));

    // override the doi url prefix if one is specified in the config
    if (doiUrlPrefix != null)
        t.setParameter("doi-url-prefix", doiUrlPrefix);

    /*
     * Note: it would be preferable (and correct according to latest JAXP specs) to use
     * t.setErrorListener(), but Saxon does not forward <xls:message>'s to the error listener.
     * Hence we need to use Saxon's API's in order to get at those messages.
     */
    final StringWriter msgs = new StringWriter();
    MessageWarner em = new MessageWarner();
    ((Controller) t).setMessageEmitter(em);
    t.setErrorListener(new ErrorListener() {
        public void warning(TransformerException te) {
            log.warn("Warning received while processing zip", te);
        }

        public void error(TransformerException te) {
            log.warn("Error received while processing zip", te);
            msgs.write(te.getMessageAndLocation() + '\n');
        }

        public void fatalError(TransformerException te) {
            log.warn("Fatal error received while processing zip", te);
            msgs.write(te.getMessageAndLocation() + '\n');
        }
    });

    Source inp = new StreamSource(new StringReader(zipInfo), "zip:/");
    DOMResult res = new DOMResult();

    try {
        t.transform(inp, res);
    } catch (TransformerException te) {
        if (msgs.getBuffer().length() > 0) {
            log.error(msgs.getBuffer().toString());
            throw new TransformerException(msgs.toString(), te);
        } else
            throw te;
    }
    if (msgs.getBuffer().length() > 0)
        throw new TransformerException(msgs.toString());
    return (Document) res.getNode();
}

From source file:net.sf.jabref.logic.xmp.XMPUtil.java

/**
 * Try to write the given BibTexEntry in the XMP-stream of the given
 * PDF-file./*from  w ww  . ja  va  2  s  . co m*/
 *
 * Throws an IOException if the file cannot be read or written, so the user
 * can remove a lock or cancel the operation.
 *
 * The method will overwrite existing BibTeX-XMP-data, but keep other
 * existing metadata.
 *
 * @param file
 *            The file to write the entries to.
 * @param bibtexEntries
 *            The entries to write to the file. *
 * @param database
 *            maybenull An optional database which the given bibtex entries
 *            belong to, which will be used to resolve strings. If the
 *            database is null the strings will not be resolved.
 * @param writePDFInfo
 *            Write information also in PDF document properties
 * @throws TransformerException
 *             If the entry was malformed or unsupported.
 * @throws IOException
 *             If the file could not be written to or could not be found.
 */
public static void writeXMP(File file, Collection<BibEntry> bibtexEntries, BibDatabase database,
        boolean writePDFInfo) throws IOException, TransformerException {

    Collection<BibEntry> resolvedEntries;
    if (database == null) {
        resolvedEntries = bibtexEntries;
    } else {
        resolvedEntries = database.resolveForStrings(bibtexEntries, false);
    }

    try (PDDocument document = PDDocument.load(file.getAbsoluteFile())) {
        if (document.isEncrypted()) {
            throw new EncryptedPdfsNotSupportedException();
        }

        if (writePDFInfo && (resolvedEntries.size() == 1)) {
            XMPUtil.writeDocumentInformation(document, resolvedEntries.iterator().next(), null);
            XMPUtil.writeDublinCore(document, resolvedEntries, null);
        }

        PDDocumentCatalog catalog = document.getDocumentCatalog();
        PDMetadata metaRaw = catalog.getMetadata();

        XMPMetadata meta;
        if (metaRaw == null) {
            meta = new XMPMetadata();
        } else {
            meta = new XMPMetadata(XMLUtil.parse(metaRaw.createInputStream()));
        }
        meta.addXMLNSMapping(XMPSchemaBibtex.NAMESPACE, XMPSchemaBibtex.class);

        // Remove all current Bibtex-schemas
        List<XMPSchema> schemas = meta.getSchemasByNamespaceURI(XMPSchemaBibtex.NAMESPACE);
        for (XMPSchema schema : schemas) {
            XMPSchemaBibtex bib = (XMPSchemaBibtex) schema;
            bib.getElement().getParentNode().removeChild(bib.getElement());
        }

        for (BibEntry e : resolvedEntries) {
            XMPSchemaBibtex bibtex = new XMPSchemaBibtex(meta);
            meta.addSchema(bibtex);
            bibtex.setBibtexEntry(e, null);
        }

        // Save to stream and then input that stream to the PDF
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        meta.save(os);
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        PDMetadata metadataStream = new PDMetadata(document, is, false);
        catalog.setMetadata(metadataStream);

        // Save
        try {
            document.save(file.getAbsolutePath());
        } catch (COSVisitorException e) {
            LOGGER.debug("Could not write XMP metadata", e);
            throw new TransformerException("Could not write XMP metadata: " + e.getLocalizedMessage(), e);
        }
    }
}

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  a  2s  . 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());
    }
}

From source file:org.apache.fop.apps.FOURIResolver.java

/**
 * Handles resolve exceptions appropriately.
 *
 * @param e//  w w  w  . j  a v a 2s . co  m
 *            the exception
 * @param errorStr
 *            error string
 * @param strict
 *            strict user config
 */
private void handleException(Exception e, String errorStr, boolean strict) throws TransformerException {
    if (strict) {
        throw new TransformerException(errorStr, e);
    }
    log.error(e.getMessage());
}

From source file:org.apache.fop.fonts.apps.AbstractFontReader.java

/**
 * Writes the generated DOM Document to a file.
 *
 * @param   doc The DOM Document to save.
 * @param   target The target file for the XML file.
 * @throws TransformerException if an error occurs during serialization
 *//* ww w .j  a  va 2  s.  c om*/
public void writeFontXML(org.w3c.dom.Document doc, File target) throws TransformerException {
    log.info("Writing xml font file " + target + "...");

    try {
        OutputStream out = new java.io.FileOutputStream(target);
        out = new java.io.BufferedOutputStream(out);
        try {
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.transform(new javax.xml.transform.dom.DOMSource(doc),
                    new javax.xml.transform.stream.StreamResult(out));
        } finally {
            out.close();
        }
    } catch (IOException ioe) {
        throw new TransformerException("Error writing the output file", ioe);
    }
}

From source file:org.clazzes.odtransform.ZipFileURIResolver.java

public Source resolve(String href, String base) throws TransformerException {
    try {//from ww  w . j av  a  2s .co m
        URI uri = new URI(href);

        if (uri.isAbsolute())
            return null;

        log.debug("Resolving relative URI [" + href + "].");

        return new StreamSource(this.zipFile.getInputStream(new ZipEntry(href)));

    } catch (URISyntaxException e) {
        throw new TransformerException("Invalid URI", e);
    } catch (IOException e) {
        throw new TransformerException("Unexpected I/O error", e);
    }
}