Example usage for javax.xml.transform TransformerConfigurationException getCause

List of usage examples for javax.xml.transform TransformerConfigurationException getCause

Introduction

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

Prototype

@Override
public Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:Main.java

/**
 * This method performs XSL Transformation. <br>
 * <b>Deprecated use XmlTransformer.transform</b>
 * /* w w w  .  j  a va2s  .  c  o m*/
 * @param source
 *            The input XML document
 * @param stylesheet
 *            The XSL stylesheet
 * @param params
 *            parameters to apply to the XSL Stylesheet
 * @param outputProperties
 *            properties to use for the xsl transform. Will overload the xsl output definition.
 * @return The output document transformed
 * @throws Exception
 *             The exception
 */
@Deprecated
public static String transform(Source source, Source stylesheet, Map<String, String> params,
        Properties outputProperties) throws Exception {
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(stylesheet);

        if (outputProperties != null) {
            transformer.setOutputProperties(outputProperties);
        }

        if (params != null) {
            transformer.clearParameters();

            for (Entry<String, String> entry : params.entrySet()) {
                String name = entry.getKey();
                String value = entry.getValue();
                transformer.setParameter(name, value);
            }
        }

        StringWriter sw = new StringWriter();
        Result result = new StreamResult(sw);
        transformer.transform(source, result);

        return sw.toString();
    } catch (TransformerConfigurationException e) {
        String strMessage = e.getMessage();

        if (e.getLocationAsString() != null) {
            strMessage += ("- location : " + e.getLocationAsString());
        }

        throw new Exception("Error transforming document XSLT : " + strMessage, e.getCause());
    } catch (TransformerFactoryConfigurationError e) {
        throw new Exception("Error transforming document XSLT : " + e.getMessage(), e);
    } catch (TransformerException e) {
        String strMessage = e.getMessage();

        if (e.getLocationAsString() != null) {
            strMessage += ("- location : " + e.getLocationAsString());
        }

        throw new Exception("Error transforming document XSLT : " + strMessage, e.getCause());
    } catch (Exception e) {
        throw new Exception("Error transforming document XSLT : " + e.getMessage(), e);
    }
}

From source file:fr.paris.lutece.plugins.calendar.service.XMLUtils.java

/**
 * This method performs XSL Transformation.
 * //from  w ww  .  j  a v a 2 s . c  om
 * @param strXml The input XML document
 * @param baSource The source input stream
 * @param params parameters to apply to the XSL Stylesheet
 * @param outputProperties properties to use for the xsl transform. Will
 *            overload the xsl output definition.
 * @return The output document transformed
 * @throws Exception The exception
 */
public static byte[] transformXMLToXSL(String strXml, InputStream baSource, Map<String, String> params,
        Properties outputProperties) throws Exception {
    Source stylesheet = new StreamSource(baSource);
    StringReader srInputXml = new StringReader(strXml);
    StreamSource source = new StreamSource(srInputXml);

    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(stylesheet);

        if (outputProperties != null) {
            transformer.setOutputProperties(outputProperties);
        }

        if (params != null) {
            transformer.clearParameters();

            Set<Entry<String, String>> entries = params.entrySet();

            for (Entry<String, String> entry : entries) {
                String name = entry.getKey();
                String value = entry.getValue();
                transformer.setParameter(name, value);
            }
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Result result = new StreamResult(out);
        transformer.transform(source, result);

        return out.toByteArray();
    } catch (TransformerConfigurationException e) {
        String strMessage = e.getMessage();

        if (e.getLocationAsString() != null) {
            strMessage += ("- location : " + e.getLocationAsString());
        }

        throw new Exception("Error transforming document XSLT : " + strMessage, e.getCause());
    } catch (TransformerFactoryConfigurationError e) {
        throw new Exception("Error transforming document XSLT : " + e.getMessage(), e);
    } catch (TransformerException e) {
        String strMessage = e.getMessage();

        if (e.getLocationAsString() != null) {
            strMessage += ("- location : " + e.getLocationAsString());
        }

        throw new Exception("Error transforming document XSLT : " + strMessage, e.getCause());
    } catch (Exception e) {
        throw new Exception("Error transforming document XSLT : " + e.getMessage(), e);
    }
}

From source file:org.lareferencia.backend.indexer.IntelligoIndexer.java

private Transformer buildTransformer() throws IndexerException {

    Transformer trf;//from  w w w .  ja v  a  2s  .  c  om

    try {

        StreamSource stylesource = new StreamSource(stylesheet);
        trf = xformFactory.newTransformer(stylesource);

        trf = MedatadaDOMHelper.buildXSLTTransformer(stylesheet);
        trf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trf.setOutputProperty(OutputKeys.INDENT, "yes");
        trf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    } catch (TransformerConfigurationException e) {
        throw new IndexerException(e.getMessage(), e.getCause());
    }

    return trf;

}

From source file:ddf.catalog.services.xsltlistener.XsltMetacardTransformer.java

@Override
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments)
        throws CatalogTransformerException {
    LOGGER.debug("Entering metacard xslt transform.");

    Transformer transformer;//  w w  w .jav a  2 s.  co  m
    Map<String, Object> mergedMap = new HashMap<String, Object>(localMap);

    if (arguments != null) {
        mergedMap.putAll(arguments);
    }

    // adding metacard data not in document
    mergedMap.put("id", getValueOrEmptyString(metacard.getId()));
    mergedMap.put("siteName", getValueOrEmptyString(metacard.getSourceId()));
    mergedMap.put("title", getValueOrEmptyString(metacard.getTitle()));
    mergedMap.put("type", getValueOrEmptyString(metacard.getMetacardType()));
    mergedMap.put("date", getValueOrEmptyString(metacard.getCreatedDate()));
    mergedMap.put("product", getValueOrEmptyString(metacard.getResourceURI()));
    mergedMap.put("thumbnail", getValueOrEmptyString(metacard.getThumbnail()));
    mergedMap.put("geometry", getValueOrEmptyString(metacard.getLocation()));

    ServiceReference[] refs = null;
    try {
        LOGGER.debug("Searching for other Metacard Transformers.");
        // TODO INJECT THESE!!!
        refs = context.getServiceReferences(MetacardTransformer.class.getName(), null);
    } catch (InvalidSyntaxException e) {
        // can't happen because filter is null
    }

    if (refs != null) {
        List<String> serviceList = new ArrayList<String>();
        LOGGER.debug("Found other Metacard transformers, adding them to a service reference list.");
        for (ServiceReference ref : refs) {
            if (ref != null) {
                String title = null;
                String shortName = (String) ref.getProperty(Constants.SERVICE_SHORTNAME);

                if ((title = (String) ref.getProperty(Constants.SERVICE_TITLE)) == null) {
                    title = "View as " + shortName.toUpperCase();
                }

                String url = "/services/catalog/" + metacard.getId() + "?transform=" + shortName;

                // define the services
                serviceList.add(title);
                serviceList.add(url);
            }
        }
        mergedMap.put("services", serviceList);
    } else {
        LOGGER.debug("No other Metacard transformers were found.");
    }

    // TODO: maybe add updated, type, and uuid here?
    // map.put("updated", fmt.print(result.getPostedDate().getTime()));
    // map.put("type", card.getSingleType().getValue());

    BinaryContent resultContent;
    StreamResult resultOutput = null;
    Source source = new StreamSource(
            new ByteArrayInputStream(metacard.getMetadata().getBytes(StandardCharsets.UTF_8)));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    resultOutput = new StreamResult(baos);

    try {
        transformer = templates.newTransformer();
    } catch (TransformerConfigurationException tce) {
        throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(),
                tce.getCause());
    }

    if (!mergedMap.isEmpty()) {
        for (Map.Entry<String, Object> entry : mergedMap.entrySet()) {
            LOGGER.debug("Adding parameter to transform {}:{}", entry.getKey(), entry.getValue());
            transformer.setParameter(entry.getKey(), entry.getValue());
        }
    }

    try {
        transformer.transform(source, resultOutput);
        byte[] bytes = baos.toByteArray();
        IOUtils.closeQuietly(baos);
        LOGGER.debug("Transform complete.");
        resultContent = new XsltTransformedContent(bytes, mimeType);
    } catch (TransformerException te) {
        throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getMessage(),
                te.getCause());
    } finally {
        // TODO: if we ever start to reuse transformers, we should add this
        // code back in
        // transformer.reset();
    }

    return resultContent;
}

From source file:ddf.catalog.services.xsltlistener.XsltResponseQueueTransformer.java

@Override
public ddf.catalog.data.BinaryContent transform(SourceResponse upstreamResponse,
        Map<String, Serializable> arguments) throws CatalogTransformerException {

    LOGGER.debug("Transforming ResponseQueue with XSLT tranformer");

    long grandTotal = -1;

    try {//from   w  ww.  j  a  v a  2s .c  o  m
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document doc = builder.newDocument();

        Node resultsElement = doc.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "results", null));

        // TODO use streaming XSLT, not DOM
        List<Result> results = upstreamResponse.getResults();
        grandTotal = upstreamResponse.getHits();

        for (Result result : results) {
            Metacard metacard = result.getMetacard();
            String thisMetacard = metacard.getMetadata();
            if (metacard != null && thisMetacard != null) {
                Element metacardElement = createElement(doc, XML_RESULTS_NAMESPACE, "metacard", null);
                if (metacard.getId() != null) {
                    metacardElement
                            .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "id", metacard.getId()));
                }
                if (metacard.getMetacardType().toString() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "type",
                            metacard.getMetacardType().getName()));
                }
                if (metacard.getTitle() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "title", metacard.getTitle()));
                }
                if (result.getRelevanceScore() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "score",
                            result.getRelevanceScore().toString()));
                }
                if (result.getDistanceInMeters() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "distance",
                            result.getDistanceInMeters().toString()));
                }
                if (metacard.getSourceId() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "site", metacard.getSourceId()));
                }
                if (metacard.getContentTypeName() != null) {
                    String contentType = metacard.getContentTypeName();
                    Element typeElement = createElement(doc, XML_RESULTS_NAMESPACE, "content-type",
                            contentType);
                    // TODO revisit what to put in the qualifier
                    typeElement.setAttribute("qualifier", "content-type");
                    metacardElement.appendChild(typeElement);
                }
                if (metacard.getResourceURI() != null) {
                    try {
                        metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "product",
                                metacard.getResourceURI().toString()));
                    } catch (DOMException e) {
                        LOGGER.warn(" Unable to create resource uri element", e);
                    }
                }
                if (metacard.getThumbnail() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "thumbnail",
                            Base64.encodeBase64String(metacard.getThumbnail())));
                    try {
                        String mimeType = URLConnection
                                .guessContentTypeFromStream(new ByteArrayInputStream(metacard.getThumbnail()));
                        metacardElement
                                .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", mimeType));
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        metacardElement.appendChild(
                                createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", "image/png"));
                    }
                }
                DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
                if (metacard.getCreatedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "created",
                            fmt.print(metacard.getCreatedDate().getTime())));
                }
                // looking at the date last modified
                if (metacard.getModifiedDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "updated",
                            fmt.print(metacard.getModifiedDate().getTime())));
                }
                if (metacard.getEffectiveDate() != null) {
                    metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "effective",
                            fmt.print(metacard.getEffectiveDate().getTime())));
                }
                if (metacard.getLocation() != null) {
                    metacardElement.appendChild(
                            createElement(doc, XML_RESULTS_NAMESPACE, "location", metacard.getLocation()));
                }
                Element documentElement = doc.createElementNS(XML_RESULTS_NAMESPACE, "document");
                metacardElement.appendChild(documentElement);
                resultsElement.appendChild(metacardElement);

                Node importedNode = doc.importNode(new XPathHelper(thisMetacard).getDocument().getFirstChild(),
                        true);
                documentElement.appendChild(importedNode);
            } else {
                LOGGER.debug("Null content/document returned to XSLT ResponseQueueTransformer");
                continue;
            }
        }

        if (LOGGER.isDebugEnabled()) {
            DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
            LSSerializer lsSerializer = domImplementation.createLSSerializer();
            LOGGER.debug("Generated XML input for transform: " + lsSerializer.writeToString(doc));
        }

        LOGGER.debug("Starting responsequeue xslt transform.");

        Transformer transformer;

        Map<String, Object> mergedMap = new HashMap<String, Object>();
        mergedMap.put(GRAND_TOTAL, grandTotal);
        if (arguments != null) {
            mergedMap.putAll(arguments);
        }

        BinaryContent resultContent;
        StreamResult resultOutput = null;
        Source source = new DOMSource(doc);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        resultOutput = new StreamResult(baos);

        try {
            transformer = templates.newTransformer();
        } catch (TransformerConfigurationException tce) {
            throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(),
                    tce.getCause());
        }

        if (mergedMap != null && !mergedMap.isEmpty()) {
            for (Map.Entry<String, Object> entry : mergedMap.entrySet()) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                            "Adding parameter to transform {" + entry.getKey() + ":" + entry.getValue() + "}");
                }
                transformer.setParameter(entry.getKey(), entry.getValue());
            }
        }

        try {
            transformer.transform(source, resultOutput);
            byte[] bytes = baos.toByteArray();
            LOGGER.debug("Transform complete.");
            resultContent = new XsltTransformedContent(bytes, mimeType);
        } catch (TransformerException te) {
            LOGGER.error("Could not perform Xslt transform: " + te.getException(), te.getCause());
            throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getException(),
                    te.getCause());
        } finally {
            // transformer.reset();
            // don't need to do that unless we are putting it back into a
            // pool -- which we should do, but that can wait until later.
        }

        return resultContent;
    } catch (ParserConfigurationException e) {
        LOGGER.warn("Error creating new document: " + e.getMessage(), e.getCause());
        throw new CatalogTransformerException("Error merging entries to xml feed.", e);
    }
}

From source file:org.displaytag.export.FopExportView.java

/**
 * Don't forget to enable debug if you want to see the raw FO.
 *
 * @param out output writer/*from  w w  w .  j  av  a 2s .c  o m*/
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws JspException the jsp exception
 */
@Override
public void doExport(OutputStream out) throws IOException, JspException {
    String xmlResults = getXml();

    FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
    Source xslt = new StreamSource(getStyleSheet());
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = factory.newTransformer(xslt);
    } catch (TransformerConfigurationException e) {
        throw new JspException("Cannot configure pdf export " + e.getMessage(), e); //$NON-NLS-1$
    }

    boolean outputForDebug = log.isDebugEnabled();
    if (outputForDebug) {
        logXsl(xmlResults, transformer, null);
    }

    Fop fop;
    try {
        fop = fopFactory.newFop(org.apache.xmlgraphics.util.MimeConstants.MIME_PDF, out);
    } catch (FOPException e) {
        throw new JspException("Cannot configure pdf export " + e.getMessage(), e); //$NON-NLS-1$
    }

    StreamSource src = new StreamSource(new StringReader(xmlResults));
    Result res;
    try {
        res = new SAXResult(fop.getDefaultHandler());
    } catch (FOPException e) {
        throw new JspException("error setting up transform ", e); //$NON-NLS-1$
    }
    try {
        transformer.transform(src, res);
    } catch (TransformerException e) {
        if (e.getCause() instanceof ValidationException) {
            // recreate the errant fo
            ValidationException ve = (ValidationException) e.getCause();
            logXsl(xmlResults, transformer, ve);
        } else {
            throw new JspException("error creating pdf output", e); //$NON-NLS-1$
        }

    }
}

From source file:org.lareferencia.backend.indexer.IndexerImpl.java

private Transformer buildTransformer() throws IndexerException {

    Transformer trf;/*from w ww .j  a  v  a  2 s .  c om*/

    try {

        StreamSource stylesource = new StreamSource(stylesheet);
        trf = xformFactory.newTransformer(stylesource);

        trf = MedatadaDOMHelper.buildXSLTTransformer(stylesheet);
        trf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trf.setOutputProperty(OutputKeys.INDENT, "no");
        trf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    } catch (TransformerConfigurationException e) {
        throw new IndexerException(e.getMessage(), e.getCause());
    }

    return trf;

}

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

@Override
public void transform(MCRContent source, OutputStream out, MCRParameterCollector parameter) throws IOException {
    MCRErrorListener el = null;// ww w. j  av  a  2  s.  co m
    try {
        LinkedList<TransformerHandler> transformHandlerList = getTransformHandlerList(parameter);
        XMLReader reader = getXMLReader(transformHandlerList);
        TransformerHandler lastTransformerHandler = transformHandlerList.getLast();
        el = (MCRErrorListener) lastTransformerHandler.getTransformer().getErrorListener();
        StreamResult result = new StreamResult(out);
        lastTransformerHandler.setResult(result);
        reader.parse(source.getInputSource());
    } catch (TransformerConfigurationException e) {
        throw new IOException(e);
    } catch (IllegalArgumentException e) {
        throw new IOException(e);
    } catch (SAXException e) {
        throw new IOException(e);
    } catch (RuntimeException e) {
        if (el != null && e.getCause() == null && el.getExceptionThrown() != null) {
            //typically if a RuntimeException has no cause, we can get the "real cause" from MCRErrorListener, yeah!!!
            throw new IOException(el.getExceptionThrown());
        }
        throw e;
    }
}