List of usage examples for org.w3c.dom Document normalizeDocument
public void normalizeDocument();
From source file:edu.cudenver.bios.matrixsvc.representation.CholeskyDecompositionXmlRepresentation.java
/** * Create an XML representation for a Cholesky Decomposition XML response * entity body. /* w w w . ja v a 2 s. c om*/ * * @param cdImpl is a @see CholeskyDecompositionImpl. * @throws IOException */ public CholeskyDecompositionXmlRepresentation(CholeskyDecompositionImpl cdImpl) throws IOException { super(MediaType.APPLICATION_XML); logger.debug("In CholeskyDecompositionXmlRepresentation constructor"); Document doc = getDocument(); Element rootElement = createXml(cdImpl, doc); doc.appendChild(rootElement); doc.normalizeDocument(); }
From source file:fi.csc.kapaVirtaAS.MessageTransformer.java
public String createAuthenticationString(String message) { try {/* w w w .ja va 2s . c om*/ DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = dBuilder .parse(new InputSource(new ByteArrayInputStream(stripXmlDefinition(message).getBytes()))); doc.setXmlVersion("1.0"); doc.normalizeDocument(); Optional<NodeList> headerNodes = getChildByKeyword( nodeListToStream(doc.getDocumentElement().getChildNodes()), "header"); Optional<NodeList> clientHeaders = headerNodes .map(nodeList -> getChildByKeyword(nodeListToStream(nodeList), "client")) .orElse(Optional.empty()); Number l = clientHeaders.get().getLength(); l.toString(); return clientHeaders .map(nodeList -> getNodeByKeyword(nodeListToStream(nodeList), "xRoadInstance") .map(node -> node.getTextContent())) .orElse(Optional.empty()).orElse("") + ":" + clientHeaders.map(nodeList -> getNodeByKeyword(nodeListToStream(nodeList), "memberClass") .map(node -> node.getTextContent())).orElse(Optional.empty()).orElse("") + ":" + clientHeaders.map(nodeList -> getNodeByKeyword(nodeListToStream(nodeList), "memberCode") .map(node -> node.getTextContent())).orElse(Optional.empty()).orElse("") + ":" + clientHeaders.map(nodeList -> getNodeByKeyword(nodeListToStream(nodeList), "subsystemCode") .map(node -> node.getTextContent())).orElse(Optional.empty()).orElse(""); } catch (Exception e) { log.error("Error in parsing authenticationstring"); log.error(e.toString()); return ""; } }
From source file:fi.csc.kapaVirtaAS.MessageTransformer.java
public String transform(String message, MessageDirection direction) throws Exception { try {//from w w w .j a v a 2s .c o m DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = dBuilder .parse(new InputSource(new ByteArrayInputStream(stripXmlDefinition(message).getBytes()))); doc.setXmlVersion("1.0"); doc.normalizeDocument(); Element root = doc.getDocumentElement(); if (direction == MessageDirection.XRoadToVirta) { // Save XRoad schema prefix for response message xroadSchemaPrefix = namedNodeMapToStream(root.getAttributes()) .filter(node -> node .getNodeValue().toLowerCase().contains(conf.getXroadSchema().toLowerCase())) .findFirst() .orElseThrow( () -> new DOMException(DOMException.NOT_FOUND_ERR, "Xroad schema prefix not found")) .getNodeName(); xroadIdSchemaPrefix = namedNodeMapToStream(root.getAttributes()) .filter(node -> node.getNodeValue().toLowerCase() .contains(conf.getXroadIdSchema().toLowerCase())) .findFirst().orElseThrow(() -> new DOMException(DOMException.NOT_FOUND_ERR, "XroadId schema prefix not found")) .getNodeName(); // Change tns schema getNodeByKeyword(namedNodeMapToStream(root.getAttributes()), conf.getAdapterServiceSchema()) .map(attribute -> setNodeValueToNode(attribute, conf.getVirtaServiceSchema())); //There should be two children under the root node: header and body for (int i = 0; i < root.getChildNodes().getLength(); ++i) { Node child = root.getChildNodes().item(i); // Save soap-headers for reply message and remove child elements under soap-headers if (child.getNodeName().toLowerCase().contains("header")) { this.xroadHeaderElement = child.cloneNode(true); root.replaceChild(child.cloneNode(false), child); } // Change SOAP-body else if (child.getNodeName().toLowerCase().contains("body")) { for (int j = 0; j < child.getChildNodes().getLength(); ++j) { if (child.getChildNodes().item(j).getNodeType() == Node.ELEMENT_NODE) { doc.renameNode(child.getChildNodes().item(j), conf.getVirtaServiceSchema(), child.getChildNodes().item(j).getNodeName() + "Request"); break; } } } } } if (direction == MessageDirection.VirtaToXRoad) { // Add XRoad schemas with saved prefix to response message root.setAttribute(xroadSchemaPrefix, conf.getXroadSchema()); root.setAttribute(xroadIdSchemaPrefix, conf.getXroadIdSchema()); // Change tns schema getNodeByKeyword(namedNodeMapToStream(root.getAttributes()), conf.getVirtaServiceSchema()) .map(attribute -> setNodeValueToNode(attribute, conf.getAdapterServiceSchema())); // Change SOAP-headers Node headerNode = getNodeByKeyword(nodeListToStream(root.getChildNodes()), "header").get(); for (int i = 0; i < this.xroadHeaderElement.getChildNodes().getLength(); ++i) { headerNode.appendChild(doc.importNode(this.xroadHeaderElement.getChildNodes().item(i), true)); } // Change SOAP-body getNodeByKeyword(nodeListToStream(root.getChildNodes()), "body") .map(bodyNode -> removeAttribureFromElement(nodeToElement(bodyNode), virtaServicePrefix)) .map(bodyNode -> setAttributeToElement(nodeToElement(bodyNode), virtaServicePrefix, conf.getAdapterServiceSchema())); //Virta gives malformed soap fault message. Need to parse it correct. getNodeByKeyword(nodeListToStream(root.getChildNodes()), "body") .map(bodyNode -> nodeListToStream(bodyNode.getChildNodes())).map( nodesInBodyStream -> getNodeByKeyword(nodesInBodyStream, "fault") .map(faultNode -> removeAttribureFromElement( nodeToElement(nodeToElement(faultNode) .getElementsByTagName("faultstring").item(0)), "xml:lang"))); } doc.normalizeDocument(); DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(domSource, result); message = writer.toString(); return stripXmlDefinition(message); } catch (Exception e) { if (direction == MessageDirection.XRoadToVirta) { log.error("Error in parsing request message."); throw e; } else { log.error("Error in parsing response message"); log.error(e.toString()); return stripXmlDefinition(faultMessageService.generateSOAPFault(message, faultMessageService.getResValidFail(), this.xroadHeaderElement)); } } }
From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java
static public Document parseDOM(InputStream is) throws SAXException, IOException, EngineException { Document doc = getDefaultDocumentBuilder().parse(is); doc.normalizeDocument(); return doc;/*ww w. j a va2 s . com*/ }
From source file:com.sitewhere.configuration.ConfigurationMigrationSupport.java
/** * Perform the migration work.//www.j a v a2 s. c o m * * @param document * @throws SiteWhereException */ protected static void migrateTenantConfiguration(Document document) throws SiteWhereException { Element beans = document.getDocumentElement(); Element config = DomUtils.getChildElementByTagName(beans, "tenant-configuration"); if (config == null) { throw new SiteWhereException("Tenant configuration element not found."); } Element dcomm = DomUtils.getChildElementByTagName(config, "device-communication"); if (dcomm == null) { throw new SiteWhereException("Device communication element missing."); } Element asset = DomUtils.getChildElementByTagName(config, "asset-management"); if (asset == null) { throw new SiteWhereException("Asset management element missing."); } Element eproc = DomUtils.getChildElementByTagName(config, "event-processing"); if (eproc == null) { LOGGER.info("Event processing element missing. Migrating to new configuration format."); eproc = document.createElementNS(config.getNamespaceURI(), "event-processing"); eproc.setPrefix(config.getPrefix()); config.insertBefore(eproc, asset); moveEventProcessingElements(config, dcomm, eproc, document); } document.normalizeDocument(); }
From source file:dk.dma.ais.abnormal.analyzer.AbnormalAnalyzerAppModule.java
private List<BoundingBox> parseGeoMaskXmlInputStream(InputStream is) { List<BoundingBox> boundingBoxes = new ArrayList<>(); try {/* www .j a v a2s. co m*/ DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = documentBuilder.parse(is); document.normalizeDocument(); final NodeList areaPolygons = document.getElementsByTagName("area_polygon"); final int numAreaPolygons = areaPolygons.getLength(); for (int i = 0; i < numAreaPolygons; i++) { Node areaPolygon = areaPolygons.item(i); LOG.debug( "XML reading area_polygon " + areaPolygon.getAttributes().getNamedItem("name").toString()); NodeList polygons = areaPolygon.getChildNodes(); int numPolygons = polygons.getLength(); for (int p = 0; p < numPolygons; p++) { Node polygon = polygons.item(p); if (polygon instanceof Element) { NodeList items = polygon.getChildNodes(); int numItems = items.getLength(); BoundingBox boundingBox = null; try { for (int j = 0; j < numItems; j++) { Node item = items.item(j); if (item instanceof Element) { final double lat = Double .parseDouble(item.getAttributes().getNamedItem("lat").getNodeValue()); final double lon = Double .parseDouble(item.getAttributes().getNamedItem("lon").getNodeValue()); if (boundingBox == null) { boundingBox = BoundingBox.create(Position.create(lat, lon), Position.create(lat, lon), CoordinateSystem.CARTESIAN); } else { boundingBox = boundingBox.include(Position.create(lat, lon)); } } } LOG.info("Blocking messages in bbox " + areaPolygon.getAttributes().getNamedItem("name").toString() + ": " + boundingBox.toString() + " " + (boundingBox.getMaxLat() - boundingBox.getMinLat()) + " " + (boundingBox.getMaxLon() - boundingBox.getMinLon())); boundingBoxes.add(boundingBox); } catch (NumberFormatException e) { LOG.error(e.getMessage(), e); } } } } } catch (ParserConfigurationException e) { e.printStackTrace(System.err); } catch (SAXException e) { e.printStackTrace(System.err); } catch (IOException e) { e.printStackTrace(System.err); } return boundingBoxes; }
From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java
@Test public void testPerformEntityResolutionWithDetermFactors() throws Exception { XmlConverter converter = new XmlConverter(); converter.getDocumentBuilderFactory().setNamespaceAware(true); InputStream attributeParametersStream = getClass() .getResourceAsStream("/xml/TestAttributeParametersWithDeterm.xml"); entityResolutionMessageHandler.setAttributeParametersStream(attributeParametersStream); testRequestMessageInputStream = getClass() .getResourceAsStream("/xml/EntityMergeRequestMessageForDeterm.xml"); Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream); Node entityContainerNode = testRequestMessage .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer") .item(0);//from w ww . jav a 2 s. co m assertNotNull(entityContainerNode); Document resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null, null); resultDocument.normalizeDocument(); // LOG.info(converter.toString(resultDocument)); XPath xp = XPathFactory.newInstance().newXPath(); xp.setNamespaceContext(new EntityResolutionNamespaceContext()); NodeList entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity", resultDocument, XPathConstants.NODESET); assertEquals(2, entityNodes.getLength()); entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument, XPathConstants.NODESET); assertEquals(2, entityNodes.getLength()); entityNodes = (NodeList) xp.evaluate("//merge-result-ext:OriginalRecordReference", resultDocument, XPathConstants.NODESET); assertEquals(2, entityNodes.getLength()); for (int i = 0; i < entityNodes.getLength(); i++) { Element e = (Element) entityNodes.item(i); String entityIdRef = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "ref"); assertNotNull(entityIdRef); assertNotNull(xp.evaluate("//merge-result-ext:Entity[@s:id='" + entityIdRef + "']", resultDocument, XPathConstants.NODE)); } }
From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java
@Test public void testPerformEntityResolution() throws Exception { XPath xp = XPathFactory.newInstance().newXPath(); xp.setNamespaceContext(testNamespaceContext); XmlConverter converter = new XmlConverter(); converter.getDocumentBuilderFactory().setNamespaceAware(true); Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream); // LOG.info(converter.toString(testRequestMessage)); Node entityContainerNode = testRequestMessage .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer") .item(0);//from w w w. j a va 2s . c o m assertNotNull(entityContainerNode); List<String> lastNames = new ArrayList<String>(); List<String> firstNames = new ArrayList<String>(); List<String> sids = new ArrayList<String>(); NodeList inputEntityNodes = (NodeList) testRequestMessage .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "Entity"); int inputEntityNodeCount = 6; assertEquals(inputEntityNodeCount, inputEntityNodes.getLength()); for (int i = 0; i < inputEntityNodeCount; i++) { Node entityNode = inputEntityNodes.item(i); lastNames.add( xp.evaluate("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName", entityNode)); firstNames.add( xp.evaluate("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName", entityNode)); sids.add(xp.evaluate( "ext:PersonSearchResult/ext:Person/jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID", entityNode)); } Map<String, Integer> lastNameCountMap = new HashMap<String, Integer>(); for (String lastName : lastNames) { Integer count = lastNameCountMap.get(lastName); if (count == null) { count = 0; } lastNameCountMap.put(lastName, ++count); } Map<String, Integer> firstNameCountMap = new HashMap<String, Integer>(); for (String firstName : firstNames) { Integer count = firstNameCountMap.get(firstName); if (count == null) { count = 0; } firstNameCountMap.put(firstName, ++count); } Map<String, Integer> sidCountMap = new HashMap<String, Integer>(); for (String sid : sids) { Integer count = sidCountMap.get(sid); if (count == null) { count = 0; } sidCountMap.put(sid, ++count); } Document resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null, null); resultDocument.normalizeDocument(); // LOG.info(converter.toString(resultDocument)); NodeList entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity", resultDocument, XPathConstants.NODESET); assertEquals(inputEntityNodeCount, entityNodes.getLength()); entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument, XPathConstants.NODESET); assertEquals(3, entityNodes.getLength()); entityNodes = (NodeList) xp.evaluate("//merge-result-ext:OriginalRecordReference", resultDocument, XPathConstants.NODESET); assertEquals(inputEntityNodeCount, entityNodes.getLength()); for (int i = 0; i < entityNodes.getLength(); i++) { Element e = (Element) entityNodes.item(i); String entityIdRef = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "ref"); assertNotNull(entityIdRef); assertNotNull(xp.evaluate("//merge-result-ext:Entity[@s:id='" + entityIdRef + "']", resultDocument, XPathConstants.NODE)); } for (String lastName : lastNameCountMap.keySet()) { assertEquals(lastNameCountMap.get(lastName).intValue(), ((Number) xp.evaluate( "count(//merge-result-ext:Entity[ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName='" + lastName + "'])", resultDocument, XPathConstants.NUMBER)).intValue()); } for (String firstName : firstNames) { assertEquals(firstNameCountMap.get(firstName).intValue(), ((Number) xp.evaluate( "count(//merge-result-ext:Entity[ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName='" + firstName + "'])", resultDocument, XPathConstants.NUMBER)).intValue()); } for (String sid : sids) { assertEquals(sidCountMap.get(sid).intValue(), ((Number) xp.evaluate( "count(//merge-result-ext:Entity[ext:PersonSearchResult/ext:Person/jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID='" + sid + "'])", resultDocument, XPathConstants.NUMBER)).intValue()); } String recordLimitExceeded = xp.evaluate( "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument); assertEquals("false", recordLimitExceeded); }
From source file:com.servicelibre.jxsl.scenario.XslScenario.java
private Document asXml(RunReport runReport) { XStream xstream = new XStream(new DomDriver()); String xml = xstream.toXML(runReport); Document reportDoc = null; try {//from w w w .j a va 2s . c o m reportDoc = xmlBuilder.parse(new ByteArrayInputStream(xml.getBytes())); reportDoc.normalizeDocument(); } catch (SAXException e) { logger.error("Error while converting runReport to XML", e); } catch (IOException e) { logger.error("Error while converting runReport to XML", e); } return reportDoc; }
From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandler.java
/** * This method performs entity resolution and returns the Merge Response Document. * /*w w w . j a v a 2s . c o m*/ * @param entityContainerNode * @param attributeParametersNode * @param entityResolutionConfigurationNode * @return * @throws Exception * @throws ParserConfigurationException * @throws XPathExpressionException */ Document performEntityResolution(Node entityContainerNode, Node attributeParametersNode, Node entityResolutionConfigurationNode) throws Exception, ParserConfigurationException, XPathExpressionException { Set<AttributeParametersXpathSupport> attributeParametersXpathSupport = getAttributeParameters( attributeParametersNode); // We can't call the ER OSGi service with AttributeParametersXpathSupport Set // so we create an attributeParameters Set to call it with. Set<AttributeParameters> attributeParameters = new HashSet<AttributeParameters>(); for (AttributeParametersXpathSupport attributeParameterXpathSupport : attributeParametersXpathSupport) { attributeParameters.add(attributeParameterXpathSupport); } String recordLimitString = null; if (entityResolutionConfigurationNode != null) { recordLimitString = xpath.evaluate("er-ext:RecordLimit", entityResolutionConfigurationNode); } int recordLimit = Integer.MAX_VALUE; if (recordLimitString != null) { try { recordLimit = Integer.parseInt(recordLimitString); } catch (NumberFormatException nfe) { LOG.debug("Record limit value " + recordLimitString + " does not parse as an integer, will not set a record limit"); } } EntityResolutionResults results = null; NodeList entityNodeList = (NodeList) xpath.evaluate("er-ext:Entity", entityContainerNode, XPathConstants.NODESET); if (entityNodeList.getLength() <= recordLimit) { List<RecordWrapper> records = createRecordsFromRequestMessage(entityNodeList, attributeParametersNode); LOG.debug("before resolveEntities, records=" + records); results = entityResolutionService.resolveEntities(records, attributeParameters, recordLimit); } Document resultDocument = createResponseMessage(entityContainerNode, results, attributeParametersNode, recordLimit); // without this next line, we get an exception about an unbound namespace URI (NIEM structures) resultDocument.normalizeDocument(); return resultDocument; }