use of org.w3c.dom.ls.LSSerializer in project tomee by apache.
the class XmlFormatter method format.
public static String format(final String in) {
try {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
final DocumentBuilder db = dbf.newDocumentBuilder();
final InputSource is = new InputSource(new StringReader(in));
final Document document = db.parse(is);
final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
final DOMImplementationLS impl = DOMImplementationLS.class.cast(registry.getDOMImplementation("XML 3.0 LS 3.0"));
if (impl == null) {
return in;
}
final LSSerializer serializer = impl.createLSSerializer();
if (serializer.getDomConfig().canSetParameter("format-pretty-print", Boolean.TRUE)) {
serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
final LSOutput lsOutput = impl.createLSOutput();
lsOutput.setEncoding("UTF-8");
final StringWriter stringWriter = new StringWriter();
lsOutput.setCharacterStream(stringWriter);
serializer.write(document, lsOutput);
return stringWriter.toString().replace("\"UTF-8\"?><", "\"UTF-8\"?>\n<");
}
return in;
} catch (final Throwable t) {
// just to be more sexy so ignore it and use ugly xml
return in;
}
}
use of org.w3c.dom.ls.LSSerializer in project beast-mcmc by beast-dev.
the class ConfigPersister method load.
public void load(File f) throws ConfigPersisterException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation();
LSSerializer lsSerializer = domImplementation.createLSSerializer();
String configString = lsSerializer.writeToString(doc);
_config = (Config) _xstream.fromXML(convertToCurrent(configString));
setConfigPath(f);
} catch (Exception e) {
throw new ConfigPersisterException(e);
}
}
use of org.w3c.dom.ls.LSSerializer 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 org.w3c.dom.ls.LSSerializer in project ddf by codice.
the class XPathHelper method print.
/**
* Prints a given node as a String
*
* @param n
* - the node to print as a String
* @param encoding
* - the character encoding to use for the returned String
* @return the Node as a String, null if an exception is thrown or null is passed in.
*/
public static String print(Node n, String encoding) {
if (n == null) {
return null;
}
try {
Document document = null;
if (n instanceof Document) {
document = (Document) n;
} else {
document = n.getOwnerDocument();
}
StringWriter stringOut = new StringWriter();
DOMImplementationLS domImpl = (DOMImplementationLS) document.getImplementation();
LSSerializer serializer = domImpl.createLSSerializer();
LSOutput lsOut = domImpl.createLSOutput();
lsOut.setEncoding(encoding);
lsOut.setCharacterStream(stringOut);
serializer.write(n, lsOut);
return stringOut.toString();
} catch (DOMException | LSException e) {
LOGGER.debug(e.getMessage(), e);
}
return null;
}
use of org.w3c.dom.ls.LSSerializer in project ddf by codice.
the class SAMLAuthenticationToken method getCredentialsAsXMLString.
@Override
public String getCredentialsAsXMLString() {
String creds = "";
Element element = getSAMLTokenAsElement();
if (element != null) {
DOMImplementationLS lsImpl = (DOMImplementationLS) element.getOwnerDocument().getImplementation().getFeature("LS", "3.0");
if (null != lsImpl) {
LSSerializer serializer = lsImpl.createLSSerializer();
serializer.getDomConfig().setParameter("xml-declaration", //by default its true, so set it to false to get String without xml-declaration
false);
creds = serializer.writeToString(element);
}
LOGGER.trace("XML representation of SAML token: {}", creds);
}
return creds;
}
Aggregations