Example usage for org.dom4j Element remove

List of usage examples for org.dom4j Element remove

Introduction

In this page you can find the example usage for org.dom4j Element remove.

Prototype

boolean remove(Text text);

Source Link

Document

Removes the given Text if the node is an immediate child of this element.

Usage

From source file:org.infoglue.common.settings.controllers.SettingsController.java

License:Open Source License

public void updateSettings(String nameSpace, String id, Map properties, Session session) throws Exception {
    Document document = getPropertyDocument(nameSpace, session);
    //String xml1 = domBuilder.getFormattedDocument(document, "UTF-8");
    //log.debug("xml1:" + xml1);
    String xpath = "/variations/variation[@id='" + id + "']/setting";
    //String xpath = "/languages/language[@languageCode='" + languageCode +"']/labels";
    //log.debug("xpath:" + xpath);

    Element labelsElement = (Element) document.selectSingleNode(xpath);
    //log.debug("labelsElement:" + labelsElement);

    Iterator keyInterator = properties.keySet().iterator();
    while (keyInterator.hasNext()) {
        String key = (String) keyInterator.next();
        String value = (String) properties.get(key);
        if (!Character.isLetter(key.charAt(0)))
            key = "NP" + key;

        if (key != null && value != null && labelsElement != null) {
            Element labelElement = labelsElement.element(key);
            if (labelElement == null)
                labelElement = domBuilder.addElement(labelsElement, key);

            labelElement.clearContent();

            List elements = labelElement.elements();
            Iterator elementsIterator = elements.iterator();
            while (elementsIterator.hasNext()) {
                Element element = (Element) elementsIterator.next();
                //log.debug("Removing element:" + element.asXML());
                labelElement.remove(element);
            }/* www . ja va2  s  .  c om*/

            domBuilder.addCDATAElement(labelElement, value);
        }
    }

    String xml = domBuilder.getFormattedDocument(document, "UTF-8");
    //log.debug("xml:" + xml);

    labelsPersister.updateProperty(nameSpace, "systemSettings", xml, session);

    CacheController.clearCache(SETTINGSPROPERTIESCACHENAME);
}

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

License:Open Source License

/**
 * Saves the multi-page editor's document.
 *///w w w  .ja  v a  2 s.com
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 w w.jav a 2  s.  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.//w ww  . j a  v a  2s  .  c  om
 * 
 * @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.EscalateDispatcher.java

License:Open Source License

public Document dispatchRequest(Document request) throws InvalidInputFormatException {
    Namespace ns = new Namespace(NS_PREFIX, NS_URI);
    Element rootElement = request.getRootElement();
    userProcessNamespace = rootElement.getNamespaceURI();
    userProcessPrefix = rootElement.getNamespacePrefix();
    List nodes = DocumentHelper.createXPath("//*").selectNodes(request);
    for (int i = 0; i < nodes.size(); ++i) {
        Element element = (Element) nodes.get(i);
        element.remove(element.getNamespaceForURI(userProcessNamespace));
        element.setQName(new QName(element.getName(), ns));
    }/*from  w  w  w  .  j  a v  a 2s  . c o  m*/

    rootElement.setQName(new QName("escalateTaskRequest", ns));
    // TODO: fix this in VC!
    return request;
}

From source file:org.intalio.tempo.workflow.fds.dispatches.EscalateDispatcher.java

License:Open Source License

public Document dispatchResponse(Document response) throws InvalidInputFormatException {
    // TODO: process the TMP response
    Namespace ns = new Namespace(userProcessPrefix, userProcessNamespace);
    response.getRootElement().setName("escalateResponse");
    List nodes = DocumentHelper.createXPath("//*").selectNodes(response);
    for (int i = 0; i < nodes.size(); ++i) {
        Element element = (Element) nodes.get(i);
        element.remove(element.getNamespaceForURI(NS_URI));
        element.setQName(new QName(element.getName(), ns));
    }// w ww  .java  2 s.  c om
    return response;
}

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   ww  w  . j  a  va  2  s  .  c o 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;
}

From source file:org.jage.platform.config.xml.loaders.ArgumentShortcutExtractor.java

License:Open Source License

private void extractConstrPropShortcuts(final Document document) throws ConfigurationException {
    for (final Element element : selectNodes(CONST_PROP, document)) {
        final Attribute valueAttr = element.attribute(ConfigAttributes.VALUE.toString());
        final Attribute typeAttr = element.attribute(ConfigAttributes.TYPE.toString());
        final Attribute refAttr = element.attribute(ConfigAttributes.REF.toString());

        if (bothNotNull(valueAttr, refAttr)) {
            throw new ConfigurationException(
                    element.getUniquePath() + ": Value and ref shortcut attributes can't be both set");
        }//  w ww  .j a  v  a2  s  .  c  om

        if (anyNotNull(valueAttr, refAttr)) {
            if (!element.elements().isEmpty()) {
                throw new ConfigurationException(element.getUniquePath()
                        + ": there can't be both a shortcut attribute and a child definition of some argument");
            }

            if (valueAttr != null) {
                final String value = valueAttr.getValue();
                final String type = typeAttr.getValue();
                element.remove(typeAttr);
                element.remove(valueAttr);
                element.add(newValueElement(type, value));
            } else if (refAttr != null) {
                final String ref = refAttr.getValue();
                element.remove(refAttr);
                element.add(newReferenceElement(ref));
            }
        } else if (element.elements().isEmpty()) {
            throw new ConfigurationException(element.getUniquePath()
                    + ": there must be either a shortcut attribute or a child definition of some argument");
        }
    }
}

From source file:org.jage.platform.config.xml.loaders.ArgumentShortcutExtractor.java

License:Open Source License

@SuppressWarnings("unchecked")
private void extractEntryShortcuts(final Document document) throws ConfigurationException {
    for (final Element element : selectNodes(ENTRIES, document)) {
        final Attribute keyAttr = element.attribute(ConfigAttributes.KEY.toString());
        final Attribute keyRefAttr = element.attribute(ConfigAttributes.KEY_REF.toString());

        if (bothNotNull(keyAttr, keyRefAttr)) {
            throw new ConfigurationException(
                    element.getUniquePath() + ": key and key-ref shortcut attributes can't be both set");
        }/*from  ww w  .  j a  v a2s . c o m*/

        if (anyNotNull(keyAttr, keyRefAttr)) {
            if (!getChildrenIncluding(element, KEY).isEmpty()) {
                throw new ConfigurationException(element.getUniquePath()
                        + ": there can't be both a key shortcut attribute and a child definition of some argument");
            }

            if (keyAttr != null) {
                final String key = keyAttr.getValue();
                element.remove(keyAttr);
                element.elements().add(0, newKeyElement(newValueElement(key)));
            } else if (keyRefAttr != null) {
                final String keyRef = keyRefAttr.getValue();
                element.remove(keyRefAttr);
                element.elements().add(0, newKeyElement(newReferenceElement(keyRef)));
            }
        } else if (getChildrenIncluding(element, KEY).isEmpty()) {
            throw new ConfigurationException(element.getUniquePath()
                    + ": there must be either a key shortcut attribute or a child definition of some argument");
        }

        final Attribute valueAttr = element.attribute(ConfigAttributes.VALUE.toString());
        final Attribute valueRefAttr = element.attribute(ConfigAttributes.VALUE_REF.toString());

        if (bothNotNull(valueAttr, valueRefAttr)) {
            throw new ConfigurationException(
                    element.getUniquePath() + ": value and value-ref shortcut attributes can't be both set");
        }

        if (anyNotNull(valueAttr, valueRefAttr)) {
            if (!getChildrenExcluding(element, KEY).isEmpty()) {
                throw new ConfigurationException(element.getUniquePath()
                        + ": there can't be both a value shortcut attribute and a child definition of some argument");
            }

            if (valueAttr != null) {
                final String value = valueAttr.getValue();
                element.remove(valueAttr);
                element.add(newValueElement(value));
            } else if (valueRefAttr != null) {
                final String valueRef = valueRefAttr.getValue();
                element.remove(valueRefAttr);
                element.add(newReferenceElement(valueRef));
            }
        } else if (getChildrenExcluding(element, KEY).isEmpty()) {
            throw new ConfigurationException(element.getUniquePath()
                    + ": there must be either a value shortcut attribute or a child definition of some argument");
        }
    }
}

From source file:org.jage.platform.config.xml.loaders.IncludingDocumentLoader.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public Document loadDocument(String path) throws ConfigurationException {
    Document document = delegate.loadDocument(path);

    List<Element> includeElements = xPath.selectNodes(document);
    for (Element include : includeElements) {
        String fileAttribute = getRequiredAttribute(include, ConfigAttributes.FILE);

        Document includedDocument = loadDocument(fileAttribute);
        List<Element> includedElements = includedDocument.getRootElement().elements();

        Element indluding = include.getParent();
        List<Element> includingElements = indluding.elements();
        int includeIndex = includingElements.indexOf(include);
        indluding.remove(include);

        for (Element included : consumingIterable(includedElements)) {
            indluding.elements().add(includeIndex, included);
            includeIndex++;//from w  ww .j a v a2s  . c  o  m
        }
    }

    return document;
}