Example usage for javax.xml.transform TransformerException getCause

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

Introduction

In this page you can find the example usage for javax.xml.transform TransformerException 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:com.databasepreservation.visualization.api.utils.ApiUtils.java

public static Response errorResponse(TransformerException e) {
    String message;/*from   www  .j  a  v a2  s  . com*/

    if (e.getCause() != null) {
        message = e.getCause().getMessage();
    } else {
        message = e.getMessage();
    }

    return Response.serverError().entity(new ApiResponseMessage(ApiResponseMessage.ERROR, message)).build();
}

From source file:net.padaf.xmpbox.SaveMetadataHelper.java

/**
 * Serialize a schema into an Output stream
 * // ww w .  j  a v a  2s  .  co m
 * @param schema
 *            Schema concerned by the serialization processing
 * @param os
 *            Stream to save serialized schema
 * @throws TransformException
 *             When couldn't parse data to XML/RDF
 */
public static void serialize(XMPSchema schema, OutputStream os) throws TransformException {
    try {
        Document doc = XMLUtil.newDocument();
        Element rdf = doc.createElementNS("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:RDF");
        Node schemContent = schema.getElement().cloneNode(true);
        doc.adoptNode(schemContent);
        rdf.appendChild(schemContent);
        XMLUtil.save(rdf, os, "UTF-8");
    } catch (TransformerException e) {
        throw new TransformException("Failed to parse defined XMP");
    } catch (IOException e) {
        throw new TransformException("Failed to create Document to contain Schema representation ",
                e.getCause());
    }

}

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  . ja va 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:com.summer.logger.LoggerPrinter.java

  /**
 * Formats the json content and print it
 *
 * @param xml the xml content/*w  w w  . ja  v  a2  s.  co  m*/
 */
@Override public void xml(String xml) {
  if (TextUtils.isEmpty(xml)) {
    d("Empty/Null xml content");
    return;
  }
  try {
    Source xmlInput = new StreamSource(new StringReader(xml));
    StreamResult xmlOutput = new StreamResult(new StringWriter());
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    transformer.transform(xmlInput, xmlOutput);
    d(xmlOutput.getWriter().toString().replaceFirst(">", ">\n"));
  } catch (TransformerException e) {
    e(e.getCause().getMessage() + "\n" + xml);
  }
}

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  va2  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:org.apache.cocoon.components.xslt.XSLTProcessorErrorListener.java

public void error(TransformerException ex) throws TransformerException {

    // If we had a warning previoulsy, and the current exception has no cause, then use the warning.
    // This is how Xalan behaves on <xsl:message terminate="yes">: it first issues a warning with all
    // the useful information, then a useless "stylesheed directed termination" error.
    if (warningEx != null && ex.getCause() == null) {
        ex = warningEx;/*from   w  ww .  j a  v a 2  s.co  m*/
    }
    warningEx = null;

    // Keep the exception for later use.
    exception = ex;
    // and rethrow it
    throw ex;
}

From source file:org.apache.cocoon.components.xslt.XSLTProcessorErrorListener.java

public void fatalError(TransformerException ex) throws TransformerException {
    if (warningEx != null && ex.getCause() == null) {
        ex = warningEx;/*from   w w w  .j  ava  2 s  .  c om*/
    }
    warningEx = null;

    exception = ex;
    throw ex;
}

From source file:org.apache.fop.render.intermediate.IFParser.java

/**
 * Parses an intermediate file and paints it.
 * @param src the Source instance pointing to the intermediate file
 * @param documentHandler the intermediate format document handler used to process the IF events
 * @param userAgent the user agent//from   w ww .j a va2s.  c o m
 * @throws TransformerException if an error occurs while parsing the area tree XML
 * @throws IFException if an IF-related error occurs inside the target document handler
 */
public void parse(Source src, IFDocumentHandler documentHandler, FOUserAgent userAgent)
        throws TransformerException, IFException {
    try {
        Transformer transformer = tFactory.newTransformer();
        transformer.setErrorListener(new DefaultErrorListener(log));

        SAXResult res = new SAXResult(getContentHandler(documentHandler, userAgent));

        transformer.transform(src, res);
    } catch (TransformerException te) {
        //Unpack original IFException if applicable
        if (te.getCause() instanceof SAXException) {
            SAXException se = (SAXException) te.getCause();
            if (se.getCause() instanceof IFException) {
                throw (IFException) se.getCause();
            }
        } else if (te.getCause() instanceof IFException) {
            throw (IFException) te.getCause();
        }
        throw te;
    }
}

From source file:org.apache.fop.render.svg.SVGDocumentHandler.java

/** {@inheritDoc} */
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException {
    if (this.multiFileUtil != null) {
        prepareHandlerWithOutputStream(index);
    } else {/*w w  w .j a  v  a2s .  com*/
        if (this.simpleResult == null) {
            //Only one page is supported with this approach at the moment
            throw new IFException("Only one page is supported for output with the given Result instance!",
                    null);
        }
        super.setResult(this.simpleResult);
        this.simpleResult = null;
    }

    try {
        handler.startDocument();
        handler.startPrefixMapping("", NAMESPACE);
        handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE);
        AttributesImpl atts = new AttributesImpl();
        XMLUtil.addAttribute(atts, "version", "1.1"); //SVG 1.1
        /*
        XMLUtil.addAttribute(atts, "index", Integer.toString(index));
        XMLUtil.addAttribute(atts, "name", name);
        */
        XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(size.width) + "pt");
        XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(size.height) + "pt");
        XMLUtil.addAttribute(atts, "viewBox",
                "0 0 " + SVGUtil.formatMptToPt(size.width) + " " + SVGUtil.formatMptToPt(size.height));
        handler.startElement("svg", atts);

        try {
            Transformer transformer = tFactory.newTransformer();
            Source src = new DOMSource(this.reusedParts.getDocumentElement());
            Result res = new SAXResult(new DelegatingFragmentContentHandler(this.handler));
            transformer.transform(src, res);
        } catch (TransformerConfigurationException tce) {
            throw new IFException("Error setting up a Transformer", tce);
        } catch (TransformerException te) {
            if (te.getCause() instanceof SAXException) {
                throw (SAXException) te.getCause();
            } else {
                throw new IFException("Error while serializing reused parts", te);
            }
        }
    } catch (SAXException e) {
        throw new IFException("SAX error in startPage()", e);
    }
}

From source file:org.apache.maven.doxia.module.fo.FoAggregateSinkTest.java

/**
 * Test the FO PDF generation with some special characters in company name.
 */// ww w  .  jav a 2s  .  co m
public void testSpecialCharacters() throws IOException, TransformerException {
    DocumentModel model = new DocumentModel();
    DocumentCover cover = new DocumentCover();

    cover.setCompanyName("Partner & Friends");
    cover.setCoverTitle("A Masterpice in Encoding Theory <>&");
    cover.setCoverSubTitle("Some nice Encodings & <METHODS>");
    cover.setProjectName("A Masterpice in Encoding Theory <>&");
    cover.setAuthor("Partner & Friends");
    model.setCover(cover);

    File foFile = File.createTempFile("fo-test", ".fo");
    File pdfFile = File.createTempFile("fo-test", ".pdf");
    try {

        sink = new FoAggregateSink(WriterFactory.newXmlWriter(foFile));

        sink.setDocumentModel(model);
        sink.setDocumentTitle("A Masterpice in Encoding Theory <>&");
        sink.beginDocument();
        sink.coverPage();
        // sink.toc();
        sink.endDocument();
    } finally {
        sink.close();
    }

    try {
        FoUtils.convertFO2PDF(foFile, pdfFile, null, model);
    } catch (TransformerException e) {
        if ((e.getCause() != null) && (e.getCause() instanceof SAXParseException)) {
            SAXParseException sax = (SAXParseException) e.getCause();

            StringBuffer sb = new StringBuffer();
            sb.append("Error creating PDF from ").append(foFile.getAbsolutePath()).append(":")
                    .append(sax.getLineNumber()).append(":").append(sax.getColumnNumber()).append("\n");
            sb.append(e.getMessage());

            throw new RuntimeException(sb.toString());
        }

        throw new TransformerException("Error creating PDF from " + foFile + ": " + e.getMessage());
    }
}