Example usage for org.dom4j XPath setNamespaceURIs

List of usage examples for org.dom4j XPath setNamespaceURIs

Introduction

In this page you can find the example usage for org.dom4j XPath setNamespaceURIs.

Prototype

void setNamespaceURIs(Map<String, String> map);

Source Link

Document

Sets the current NamespaceContext from a Map where the keys are the String namespace prefixes and the values are the namespace URIs.

Usage

From source file:org.etudes.component.app.melete.MeleteImportServiceImpl.java

License:Apache License

public String getContentSourceInfo(Document document) {
    Map uris = new HashMap();
    uris.put("imscp", DEFAULT_NAMESPACE_URI);
    uris.put("imsmd", IMSMD_NAMESPACE_URI);

    try {/*from  www .j a  v  a2  s  .c  o  m*/
        // description
        XPath xpath = document
                .createXPath("/imscp:manifest/imscp:metadata/imsmd:lom/imsmd:rights/imsmd:description");
        xpath.setNamespaceURIs(uris);

        Element eleOrg = (Element) xpath.selectSingleNode(document);
        if (eleOrg != null) {
            // logger.debug("got desc element" + eleOrg.toString());
            return eleOrg.selectSingleNode(".//imsmd:langstring").getText();
        } else
            return null;
    } catch (Exception e) {
        logger.debug("error in reading other contact info" + e.toString());
        return null;
    }
}

From source file:org.etudes.jforum.view.admin.ImportExportAction.java

License:Apache License

/**
 * Parses the manifest and build topics//from w  w  w.  ja  v  a  2  s .c  om
 * 
 * @param document
 *            document
 * @param unZippedDirPath
 *            unZipped files Directory Path
 * @exception throws exception
 */
public void parseAndCreateTopics(Document document, String unZippedDirPath) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("Entering parseAndCreateTopics");

    boolean isfacilitator = JForumUserUtil.isJForumFacilitator(UserDirectoryService.getCurrentUser().getId())
            || SecurityService.isSuperUser();

    if (!isfacilitator) {
        this.context.put("message", I18n.getMessage("User.NotAuthorizedToManage"));
        this.setTemplateName(TemplateKeys.MANAGE_NOT_AUTHORIZED);
        return;
    }

    // get current site
    Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
    Collection sakaiSiteGroups = site.getGroups();

    Map uris = new HashMap();
    uris.put("imscp", DEFAULT_NAMESPACE_URI);
    uris.put("imsmd", IMSMD_NAMESPACE_URI);

    // organizations
    XPath xpath = document.createXPath("/imscp:manifest/imscp:organizations/imscp:organization");
    xpath.setNamespaceURIs(uris);

    Element eleOrg = (Element) xpath.selectSingleNode(document);

    // create category, forum if not existing and then add task topics of
    // the forum
    // loop thru organization elements - item elements(category)
    List elements = eleOrg.elements();
    for (Iterator iter = elements.iterator(); iter.hasNext();) {
        Element element = (Element) iter.next();
        if (element.getName().equalsIgnoreCase("item")) {
            processXML(element, document, unZippedDirPath);
        }

    }

    if (logger.isDebugEnabled())
        logger.debug("Exiting parseAndCreateTopics");
}

From source file:org.etudes.jforum.view.admin.ImportExportAction.java

License:Apache License

/**
 * gets the resource element/*from w  w  w . ja va  2 s. c o  m*/
 * 
 * @param resName
 *            resource name
 * @param document
 *            document
 * @return resource element
 * @throws Exception
 */
private Element getResource(String resName, Document document) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("Entering getResource...");

    Map uris = new HashMap();
    uris.put("imscp", DEFAULT_NAMESPACE_URI);
    uris.put("imsmd", IMSMD_NAMESPACE_URI);

    // resource
    XPath xpath = document
            .createXPath("/imscp:manifest/imscp:resources/imscp:resource[@identifier = '" + resName + "']");
    xpath.setNamespaceURIs(uris);

    Element eleRes = (Element) xpath.selectSingleNode(document);

    if (logger.isDebugEnabled())
        logger.debug("Exiting getResource...");

    return eleRes;
}

From source file:org.fcrepo.server.messaging.FedoraTypes.java

License:fedora commons license

public String getDatatype(String method, String param) {
    String key = method + "." + param;

    if (!method2datatype.containsKey(key)) {
        String query = String.format("/xsd:schema/xsd:element[@name='%s']" + "/xsd:complexType/xsd:sequence"
                + "/xsd:element[@name='%s']/@type", method, param);
        XPath xpath = DocumentHelper.createXPath(query);
        xpath.setNamespaceURIs(ns2prefix);
        String datatype = xpath.valueOf(getDocument());
        if (datatype.isEmpty()) {
            datatype = null;//  w  w w  .  j  a  v  a  2 s.com
        }
        method2datatype.put(key, datatype);
    }
    return method2datatype.get(key);
}

From source file:org.fcrepo.server.messaging.FedoraTypes.java

License:fedora commons license

public String getResponseParameter(String response) {
    if (!response2parameter.containsKey(response)) {
        String query = String.format(
                "/xsd:schema/xsd:element[@name='%s']" + "/xsd:complexType/xsd:sequence" + "/xsd:element/@name",
                response);/*w w  w.  ja v  a 2  s.co  m*/
        XPath xpath = DocumentHelper.createXPath(query);
        xpath.setNamespaceURIs(ns2prefix);
        String param = xpath.valueOf(getDocument());
        if (param.isEmpty()) {
            param = null;
        }
        response2parameter.put(response, param);
    }
    return response2parameter.get(response);
}

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 {/*from  w ww . j a  v  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.infoglue.cms.util.dom.DOMBuilder.java

License:Open Source License

/**
 * A helper method to get nodes that has a namespace.
 *//*from ww  w  .j av a 2  s.co  m*/

public Node selectSingleNode(Node contextNode, String xpathExpression, String namespaceName,
        String namespaceValue) {
    Map namespaces = new HashMap();
    namespaces.put(namespaceName, namespaceValue);
    org.dom4j.XPath xpath = contextNode.createXPath(xpathExpression);
    xpath.setNamespaceURIs(namespaces);
    return xpath.selectSingleNode(contextNode);
}

From source file:org.infoglue.igide.editor.IGMultiPageEditor.java

License:Open Source License

/**
 * Saves the multi-page editor's document.
 *//*from  w  w w  . j ava2 s  . co m*/
public void doSave(IProgressMonitor monitor) {
    Logger.logConsole("YES - doSave: " + monitor + ":" + isReloadCMSPushCall);
    saving = true;
    boolean dirtyflag = isDirty();
    Utils.getMonitor(monitor).beginTask("Saving content to CMS", 100);

    for (int i = 0; i < getPageCount(); i++) {
        IEditorPart editor = getEditor(i);
        editor.doSave(monitor);

    }

    Logger.logConsole("Saved each editor part...");
    Utils.getMonitor(monitor).worked(25);
    InfoglueEditorInput input = getInfoglueEditorInput();
    Logger.logConsole("input: " + input);
    input.getContent().doSave(monitor);
    System.out.println("isReloadCMSPushCall: " + isReloadCMSPushCall);
    if (!isReloadCMSPushCall)
        try {
            Logger.logConsole("saveLocalXML called");
            ContentVersion cv = InfoglueCMS.getProjectContentVersion(
                    input.getContent().getNode().getProject().getName(), input.getContent().getNode().getId());

            SAXReader reader = new SAXReader();

            Document document = reader.read(new StringReader(cv.getValue()));
            Map<String, String> namespaceUris = new HashMap<String, String>();
            namespaceUris.put("art", "x-schema:ArticleSchema.xml");

            XPath xPath = DocumentHelper.createXPath("/art:article/art:attributes");
            xPath.setNamespaceURIs(namespaceUris);

            Element attributesNode = (Element) xPath.selectSingleNode(document); //(Element)document.selectSingleNode("/article/attributes");

            @SuppressWarnings("unchecked")
            List<Element> attributes = attributesNode.elements();//document.selectNodes("//attributes/*");

            EditableInfoglueContent content = input.getContent();
            final ArrayList<String> contentAttributes = content.getAttributesOrder();

            Map<String, Element> attributeMap = new HashMap<String, Element>();

            // This loop remove elements from the DOM element
            for (Element attribute : attributes) {
                // DOM4j will shorten empty attributes, which is not good for InfoGlue
                if ("".equals(attribute.getText())) {
                    attribute.clearContent();
                    attribute.addCDATA("");
                }

                if (attributeMap.containsKey(attribute.getName())) {
                    Logger.logConsole("Found duplicate attribute. Removing it. Name: " + attribute.getName());
                    attributesNode.remove(attribute);
                } else {
                    String attributeName = attribute.getName();
                    if (contentAttributes.contains(attributeName)) {
                        attributeMap.put(attributeName, attribute);
                    } else if (!"IGAuthorFullName".equals(attributeName)
                            && !"IGAuthorEmail".equals(attributeName)) {
                        Logger.logConsole(
                                "Found attribute in version that is not in the content type. Removing. Name: "
                                        + attributeName);
                        attributesNode.remove(attribute);
                    }
                }
            }

            // This loop add elements to the DOM element
            for (int i = 0; i < getPageCount(); i++) {
                IEditorPart editor = getEditor(i);
                editor.doSave(monitor);
                IEditorInput editorInput = editor.getEditorInput();
                AttributeEditorInput attributeInput = null;
                if (editorInput instanceof AttributeEditorInput) {
                    attributeInput = (AttributeEditorInput) editorInput;
                    ContentTypeAttribute cta = attributeInput.getAttribute();
                    Element attributeNode = attributeMap.get(cta.getName());
                    if (attributeNode == null) {
                        Logger.logConsole("Found no attribute for editor, name: " + cta.getName());
                        Element attributeElement = attributesNode.addElement(cta.getName());
                        attributeElement.clearContent();
                        attributeElement.addCDATA(cta.getValue());
                    } else {
                        System.out.println("Setting value: " + cta.getValue() + " on node: " + cta.getName());
                        attributeNode.clearContent();
                        attributeNode.addCDATA(cta.getValue());
                    }
                }
            }

            // Sort the attributes
            attributes = (List<Element>) attributesNode.elements();
            Collections.sort(attributes, new Comparator<Element>() {
                @Override
                public int compare(Element element1, Element element2) {
                    int index1 = contentAttributes.indexOf(element1);
                    int index2 = contentAttributes.indexOf(element2);

                    if (index1 != -1 && index2 != -1) {
                        return index1 - index2;
                    } else if (index1 == -1 && index2 != -1) {
                        return 1;
                    } else if (index1 != -1 && index2 == -1) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });

            // Re-set the attributes after manipulation and sorting
            attributesNode.setContent(attributes);

            cv.setValue(document.asXML());

            InfoglueCMS.saveLocalXML(input.getContent().getNode(), cv);
            Logger.logConsole((new StringBuilder("Part in doSave:")).append(cv.getValue().substring(113, 200))
                    .toString());
        } catch (Exception e) {
            Logger.logConsole("Error in saveLocal");
            System.out.println("Exception: " + e.getMessage() + ", class: " + e.getClass());
            e.printStackTrace();
        }
    Utils.getMonitor(monitor).worked(100);
    Utils.getMonitor(monitor).done();
    saving = false;
}

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>/*from w ww  .ja v a  2s. c  om*/
 * 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.//from  w  w  w.  j  av a 2s . 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));
        }
    }
}