List of usage examples for org.dom4j XPath selectNodes
List<Node> selectNodes(Object context);
selectNodes
performs this XPath expression on the given Node or List of Node s instances appending all the results together into a single list. From source file:org.codehaus.modello.plugin.utils.Dom4jUtils.java
License:Apache License
/** * Asserts that the specified {@link Document} does not contains any <b>text</b> * nodes at the location specified by an XPATH expression. * //from w ww .ja va 2 s.c o m * @param doc target {@link Document} instance where the text nodes are to * be located. * @param xpathToParentNode XPATH expression to locate the parent node where * the search for text nodes is to be started. * @param recursive true if the specified parent node is to be searched * recursively. */ public static void assertNoTextNodes(Document doc, String xpathToParentNode, boolean recursive) { if (StringUtils.isEmpty(xpathToParentNode)) { throw new AssertionFailedError("Unable to assert an attribute using an empty xpath."); } if (doc == null) { throw new AssertionFailedError("Unable to assert an attribute using a null document."); } XPath xpath = doc.createXPath(xpathToParentNode); List nodes = xpath.selectNodes(doc); if ((nodes == null) || nodes.isEmpty()) { throw new AssertionFailedError("Expected Node(s) at '" + xpathToParentNode + "', but was not found."); } Iterator it = nodes.iterator(); while (it.hasNext()) { Node node = (Node) it.next(); assertNoTextNode("No Text should exist in '" + xpathToParentNode + "'", node, recursive); } }
From source file:org.craftercms.core.util.XmlUtils.java
License:Open Source License
/** * Executes the specified namespace aware XPath query as a multiple node query, returning the resulting list of nodes. *//*w w w .j a v a 2s . c o m*/ @SuppressWarnings("unchecked") public static List<Node> selectNodes(Node node, String xpathQuery, Map<String, String> namespaceUris) { XPath xpath = DocumentHelper.createXPath(xpathQuery); xpath.setNamespaceURIs(namespaceUris); return xpath.selectNodes(node); }
From source file:org.danann.cernunnos.xml.NodeProcessor.java
License:Apache License
public static void evaluatePhrases(Node n, Grammar g, TaskRequest req, TaskResponse res) { // Assertions... if (n == null) { String msg = "Argument 'n [Node]' cannot be null."; throw new IllegalArgumentException(msg); }// w ww . j a va 2 s .c o m if (g == null) { String msg = "Argument 'g [Grammar]' cannot be null."; throw new IllegalArgumentException(msg); } if (n instanceof Branch) { ((Branch) n).normalize(); } final XPath xpath = XPATH_LOCAL.get(); for (Iterator<?> it = xpath.selectNodes(n).iterator(); it.hasNext();) { Node d = (Node) it.next(); if (d.getText().trim().length() != 0) { Phrase p = g.newPhrase(d); Object o = p.evaluate(req, res); String value = o != null ? o.toString() : "null"; d.setText(value); } } }
From source file:org.esupportail.lecture.domain.model.Source.java
/** * Make Items objects in fonction of itemXPath, xsltURL, xmlStream. * @throws ComputeItemsException //from w w w . j a va 2 s . c o m */ @SuppressWarnings("unchecked") synchronized private void computeItems() throws ComputeItemsException { if (LOG.isDebugEnabled()) { LOG.debug("id=" + this.profileId + " - computeItems()"); } if (!itemComputed) { try { //create dom4j document Document document = DocumentHelper.parseText(xmlStream); // get encoding String encoding = document.getXMLEncoding(); //lauch Xpath find String x = getItemXPath(); XPath xpath = document.createXPath(x); xpath.setNamespaceURIs(getXPathNameSpaces()); List<Node> list = xpath.selectNodes(document); //List<Node> list = document.selectNodes(getItemXPath()); Iterator<Node> iter = list.iterator(); while (iter.hasNext()) { Node node = iter.next(); Item item = new Item(this); StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\""); xml.append(encoding); xml.append("\" ?>"); xml.append(node.asXML()); String xmlAsString = xml.toString(); String htmlContent = xml2html(xmlAsString, getXsltURL(), encoding); item.setHtmlContent(htmlContent); String MobileHtmlContent = xml2html(xmlAsString, getMobileXsltURL(), encoding); item.setMobileHtmlContent(MobileHtmlContent); //find MD5 of item content for his ID byte[] hash = MessageDigest.getInstance("MD5").digest(xmlAsString.getBytes()); StringBuffer hashString = new StringBuffer(); for (int i = 0; i < hash.length; ++i) { String hex = Integer.toHexString(hash[i]); if (hex.length() == 1) { hashString.append('0'); hashString.append(hex.charAt(hex.length() - 1)); } else { hashString.append(hex.substring(hex.length() - 2)); } } item.setId(hashString.toString()); items.add(item); } } catch (DocumentException e) { String errorMsg = "Error parsing XML content of the source"; LOG.error(errorMsg, e); throw new ComputeItemsException(errorMsg, e); } catch (NoSuchAlgorithmException e) { String errorMsg = "MD5 algorithm not supported"; LOG.error(errorMsg, e); throw new ComputeItemsException(errorMsg, e); } catch (XPathException e) { String errorMsg = "Xpath with NameSpace not specified in mappings.xml"; LOG.error(errorMsg, e); throw new ComputeItemsException(errorMsg, e); } catch (MappingNotFoundException e) { String errorMsg = "Impossible to get itemXPath,XPathNameSpaces and xsltURL"; LOG.error(errorMsg, e); throw new ComputeItemsException(errorMsg, e); } catch (Xml2HtmlException e) { String errorMsg = "Impossible to make html content"; LOG.error(errorMsg, e); throw new ComputeItemsException(errorMsg, e); } itemComputed = true; } }
From source file:org.footware.server.gpx.GPXImport.java
License:Apache License
private List<GPXTrack> parseXML(File file) { LinkedList<GPXTrack> tracks = new LinkedList<GPXTrack>(); try {// w w w . jav a 2s. co m long startTime = System.currentTimeMillis(); logger.info("Start parsing @" + startTime); // Determine GPX Version SAXReader xmlReader = new SAXReader(); Document document = xmlReader.read(file); String version = document.getRootElement().attributeValue("version"); File xsd = null; if (version.equals("1.1")) { logger.info("Detected gpx version " + version + " +" + (System.currentTimeMillis() - startTime)); xsd = new File("gpx_1_1.xsd"); GPX_NAMESPACE_URI = GPX_NAMESPACE_URI_1_1; } else if (version.equals("1.0")) { logger.info("Detected gpx version '" + version + "' +" + (System.currentTimeMillis() - startTime)); xsd = new File("gpx_1_0.xsd"); GPX_NAMESPACE_URI = GPX_NAMESPACE_URI_1_0; } else { logger.info("No supported version detected: " + version + " +" + (System.currentTimeMillis() - startTime)); // As default we try version 1.1 xsd = new File("gpx_1_1.xsd"); GPX_NAMESPACE_URI = GPX_NAMESPACE_URI_1_1; } // Parse GPX SAXParserFactory factory = SAXParserFactory.newInstance(); SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setSchema(schemaFactory.newSchema(xsd)); SAXParser parser = factory.newSAXParser(); SAXReader reader = new SAXReader(parser.getXMLReader()); reader.setValidation(true); reader.setErrorHandler(new SimpleErrorHandler()); document = reader.read(file); logger.info("End parsing +" + (System.currentTimeMillis() - startTime)); // Define namespaces HashMap<String, String> namespacesMap = new HashMap<String, String>(); namespacesMap.put(GPX_NS, GPX_NAMESPACE_URI); // Find tracks logger.info("Search tracks +" + (System.currentTimeMillis() - startTime)); XPath xpathTrk = DocumentHelper.createXPath("//" + GPX_NS + ":trk"); xpathTrk.setNamespaceURIs(namespacesMap); List<Element> xmlTracks = xpathTrk.selectNodes(document); logger.info("Found " + xmlTracks.size() + " tracks +" + (System.currentTimeMillis() - startTime)); GPXTrack track; // for (Element xmlTrack : xmlTracks) { // Iterate about all tracks of the gpx file for (int currentTrackNummer = 1; currentTrackNummer <= xmlTracks.size(); currentTrackNummer++) { logger.info("Start track " + currentTrackNummer + " +" + (System.currentTimeMillis() - startTime)); track = new GPXTrack(); // Find track segments XPath xpathTrkseg = DocumentHelper .createXPath("//" + GPX_NS + ":trk[" + currentTrackNummer + "]/" + GPX_NS + ":trkseg"); xpathTrkseg.setNamespaceURIs(namespacesMap); List<Element> xmlTrackSegs = xpathTrkseg.selectNodes(document); logger.info("Found " + xmlTrackSegs.size() + " segments for track " + currentTrackNummer + " +" + (System.currentTimeMillis() - startTime)); // List<Element> xmlTrackSegs = // xmlTrack.selectNodes("//trkseg"); GPXTrackSegment trackSegment; // for (Element xmlTrackSeq : xmlTrackSegs) { // Iterate above all segments of a track for (int currentTrackSegmentNummer = 1; currentTrackSegmentNummer <= xmlTrackSegs .size(); currentTrackSegmentNummer++) { trackSegment = new GPXTrackSegment(); // Find track points XPath xpathTrkPt = DocumentHelper.createXPath("//" + GPX_NS + ":trk[" + currentTrackNummer + "]/" + GPX_NS + ":trkseg[" + currentTrackSegmentNummer + "]/" + GPX_NS + ":trkpt"); xpathTrkPt.setNamespaceURIs(namespacesMap); List<Element> xmlTrackPts = xpathTrkPt.selectNodes(document); logger.info("Found " + xmlTrackPts.size() + " points for segment " + currentTrackSegmentNummer + " for track " + currentTrackNummer + " +" + (System.currentTimeMillis() - startTime)); GPXTrackPoint trackPoint; BigDecimal latitude; BigDecimal longitude; BigDecimal elevation; DateTime time; // Iterate above all points of a segment of a track for (Element xmlTrackPt : xmlTrackPts) { latitude = new BigDecimal(xmlTrackPt.attributeValue(LATITUDE)); longitude = new BigDecimal(xmlTrackPt.attributeValue(LONGITUDE)); elevation = new BigDecimal(xmlTrackPt.element(ELEVATION).getText()); time = ISODateTimeFormat.dateTimeNoMillis() .parseDateTime(xmlTrackPt.element(TIME).getText()); trackPoint = new GPXTrackPoint(latitude, longitude, elevation, time); trackSegment.addPoint(trackPoint); } track.addTrackSegment(trackSegment); } tracks.add(track); } logger.info("Done parsing +" + (System.currentTimeMillis() - startTime)); } catch (ParserConfigurationException e) { logger.error("ParserConfigurationException", e); e.printStackTrace(); } catch (SAXException e) { logger.error("SAXException", e); e.printStackTrace(); } catch (DocumentException e) { logger.error("DocumentException", e); e.printStackTrace(); } return tracks; }
From source file:org.gbif.portal.util.mhf.message.impl.xml.XMLMessage.java
License:Open Source License
/** * Gets a list of Strings for the multiple values that will be * returned from the XPath//from www .ja v a2s . c o m * * @param location Xpath to evaluate * @return The List of Node */ @SuppressWarnings("unchecked") public List<String> getPartsAsString(Object location) throws MessageAccessException { if (!(location instanceof XPath)) { throw new MessageAccessException("Only XPath location's are supported for accessing XMLMessage parts - " + "received: " + location.getClass()); } XPath xpath = (XPath) location; String key = GET_PARTS_AS_STRING_KEY_PREFIX + xpath.getText(); if (getCache().containsKey(key)) { return (List<String>) getCache().get(key); } else { List<Node> result = (List<Node>) xpath.selectNodes(getDocument()); List<String> resultsAsString = new LinkedList<String>(); for (Node node : result) { resultsAsString.add(node.getText()); } getCache().put(key, resultsAsString); return resultsAsString; } }
From source file:org.gbif.portal.util.mhf.message.impl.xml.XMLMessage.java
License:Open Source License
/** * Gets a list of MessageIndex// w w w . j ava2s. c o m * returned from the XPath * * @param location Xpath to evaluate * @return The List of Node */ @SuppressWarnings("unchecked") public List<Message> getParts(Object location) throws MessageAccessException, MessageParseException { if (!(location instanceof XPath)) { throw new MessageAccessException("Only XPath location's are supported for accessing XMLMessage parts - " + "received: " + location.getClass()); } XPath xpath = (XPath) location; String key = GET_PARTS_KEY_PREFIX + xpath.getText(); if (getCache().containsKey(key)) { return (List<Message>) getCache().get(key); } else { List<Node> result = (List<Node>) xpath.selectNodes(getDocument()); List<Message> resultsAsIndex = new LinkedList<Message>(); for (Node node : result) { Message indexedResult = new XMLMessageFactory().build(node, true); resultsAsIndex.add(indexedResult); } getCache().put(key, resultsAsIndex); return resultsAsIndex; } }
From source file:org.intalio.tempo.workflow.fds.core.UserProcessMessageConvertor.java
License:Open Source License
/** * Converts a SOAP message from a user process to the WorkflowProcesses * format. <br>// ww w . j av a 2 s. c o m * The conversion is done in-place. The passed <code>Document</code> * instance gets converted to the Workflow Processes format and its previous * format is lost. * * @param message * The SOAP message from a user process to convert to the * Workflow Processes format. * @throws MessageFormatException * If the specified message has an invalid format. Note that if * this exception is thrown, <code>message</code> may have * already been partly processed and therefore should be assumed * to be corrupted. */ @SuppressWarnings("unchecked") public void convertMessage(Document message) throws MessageFormatException, AxisFault { FormDispatcherConfiguration config = FormDispatcherConfiguration.getInstance(); XPath xpath = null; xpath = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/soapenv:Fault"); List<Node> fault = xpath.selectNodes(message); if (fault.size() != 0) throw new RuntimeException(fault.toString()); // Check SOAP action xpath = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body"); xpath.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> bodyQueryResult = xpath.selectNodes(message); if (bodyQueryResult.size() != 0) { Element root = (Element) bodyQueryResult.get(0); if (root.asXML().indexOf("createTaskRequest") != -1) { _soapAction = "createTask"; xpath = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Header/addr:Action"); xpath.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> wsaActionQueryResult = xpath.selectNodes(message); if (wsaActionQueryResult.size() != 0) { Element wsaToElement = (Element) wsaActionQueryResult.get(0); wsaToElement.setText(_soapAction); } else _log.warn("Did not find addr:Action in SOAP header"); } } _log.debug("Converted SOAP Action: " + _soapAction); /* * Change the wsa:To endpoint to Workflow Processes, if a wsa:To header * is present. */ xpath = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Header/addr:To"); xpath.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> wsaToQueryResult = xpath.selectNodes(message); if (wsaToQueryResult.size() != 0) { Element wsaToElement = (Element) wsaToQueryResult.get(0); String workflowProcessesUrl = config.getPxeBaseUrl() + config.getWorkflowProcessesRelativeUrl(); wsaToElement.setText(workflowProcessesUrl); } else _log.debug("Did not find addr:To in SOAP header"); /* * Change the session address to be FDS endpoint and retrieve sender * endpoint */ xpath = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Header/intalio:callback/addr:Address"); xpath.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> callbackToQueryResult = xpath.selectNodes(message); if (callbackToQueryResult.size() != 0) { Element wsaToElement = (Element) callbackToQueryResult.get(0); _userProcessEndpoint = wsaToElement.getText(); wsaToElement.setText(config.getFdsUrl()); } else _log.debug("Did not find intalio:callback/addr:Address in SOAP header"); /* Next, fetch the user process namespace URI from the task metadata */ /* * 1. fetch the first element of SOAP envelope body. */ List<Node> allSoapBodyElements = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body//*") .selectNodes(message); if (allSoapBodyElements.size() == 0) { throw new MessageFormatException("No elements found inside soapenv:Body."); } Element firstPayloadElement = (Element) allSoapBodyElements.get(0); /* * 2. fetch its namespace and use it to fetch the userProcessEndpoint * and userProcessNamespaceURI element (which should be in the same * namespace). If those elements are not found, nothing is reported. * This is necessary for converting responses, where this information is * not present. */ String messageNamespace = firstPayloadElement.getNamespaceURI(); _userProcessNamespaceUri = messageNamespace; Map<String, String> namespaceURIs = new HashMap<String, String>(MessageConstants.get_nsMap()); namespaceURIs.put(REQUEST_PREFIX, _userProcessNamespaceUri); /* * Add session in task meta data so that it can be retrieved when * workflow process needs to send a message to the user process */ xpath = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Header/intalio:callback/intalio:session"); xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */); List<Node> sessionQueryResult = xpath.selectNodes(message); if (sessionQueryResult.size() != 0) { Element wsaToElement = (Element) sessionQueryResult.get(0); String session = wsaToElement.getText(); xpath = DocumentHelper.createXPath("//" + REQUEST_PREFIX + ":taskMetaData"); xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */); List<Node> tmdQueryResult = xpath.selectNodes(message); Element tmdElement = (Element) tmdQueryResult.get(0); Element sessionElement = tmdElement.addElement("session", MessageConstants.IB4P_NS); sessionElement.setText(session); } // retrieve userProcessEndpoint from task meta data // or put sender endpoint in task meta data if not defined xpath = DocumentHelper .createXPath("//" + REQUEST_PREFIX + ":taskMetaData/" + REQUEST_PREFIX + ":userProcessEndpoint"); xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */); List<Node> endpointQueryResult = xpath.selectNodes(message); if (endpointQueryResult.size() != 0) { Element userProcessEndpointElement = (Element) endpointQueryResult.get(0); String value = userProcessEndpointElement.getText(); if (value != null && value.length() > 0) _userProcessEndpoint = value; else if (_userProcessEndpoint != null) { _log.info("User process endpoint is empty in task metadata, adding " + _userProcessEndpoint); userProcessEndpointElement.setText(_userProcessEndpoint); } } else if (_userProcessEndpoint != null) { _log.info("User process endpoint is not defined in task metadata, adding " + _userProcessEndpoint); xpath = DocumentHelper.createXPath("//" + REQUEST_PREFIX + ":taskMetaData"); xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */); List<Node> tmdQueryResult = xpath.selectNodes(message); if (tmdQueryResult.size() > 0) { Element wsaToElement = (Element) tmdQueryResult.get(0); Element nsElement = wsaToElement.addElement("userProcessEndpoint", MessageConstants.IB4P_NS); nsElement.setText(_userProcessEndpoint); } } // Add user process namespace to taskmetadata if not already defined xpath = DocumentHelper.createXPath( "//" + REQUEST_PREFIX + ":taskMetaData/" + REQUEST_PREFIX + ":userProcessNamespaceURI"); xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */); List<Node> nsQueryResult = xpath.selectNodes(message); if (nsQueryResult.size() == 0 && _userProcessNamespaceUri != null) { xpath = DocumentHelper.createXPath("//" + REQUEST_PREFIX + ":taskMetaData"); xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */); List<Node> tmdQueryResult = xpath.selectNodes(message); if (tmdQueryResult.size() > 0) { _log.info("User process namespace is not defined in task metadata, adding " + _userProcessNamespaceUri); Element wsaToElement = (Element) tmdQueryResult.get(0); Element nsElement = wsaToElement.addElement("userProcessNamespaceURI", MessageConstants.IB4P_NS); nsElement.setText(_userProcessNamespaceUri); } } else { Element wsaToElement = (Element) nsQueryResult.get(0); if (wsaToElement.getTextTrim().length() == 0) { _log.info("User process namespace is empty in task metadata, adding " + _userProcessNamespaceUri); wsaToElement.setText(_userProcessNamespaceUri); } } /* * Now, change the namespace of all soapenv:Body elements, except the * task input and the attachments, to ib4p. */ xpath = DocumentHelper.createXPath("//" + REQUEST_PREFIX + ":taskInput//*"); xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */); List<Node> allTaskInputElements = xpath.selectNodes(message); xpath = DocumentHelper.createXPath("//" + REQUEST_PREFIX + ":attachments//*"); xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */); List<Node> allAttachmentsElements = xpath.selectNodes(message); for (int i = 0; i < allSoapBodyElements.size(); ++i) { Node node = (Node) allSoapBodyElements.get(i); if (!allTaskInputElements.contains(node) && !allAttachmentsElements.contains(node)) { Element element = (Element) node; element.remove(element.getNamespace()); element.setQName(QName.get(element.getName(), "ib4p", MessageConstants.IB4P_NS)); } } }
From source file:org.intalio.tempo.workflow.fds.core.WorkflowProcessesMessageConvertor.java
License:Open Source License
/** * Converts a SOAP message from the Workflow Processes format to the format * of the user process the message is targetted for. <br> * The target user process is figured out from the message payload. <br> * The conversion is done in-place. The passed <code>Document</code> * instance gets converted to the user process format and its previous * format is lost.//ww w .jav a2s.c o m * * @param message * The SOAP message coming from the Workflow Processes to convert * to the user process format. * @param userProcessNamespaceUri * The user process namespace URI. Should be <code>null</code> * when converting the <i>requests</i>. Must be specified when * converting the <i>replies</i>, since in this case no * information about the target user process is specified inside * the message. * @throws MessageFormatException * If the specified message has an invalid format. Note that if * this exception is thrown, <code>message</code> may have * already been partly processed and therefore should be assumed * to be corrupted. */ @SuppressWarnings("unchecked") public void convertMessage(Document message, String userProcessNamespaceUri) throws MessageFormatException { XPath xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/soapenv:Fault"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> fault = xpathSelector.selectNodes(message); if (fault.size() != 0) { // return fault as-is LOG.error("Fault in response:\n" + message.asXML()); return; } //retrieve session xpathSelector = DocumentHelper .createXPath("/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskMetaData/ib4p:session"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> sessionNodes = xpathSelector.selectNodes(message); if (sessionNodes.size() > 0) { Element sessionElement = (Element) sessionNodes.get(0); String session = sessionElement.getText(); //remove callback xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Header/intalio:callback"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> callbackNodes = xpathSelector.selectNodes(message); if (callbackNodes.size() != 0) { Element wsaTo = (Element) callbackNodes.get(0); Element header = (Element) wsaTo.getParent(); header.remove(wsaTo); sessionElement = header.addElement("session", MessageConstants.INTALIO_NS); sessionElement.setText(session); } } /* fetch the user process endpoint element from the task metadata */ xpathSelector = DocumentHelper .createXPath("/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskMetaData/ib4p:userProcessEndpoint"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> userProcessEndpointNodes = xpathSelector.selectNodes(message); if (userProcessEndpointNodes.size() > 0) { /* found the user process endpoint element */ Element userProcessEndpointElement = (Element) userProcessEndpointNodes.get(0); /* save it for later use */ _userProcessEndpoint = userProcessEndpointElement.getText(); /* do we have a wsa:To element? */ xpathSelector = DocumentHelper.createXPath("//wsa:To"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> wsaToNodes = xpathSelector.selectNodes(message); if (wsaToNodes.size() != 0) { /* We have the wsa:To element. Set the correct target endpoint */ Element wsaTo = (Element) wsaToNodes.get(0); wsaTo.setText(_userProcessEndpoint); } /* do we have a addr:To element? */ xpathSelector = DocumentHelper.createXPath("//addr:To"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> addrToNodes = xpathSelector.selectNodes(message); if (addrToNodes.size() != 0) { /* We have the wsa:To element. Set the correct target endpoint */ Element wsaTo = (Element) addrToNodes.get(0); //wsaTo.removeChildren(); wsaTo.setText(_userProcessEndpoint); } } /* * If the user process namespace URI is not specified explicitly, the * userProcessNamespaceURI element must be present in the metadata * section. */ if (userProcessNamespaceUri == null) { xpathSelector = DocumentHelper.createXPath( "/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskMetaData/ib4p:userProcessNamespaceURI"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> namespaceElementQueryResult = xpathSelector.selectNodes(message); if (namespaceElementQueryResult.size() == 0) { throw new MessageFormatException("No user process namespace specified " + "and no ib4p:userProcessNamespaceURI element present to determine those."); } Element userProcessNamespaceUriElement = (Element) namespaceElementQueryResult.get(0); userProcessNamespaceUri = userProcessNamespaceUriElement.getText(); _userProcessNamespaceUri = userProcessNamespaceUri; } xpathSelector = DocumentHelper.createXPath( "/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskMetaData/ib4p:userProcessCompleteSOAPAction"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> soapActionQueryResult = xpathSelector.selectNodes(message); if (soapActionQueryResult.size() > 0) { Element soapActionElement = (Element) soapActionQueryResult.get(0); _soapAction = soapActionElement.getText(); xpathSelector = DocumentHelper.createXPath("//addr:Action"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> actionNodes = xpathSelector.selectNodes(message); if (actionNodes.size() > 0) { Element wsaTo = (Element) actionNodes.get(0); //wsaTo.removeChildren(); wsaTo.setText(_soapAction); } } // TODO: generate a unique namespace prefix? String userProcessNamespace = "userProcess"; /* Select all elements inside the soap envelope body. */ xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body//*"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> bodyNodes = xpathSelector.selectNodes(message); /* Select all elements inside the task output payload. */ xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/*[1]/ib4p:taskOutput//*"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> taskOutputNodes = xpathSelector.selectNodes(message); /* Select all the attachments. */ xpathSelector = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body//ib4p:attachments//*"); xpathSelector.setNamespaceURIs(MessageConstants.get_nsMap()); List<Node> attachementsNode = xpathSelector.selectNodes(message); /* * Change namespace for all the elements which are inside the soap * envelope body but not inside the task output payload. */ for (int i = 0; i < bodyNodes.size(); ++i) { Node node = (Node) bodyNodes.get(i); if (!taskOutputNodes.contains(node) && !attachementsNode.contains(node)) { Element element = (Element) node; element.remove(element.getNamespace()); element.setQName(QName.get(element.getName(), userProcessNamespace, userProcessNamespaceUri)); } } }
From source file:org.intalio.tempo.workflow.fds.dispatches.NotifyDispatcher.java
License:Open Source License
public Document dispatchRequest(Document request) throws InvalidInputFormatException { Element rootElement = request.getRootElement(); userProcessNamespace = rootElement.getNamespaceURI(); Namespace ns = new Namespace("tms", TMS_NS); rootElement.setQName(new QName("createTaskRequest", ns)); Element metadataElement = rootElement.element("metadata"); metadataElement.setQName(new QName("metadata", ns)); metadataElement.detach();/*from w w w . ja va 2s. co m*/ Element taskElement = rootElement.addElement("task"); taskElement.setQName(new QName("task", ns)); taskElement.add(metadataElement); if (metadataElement.selectSingleNode("taskId") == null) { Element taskIdElement = metadataElement.addElement(new QName("taskId", ns)); taskIdElement.setText(generateUID()); } if (metadataElement.selectSingleNode("taskType") == null) { Element taskTypeElement = metadataElement.addElement(new QName("taskType", ns)); taskTypeElement.setText("NOTIFICATION"); } Element inputElement = rootElement.element("input"); inputElement.setQName(new QName("input", ns)); //inputElement.addNamespace("fe", userProcessNamespace); inputElement.detach(); taskElement.add(inputElement); //TODO remove from TMS. Not needed rootElement.addElement("participantToken"); /* * Now, change the namespace the * input, to TMS_NS. */ XPath xpath = DocumentHelper.createXPath("/tms:createTaskRequest/tms:task/tms:input//*"); HashMap map = MessageConstants._nsMap; map.put("tms", TMS_NS); xpath.setNamespaceURIs(MessageConstants._nsMap); List allTaskInputElements = xpath.selectNodes(request); xpath = DocumentHelper.createXPath("//*"); List allBody = xpath.selectNodes(request); int size = allBody.size(); LOG.debug(allTaskInputElements.size() + ":" + size); for (int i = 0; i < size; ++i) { Node node = (Node) allBody.get(i); if (!allTaskInputElements.contains(node)) { Element element = (Element) node; element.remove(element.getNamespaceForURI(userProcessNamespace)); element.setQName(new QName(element.getName(), ns)); } } return request; }