use of javax.xml.transform.TransformerConfigurationException in project CFLint by cflint.
the class HTMLOutput method output.
public void output(final BugList bugList, final Writer writer, final boolean showStats) throws IOException, TransformerException {
// 1. Instantiate a TransformerFactory.
final javax.xml.transform.TransformerFactory tFactory = javax.xml.transform.TransformerFactory.newInstance();
// 2. Use the TransformerFactory to process the stylesheet Source and
// generate a Transformer.
javax.xml.transform.Transformer transformer;
// System.out.println("Using html style:" + htmlStyle);
try {
final InputStream is = getClass().getResourceAsStream("/findbugs/" + htmlStyle);
transformer = tFactory.newTransformer(new javax.xml.transform.stream.StreamSource(is));
} catch (final TransformerConfigurationException e) {
final InputStream is = getClass().getResourceAsStream("/" + htmlStyle);
transformer = tFactory.newTransformer(new javax.xml.transform.stream.StreamSource(is));
}
final StringWriter sw = new StringWriter();
new XMLOutput().outputFindBugs(bugList, sw, showStats);
// 3. Use the Transformer to transform an XML Source and send the
// output to a Result object.
transformer.transform(new StreamSource(new StringReader(sw.toString())), new javax.xml.transform.stream.StreamResult(writer));
writer.close();
}
use of javax.xml.transform.TransformerConfigurationException in project ddf by codice.
the class XsltMetacardTransformer method transform.
@Override
public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException {
LOGGER.debug("Entering metacard xslt transform.");
Transformer transformer;
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;
XMLReader xmlReader = null;
try {
XMLReader xmlParser = XMLReaderFactory.createXMLReader();
xmlParser.setFeature("http://xml.org/sax/features/external-general-entities", false);
xmlParser.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
xmlParser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
xmlReader = new XMLFilterImpl(xmlParser);
} catch (SAXException e) {
LOGGER.debug(e.getMessage(), e);
}
Source source = new SAXSource(xmlReader, new InputSource(new StringReader(metacard.getMetadata())));
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;
}
use of javax.xml.transform.TransformerConfigurationException in project ddf by codice.
the class XsltResponseQueueTransformer method transform.
@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 {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
} catch (ParserConfigurationException e) {
LOGGER.debug("Unable to configure features on document builder.", e);
}
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();
if (metacard != null) {
String metadata = metacard.getMetadata();
if (metadata != 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.debug(" Unable to create resource uri element", e);
}
}
if (metacard.getThumbnail() != null) {
metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "thumbnail", Base64.getEncoder().encodeToString(metacard.getThumbnail())));
try {
String mimeType = URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(metacard.getThumbnail()));
metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", mimeType));
} catch (IOException e) {
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(metadata).getDocument().getFirstChild(), true);
documentElement.appendChild(importedNode);
} else {
LOGGER.debug("Null content/document returned to XSLT ResponseQueueTransformer");
}
}
}
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);
}
for (Map.Entry<String, Object> entry : mergedMap.entrySet()) {
LOGGER.trace("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.debug("Could not perform Xslt transform: ", te);
throw new CatalogTransformerException("Could not perform Xslt transform: ", te);
}
return resultContent;
} catch (ParserConfigurationException e) {
LOGGER.debug("Error creating new document: ", e);
throw new CatalogTransformerException("Error merging entries to xml feed.", e);
}
}
use of javax.xml.transform.TransformerConfigurationException in project ddf by codice.
the class AbstractXsltTransformer method init.
/**
* Sets the templates and mimeType used to perform a transform. This method can also be used in
* a non-OSGi environment to setup the transformer. <b>NOTE:</b> When using in a non-OSGi
* environment, some transformers may not work.
*
* @param mimeHeaderName
* String value of the mimeType to be returned.
* @param xslFilePath
* Full, absolute path of the xsl file.
*/
public void init(String mimeString, InputStream xslStream) {
TransformerFactory tf = TransformerFactory.newInstance(net.sf.saxon.TransformerFactoryImpl.class.getName(), getClass().getClassLoader());
Source xsltSource;
xsltSource = new StreamSource(xslStream);
try {
templates = tf.newTemplates(xsltSource);
} catch (TransformerConfigurationException tce) {
throw new RuntimeException("Could not create new templates for XsltTransformer ( " + xslStream + ") : " + tce.getException(), tce);
}
if (mimeString == null) {
this.mimeType = DEFAULT_MIME_TYPE;
mimeString = "";
}
try {
this.mimeType = new MimeType(mimeString);
} catch (MimeTypeParseException e) {
this.mimeType = DEFAULT_MIME_TYPE;
}
}
use of javax.xml.transform.TransformerConfigurationException in project apps-android-commons by commons-app.
the class Utils method getStringFromDOM.
public static String getStringFromDOM(Node dom) {
Transformer transformer = null;
try {
transformer = TransformerFactory.newInstance().newTransformer();
} catch (TransformerConfigurationException | TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StringWriter outputStream = new StringWriter();
DOMSource domSource = new DOMSource(dom);
StreamResult strResult = new StreamResult(outputStream);
try {
transformer.transform(domSource, strResult);
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return outputStream.toString();
}
Aggregations