use of org.w3c.dom.ls.DOMImplementationLS in project syncope by apache.
the class CamelRouteLoader method loadRoutes.
private void loadRoutes(final String domain, final DataSource dataSource, final Resource resource, final AnyTypeKind anyTypeKind) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
boolean shouldLoadRoutes = jdbcTemplate.queryForList(String.format("SELECT * FROM %s WHERE ANYTYPEKIND = ?", CamelRoute.class.getSimpleName()), new Object[] { anyTypeKind.name() }).isEmpty();
if (shouldLoadRoutes) {
try {
TransformerFactory tf = null;
DOMImplementationLS domImpl = null;
NodeList routeNodes;
if (IS_JBOSS) {
tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
tf.setURIResolver((href, base) -> null);
Document doc = StaxUtils.read(resource.getInputStream());
routeNodes = doc.getDocumentElement().getElementsByTagName("route");
} else {
DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS");
LSInput lsinput = domImpl.createLSInput();
lsinput.setByteStream(resource.getInputStream());
LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
routeNodes = parser.parse(lsinput).getDocumentElement().getElementsByTagName("route");
}
for (int s = 0; s < routeNodes.getLength(); s++) {
Node routeElement = routeNodes.item(s);
String routeContent = IS_JBOSS ? nodeToString(routeNodes.item(s), tf) : nodeToString(routeNodes.item(s), domImpl);
String routeId = ((Element) routeElement).getAttribute("id");
jdbcTemplate.update(String.format("INSERT INTO %s(ID, ANYTYPEKIND, CONTENT) VALUES (?, ?, ?)", CamelRoute.class.getSimpleName()), new Object[] { routeId, anyTypeKind.name(), routeContent });
LOG.info("[{}] Route successfully loaded: {}", domain, routeId);
}
} catch (Exception e) {
LOG.error("[{}] Route load failed", domain, e);
}
}
}
use of org.w3c.dom.ls.DOMImplementationLS in project syncope by apache.
the class XMLUtils method createXMLFile.
public static void createXMLFile(final InputStream sis, final String filePath) throws Exception {
DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
DOMImplementationLS domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS");
LSInput lsinput = domImpl.createLSInput();
lsinput.setByteStream(sis);
LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
tf.newTransformer().transform(new DOMSource(parser.parse(lsinput)), new StreamResult(new File(filePath)));
}
use of org.w3c.dom.ls.DOMImplementationLS in project openj9 by eclipse.
the class PrefixJUnitResults method process.
private void process(File xmlFile) throws IOException, SAXException {
File outputFile = getOutputFile(xmlFile);
if (verbose) {
log("Mapping " + xmlFile.getAbsolutePath() + " to " + outputFile.getAbsolutePath());
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
Document doc = builder.parse(new InputSource(new FileReader(xmlFile)));
/* Find the testsuite nodes and prefix the name element */
NodeList testSuiteNodes = doc.getElementsByTagName("testsuite");
if (testSuiteNodes.getLength() == 0) {
log("Couldn't find testsuite node in " + xmlFile.getAbsolutePath());
}
for (int i = 0; i < testSuiteNodes.getLength(); i++) {
Node thisTestSuite = testSuiteNodes.item(i);
NamedNodeMap attributes = thisTestSuite.getAttributes();
Attr nameNode = (Attr) attributes.getNamedItem("name");
if (null == nameNode) {
log("Couldn't find name attribute on testsuite element in " + xmlFile.getAbsolutePath());
continue;
}
String oldValue = nameNode.getValue();
nameNode.setValue(prefix + "." + oldValue);
}
/* Do the same for the testcase nodes */
NodeList testCaseNodes = doc.getElementsByTagName("testcase");
for (int i = 0; i < testCaseNodes.getLength(); i++) {
Node thisTestCase = testCaseNodes.item(i);
NamedNodeMap attributes = thisTestCase.getAttributes();
Attr classNameNode = (Attr) attributes.getNamedItem("classname");
if (null == classNameNode) {
log("Couldn't find classname attribute on testcase element in " + xmlFile.getAbsolutePath());
continue;
}
String oldValue = classNameNode.getValue();
classNameNode.setValue(prefix + "." + oldValue);
}
/* Write out to new location */
DOMImplementationLS ls = (DOMImplementationLS) builder.getDOMImplementation();
LSSerializer serializer = ls.createLSSerializer();
LSOutput xmlSink = ls.createLSOutput();
xmlSink.setCharacterStream(new FileWriter(outputFile));
serializer.write(doc, xmlSink);
}
use of org.w3c.dom.ls.DOMImplementationLS in project ddf by codice.
the class XsltResponseQueueTransformer method transform.
@Override
public BinaryContent transform(SourceResponse upstreamResponse, Map<String, Serializable> arguments) throws CatalogTransformerException {
LOGGER.debug("Transforming ResponseQueue with XSLT tranformer");
long grandTotal = -1;
try {
DocumentBuilder builder = XML_UTILS.getSecureDocumentBuilder(true);
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(TRANSFORMATION_FAILURE_MSG, 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(TRANSFORMATION_FAILURE_MSG, te);
throw new CatalogTransformerException(TRANSFORMATION_FAILURE_MSG, 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.DOMImplementationLS in project ddf by codice.
the class SAMLAuthenticationToken method getCredentialsAsString.
@Override
public String getCredentialsAsString() {
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
false);
// xml-declaration
creds = serializer.writeToString(element);
}
LOGGER.trace("XML representation of SAML token: {}", creds);
}
return creds;
}
Aggregations