Example usage for javax.xml.transform TransformerConfigurationException getException

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

Introduction

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

Prototype

public Throwable getException() 

Source Link

Document

This method retrieves an exception that this exception wraps.

Usage

From source file:Main.java

public static void encodeAsXml(Node dom, OutputStream os) throws Throwable {
    try {/*  w  ww. j a v  a2s  . co  m*/
        DOMSource source = new DOMSource(dom);
        StreamResult result = new StreamResult(os);
        Transformer transformer;
        transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(source, result);
    } catch (TransformerConfigurationException tce) {
        Throwable x = tce;
        if (tce.getException() != null)
            x = tce.getException();
        throw x;
    } catch (TransformerException te) {
        Throwable x = te;
        if (te.getException() != null)
            x = te.getException();
        throw x;
    }
}

From source file:Main.java

public static void writeXMLDocToFile(Document outputDoc, String outFileName) {
    try {//from   w  w w  .j a  v a 2s . c om
        //FileWriter writer = new FileWriter( outFileName );
        final String encoding = "UTF-8";
        OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outFileName), encoding);
        // Use a Transformer for output
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();

        DOMSource source = new DOMSource(outputDoc);
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("Could not create output XML file: " + outFileName);
    } catch (TransformerConfigurationException tce) {
        // Error generated by the parser
        System.out.println("* Transformer Factory error");
        System.out.println("  " + tce.getMessage());

        // Use the contained exception, if any
        Throwable x = tce;
        if (tce.getException() != null)
            x = tce.getException();
        x.printStackTrace();
    } catch (TransformerException te) {
        // Error generated by the parser
        System.out.println("* Transformation error");
        System.out.println("  " + te.getMessage());

        // Use the contained exception, if any
        Throwable x = te;
        if (te.getException() != null)
            x = te.getException();
        x.printStackTrace();
    }
}

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;/*ww  w  .j  a va2s. c  o 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  w  w .  j a  v  a 2  s .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:edu.lternet.pasta.datapackagemanager.DataPackageManagerResource.java

/**
 * Applies the quality report stylesheet to transform the quality report
 * representation from XML to HTML for presentation purposes.
 * /* w  ww  . j av  a  2 s.  co m*/
 * @param xmlString
 *            the quality report XML string
 * @param xslPath
 *            path to the quality report stylesheet
 * 
 * @return htmlString the result of the transformation from XML to HTML
 * @throws IllegalStateException
 *             if an error occurs during the transformation process
 */
private String qualityReportXMLtoHTML(String xmlString, final String xslPath) throws IllegalStateException {
    String htmlString = "";
    Result result;
    StringWriter stringWriter = new StringWriter();
    javax.xml.transform.Transformer transformer;
    javax.xml.transform.TransformerFactory transformerFactory;
    Source xmlSource;
    File xsltFile = new File(xslPath);
    Source xsltSource;

    StringReader stringReader = new StringReader(xmlString);
    xmlSource = new javax.xml.transform.stream.StreamSource(stringReader);
    xsltSource = new javax.xml.transform.stream.StreamSource(xsltFile);
    result = new javax.xml.transform.stream.StreamResult(stringWriter);
    logger.debug("javax.xml.transform.TransformerFactory :"
            + System.getProperty("javax.xml.transform.TransformerFactory"));
    transformerFactory = javax.xml.transform.TransformerFactory.newInstance();

    try {
        transformer = transformerFactory.newTransformer(xsltSource);
        transformer.transform(xmlSource, result);
        htmlString = stringWriter.toString();
    } catch (TransformerConfigurationException e) {
        Throwable x = e;
        if (e.getException() != null) {
            x = e.getException();
        }
        x.printStackTrace();
        throw new IllegalStateException(e);
    } catch (TransformerException e) {
        Throwable x = e;
        if (e.getException() != null) {
            x = e.getException();
        }
        x.printStackTrace();
        throw new IllegalStateException(e);
    }

    return htmlString;
}