Example usage for org.dom4j Element getNamespace

List of usage examples for org.dom4j Element getNamespace

Introduction

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

Prototype

Namespace getNamespace();

Source Link

Document

Returns the Namespace of this element if one exists otherwise Namespace.NO_NAMESPACE is returned.

Usage

From source file:org.b5chat.crossfire.xmpp.disco.IQDiscoInfoHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) {
    // Create a copy of the sent pack that will be used as the reply
    // we only need to add the requested info to the reply if any otherwise add 
    // a not found error
    IQ reply = IQ.createResultIQ(packet);

    // Look for a IDiscoInfoProvider associated with the requested entity.
    // We consider the host of the recipient JID of the packet as the entity. It's the 
    // IDiscoInfoProvider responsibility to provide information about the JID's name together 
    // with any possible requested node.  
    IDiscoInfoProvider infoProvider = getProvider(
            packet.getTo() == null ? XmppServer.getInstance().getServerInfo().getXMPPDomain()
                    : packet.getTo().getDomain());
    if (infoProvider != null) {
        // Get the JID's name
        String name = packet.getTo() == null ? null : packet.getTo().getNode();
        if (name == null || name.trim().length() == 0) {
            name = null;/*w w  w  . j a  v  a 2 s . c o m*/
        }
        // Get the requested node
        Element iq = packet.getChildElement();
        String node = iq.attributeValue("node");
        //String node = metaData.getProperty("query:node");

        // Check if we have information about the requested name and node
        if (infoProvider.hasInfo(name, node, packet.getFrom())) {
            reply.setChildElement(iq.createCopy());
            Element queryElement = reply.getChildElement();

            // Add to the reply all the identities provided by the IDiscoInfoProvider
            Element identity;
            Iterator<Element> identities = infoProvider.getIdentities(name, node, packet.getFrom());
            while (identities.hasNext()) {
                identity = identities.next();
                identity.setQName(new QName(identity.getName(), queryElement.getNamespace()));
                queryElement.add((Element) identity.clone());
            }

            // Add to the reply all the features provided by the IDiscoInfoProvider
            Iterator<String> features = infoProvider.getFeatures(name, node, packet.getFrom());
            boolean hasDiscoInfoFeature = false;
            boolean hasDiscoItemsFeature = false;
            boolean hasResultSetManagementFeature = false;

            while (features.hasNext()) {
                final String feature = features.next();
                queryElement.addElement("feature").addAttribute("var", feature);
                if (feature.equals(NAMESPACE_DISCO_INFO)) {
                    hasDiscoInfoFeature = true;
                } else if (feature.equals("http://jabber.org/protocol/disco#items")) {
                    hasDiscoItemsFeature = true;
                } else if (feature.equals(ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)) {
                    hasResultSetManagementFeature = true;
                }
            }

            if (hasDiscoItemsFeature && !hasResultSetManagementFeature) {
                // IQDiscoItemsHandler provides result set management
                // support.
                queryElement.addElement("feature").addAttribute("var",
                        ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT);
            }

            if (!hasDiscoInfoFeature) {
                // XEP-0030 requires that every entity that supports service
                // discovery broadcasts the disco#info feature.
                queryElement.addElement("feature").addAttribute("var", NAMESPACE_DISCO_INFO);
            }

            // Add to the reply the extended info (XDataForm) provided by the IDiscoInfoProvider
            DataForm dataForm = infoProvider.getExtendedInfo(name, node, packet.getFrom());
            if (dataForm != null) {
                queryElement.add(dataForm.getElement());
            }
        } else {
            // If the IDiscoInfoProvider has no information for the requested name and node 
            // then answer a not found error
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.item_not_found);
        }
    } else {
        // If we didn't find a IDiscoInfoProvider then answer a not found error
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.item_not_found);
    }

    return reply;
}

From source file:org.b5chat.crossfire.xmpp.disco.IQDiscoItemsHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) {
    // Create a copy of the sent pack that will be used as the reply
    // we only need to add the requested items to the reply if any otherwise add 
    // a not found error
    IQ reply = IQ.createResultIQ(packet);

    // TODO Implement publishing client items
    if (IQ.Type.set == packet.getType()) {
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.feature_not_implemented);
        return reply;
    }//from  w  w w.  j  a  v a 2 s.  co  m

    // Look for a IDiscoItemsProvider associated with the requested entity.
    // We consider the host of the recipient JID of the packet as the entity. It's the 
    // IDiscoItemsProvider responsibility to provide the items associated with the JID's name  
    // together with any possible requested node.
    IDiscoItemsProvider itemsProvider = getProvider(
            packet.getTo() == null ? XmppServer.getInstance().getServerInfo().getXMPPDomain()
                    : packet.getTo().getDomain());
    if (itemsProvider != null) {
        // Get the JID's name
        String name = packet.getTo() == null ? null : packet.getTo().getNode();
        if (name == null || name.trim().length() == 0) {
            name = null;
        }
        // Get the requested node
        Element iq = packet.getChildElement();
        String node = iq.attributeValue("node");

        // Check if we have items associated with the requested name and node
        Iterator<DiscoItem> itemsItr = itemsProvider.getItems(name, node, packet.getFrom());
        if (itemsItr != null) {
            reply.setChildElement(iq.createCopy());
            Element queryElement = reply.getChildElement();

            // See if the requesting entity would like to apply 'result set
            // management'
            final Element rsmElement = packet.getChildElement()
                    .element(QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));

            // apply RSM only if the element exists, and the (total) results
            // set is not empty.
            final boolean applyRSM = rsmElement != null && itemsItr.hasNext();

            if (applyRSM) {
                if (!ResultSet.isValidRSMRequest(rsmElement)) {
                    reply.setError(PacketError.Condition.bad_request);
                    return reply;
                }

                // Calculate which results to include.
                final List<DiscoItem> rsmResults;
                final List<DiscoItem> allItems = new ArrayList<DiscoItem>();
                while (itemsItr.hasNext()) {
                    allItems.add(itemsItr.next());
                }
                final ResultSet<DiscoItem> rs = new ResultSetImpl<DiscoItem>(allItems);
                try {
                    rsmResults = rs.applyRSMDirectives(rsmElement);
                } catch (NullPointerException e) {
                    final IQ itemNotFound = IQ.createResultIQ(packet);
                    itemNotFound.setError(PacketError.Condition.item_not_found);
                    return itemNotFound;
                }

                // add the applicable results to the IQ-result
                for (DiscoItem item : rsmResults) {
                    final Element resultElement = item.getElement();
                    resultElement.setQName(new QName(resultElement.getName(), queryElement.getNamespace()));
                    queryElement.add(resultElement.createCopy());
                }

                // overwrite the 'set' element.
                queryElement.remove(
                        queryElement.element(QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)));
                queryElement.add(rs.generateSetElementFromResults(rsmResults));
            } else {
                // don't apply RSM:
                // Add to the reply all the items provided by the IDiscoItemsProvider
                Element item;
                while (itemsItr.hasNext()) {
                    item = itemsItr.next().getElement();
                    item.setQName(new QName(item.getName(), queryElement.getNamespace()));
                    queryElement.add(item.createCopy());
                }
            }
        } else {
            // If the IDiscoItemsProvider has no items for the requested name and node 
            // then answer a not found error
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.item_not_found);
        }
    } else {
        // If we didn't find a IDiscoItemsProvider then answer a not found error
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.item_not_found);
    }

    return reply;
}

From source file:org.codehaus.cargo.util.Dom4JXmlFileBuilder.java

License:Apache License

/**
 * @param element to traverse and change namespace of
 * @param parent - who to match namespaces with.
 *//*from   ww w .  j  av  a  2s.  c om*/
private void setNamespaceOfElementToTheSameAsParent(Element element, Element parent) {
    final Namespace namespaceOfParent = parent.getNamespace();
    element.accept(new VisitorSupport() {
        @Override
        public void visit(Element node) {
            QName nameOfElementWithCorrectNamespace = new QName(node.getName(), namespaceOfParent);
            node.setQName(nameOfElementWithCorrectNamespace);
        }
    });
}

From source file:org.danann.cernunnos.xml.NodeProcessor.java

License:Apache License

/**
 * Recursively applies the specified <code>Namespace</code> to the specified
 * <code>Element</code>, unless the <code>Element</code> (or any child
 * <code>Element</code>) already specifies a <code>Namespace</code>.
 *
 * @param nsp Namespace to apply.//w w  w . j  ava 2 s  .  co m
 * @param e XML structure upon which to apply the Namespace.
 */
public static void applyNamespace(Namespace nsp, Element e) {

    // Assertions...
    if (nsp == null) {
        String msg = "Argument 'nsp' cannot be null.";
        throw new IllegalArgumentException(msg);
    }
    if (e == null) {
        String msg = "Argument 'e [Element]' cannot be null.";
        throw new IllegalArgumentException(msg);
    }

    if (e.getNamespace().equals(Namespace.NO_NAMESPACE)) {
        e.setQName(new QName(e.getName(), nsp));
        for (Object n : e.elements()) {
            applyNamespace(nsp, (Element) n);
        }
    }

}

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 . j a v 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 .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));
        }
    }
}

From source file:org.jamppa.component.XMPPComponent.java

License:Apache License

private IQ handle(IQ iq, Map<String, QueryHandler> handlers) {
    Element queryElement = iq.getElement().element("query");
    if (queryElement == null) {
        return XMPPUtils.error(iq, "IQ does not contain query element.", LOGGER);
    }// w  ww. j  a va2  s . co  m

    Namespace namespace = queryElement.getNamespace();

    QueryHandler queryHandler = handlers.get(namespace.getURI());
    if (queryHandler == null) {
        return XMPPUtils.error(iq, "QueryHandler not found for namespace: " + namespace, LOGGER);
    }

    return queryHandler.handle(iq);
}

From source file:org.jboss.seam.init.Initialization.java

License:LGPL

@SuppressWarnings("unchecked")
private void installComponentsFromXmlElements(Element rootElement, Properties replacements)
        throws DocumentException, ClassNotFoundException {
    /*List<Element> importJavaElements = rootElement.elements("import-java-package");
      for (Element importElement : importJavaElements)
      {//from w w  w .j a va2 s  .com
    String pkgName = importElement.getTextTrim();
    importedPackages.add(pkgName);
    addNamespace( Package.getPackage(pkgName) );
      }*/

    for (Element importElement : elements(rootElement, "import")) {
        globalImports.add(importElement.getTextTrim());
    }

    for (Element component : elements(rootElement, "component")) {
        installComponentFromXmlElement(component, component.attributeValue("name"),
                component.attributeValue("class"), replacements);
    }

    for (Element factory : elements(rootElement, "factory")) {
        installFactoryFromXmlElement(factory);
    }

    for (Element event : elements(rootElement, "event")) {
        installEventListenerFromXmlElement(event);
    }

    for (Element elem : (List<Element>) rootElement.elements()) {
        String ns = elem.getNamespace().getURI();
        NamespaceDescriptor nsInfo = resolveNamespace(ns);
        if (nsInfo == null) {
            if (!ns.equals(COMPONENT_NAMESPACE)) {
                log.warn("namespace declared in components.xml does not resolve to a package: " + ns);
            }
        } else {
            String name = elem.attributeValue("name");
            String elemName = toCamelCase(elem.getName(), true);

            String className = elem.attributeValue("class");
            if (className == null) {
                for (String packageName : nsInfo.getPackageNames()) {
                    try {
                        // Try each of the packages in the namespace descriptor for a matching class
                        className = packageName + '.' + elemName;
                        Reflections.classForName(className);
                        break;
                    } catch (ClassNotFoundException ex) {
                        className = null;
                    }
                }
            }

            try {
                //get the class implied by the namespaced XML element name
                Class<Object> clazz = Reflections.classForName(className);
                Name nameAnnotation = clazz.getAnnotation(Name.class);

                //if the name attribute is not explicitly specified in the XML,
                //imply the name from the @Name annotation on the class implied
                //by the XML element name
                if (name == null && nameAnnotation != null) {
                    name = nameAnnotation.value();
                }

                //if this class already has the @Name annotation, the XML element 
                //is just adding configuration to the existing component, don't
                //add another ComponentDescriptor (this is super-important to
                //allow overriding!)
                if (nameAnnotation != null && nameAnnotation.value().equals(name)) {
                    Install install = clazz.getAnnotation(Install.class);
                    if (install == null || install.value()) {
                        className = null;
                    }
                }
            } catch (ClassNotFoundException cnfe) {
                //there is no class implied by the XML element name so the
                //component must be defined some other way, assume that we are
                //just adding configuration, don't add a ComponentDescriptor 
                //TODO: this is problematic, it results in elements getting 
                //      ignored when mis-spelled or given the wrong namespace!!
                className = null;
            } catch (Exception e) {
                throw new RuntimeException("Error loading element " + elemName + " with component name " + name
                        + " and component class " + className);
            }

            //finally, if we could not get the name from the XML name attribute,
            //or from an @Name annotation on the class, imply it
            if (name == null) {
                String prefix = nsInfo.getComponentPrefix();
                String componentName = toCamelCase(elem.getName(), false);
                name = Strings.isEmpty(prefix) ? componentName : prefix + '.' + componentName;
            }

            installComponentFromXmlElement(elem, name, className, replacements);
        }
    }
}

From source file:org.jivesoftware.openfire.disco.IQDiscoInfoHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) {
    // Create a copy of the sent pack that will be used as the reply
    // we only need to add the requested info to the reply if any otherwise add 
    // a not found error
    IQ reply = IQ.createResultIQ(packet);

    // Look for a DiscoInfoProvider associated with the requested entity.
    // We consider the host of the recipient JID of the packet as the entity. It's the 
    // DiscoInfoProvider responsibility to provide information about the JID's name together 
    // with any possible requested node.  
    DiscoInfoProvider infoProvider = getProvider(
            packet.getTo() == null ? XMPPServer.getInstance().getServerInfo().getXMPPDomain()
                    : packet.getTo().getDomain());
    if (infoProvider != null) {
        // Get the JID's name
        String name = packet.getTo() == null ? null : packet.getTo().getNode();
        if (name == null || name.trim().length() == 0) {
            name = null;//from ww w  .  j a v  a2s.  c  o m
        }
        // Get the requested node
        Element iq = packet.getChildElement();
        String node = iq.attributeValue("node");
        //String node = metaData.getProperty("query:node");

        // Check if we have information about the requested name and node
        if (infoProvider.hasInfo(name, node, packet.getFrom())) {
            reply.setChildElement(iq.createCopy());
            Element queryElement = reply.getChildElement();

            // Add to the reply all the identities provided by the DiscoInfoProvider
            Element identity;
            Iterator<Element> identities = infoProvider.getIdentities(name, node, packet.getFrom());
            while (identities.hasNext()) {
                identity = identities.next();
                identity.setQName(new QName(identity.getName(), queryElement.getNamespace()));
                queryElement.add((Element) identity.clone());
            }

            // Add to the reply all the features provided by the DiscoInfoProvider
            Iterator<String> features = infoProvider.getFeatures(name, node, packet.getFrom());
            boolean hasDiscoInfoFeature = false;
            boolean hasDiscoItemsFeature = false;
            boolean hasResultSetManagementFeature = false;

            while (features.hasNext()) {
                final String feature = features.next();
                queryElement.addElement("feature").addAttribute("var", feature);
                if (feature.equals(NAMESPACE_DISCO_INFO)) {
                    hasDiscoInfoFeature = true;
                } else if (feature.equals("http://jabber.org/protocol/disco#items")) {
                    hasDiscoItemsFeature = true;
                } else if (feature.equals(ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)) {
                    hasResultSetManagementFeature = true;
                }
            }

            if (hasDiscoItemsFeature && !hasResultSetManagementFeature) {
                // IQDiscoItemsHandler provides result set management
                // support.
                queryElement.addElement("feature").addAttribute("var",
                        ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT);
            }

            if (!hasDiscoInfoFeature) {
                // XEP-0030 requires that every entity that supports service
                // discovery broadcasts the disco#info feature.
                queryElement.addElement("feature").addAttribute("var", NAMESPACE_DISCO_INFO);
            }

            // Add to the reply the extended info (XDataForm) provided by the DiscoInfoProvider
            DataForm dataForm = infoProvider.getExtendedInfo(name, node, packet.getFrom());
            if (dataForm != null) {
                queryElement.add(dataForm.getElement());
            }
        } else {
            // If the DiscoInfoProvider has no information for the requested name and node 
            // then answer a not found error
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.item_not_found);
        }
    } else {
        // If we didn't find a DiscoInfoProvider then answer a not found error
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.item_not_found);
    }

    return reply;
}

From source file:org.jivesoftware.openfire.disco.IQDiscoItemsHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) {
    // Create a copy of the sent pack that will be used as the reply
    // we only need to add the requested items to the reply if any otherwise add 
    // a not found error
    IQ reply = IQ.createResultIQ(packet);

    // TODO Implement publishing client items
    if (IQ.Type.set == packet.getType()) {
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.feature_not_implemented);
        return reply;
    }/*from  w  ww  .j a va 2  s .  co m*/

    // Look for a DiscoItemsProvider associated with the requested entity.
    // We consider the host of the recipient JID of the packet as the entity. It's the 
    // DiscoItemsProvider responsibility to provide the items associated with the JID's name  
    // together with any possible requested node.
    DiscoItemsProvider itemsProvider = getProvider(
            packet.getTo() == null ? XMPPServer.getInstance().getServerInfo().getXMPPDomain()
                    : packet.getTo().getDomain());
    if (itemsProvider != null) {
        // Get the JID's name
        String name = packet.getTo() == null ? null : packet.getTo().getNode();
        if (name == null || name.trim().length() == 0) {
            name = null;
        }
        // Get the requested node
        Element iq = packet.getChildElement();
        String node = iq.attributeValue("node");

        // Check if we have items associated with the requested name and node
        Iterator<DiscoItem> itemsItr = itemsProvider.getItems(name, node, packet.getFrom());
        if (itemsItr != null) {
            reply.setChildElement(iq.createCopy());
            Element queryElement = reply.getChildElement();

            // See if the requesting entity would like to apply 'result set
            // management'
            final Element rsmElement = packet.getChildElement()
                    .element(QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));

            // apply RSM only if the element exists, and the (total) results
            // set is not empty.
            final boolean applyRSM = rsmElement != null && itemsItr.hasNext();

            if (applyRSM) {
                if (!ResultSet.isValidRSMRequest(rsmElement)) {
                    reply.setError(PacketError.Condition.bad_request);
                    return reply;
                }

                // Calculate which results to include.
                final List<DiscoItem> rsmResults;
                final List<DiscoItem> allItems = new ArrayList<DiscoItem>();
                while (itemsItr.hasNext()) {
                    allItems.add(itemsItr.next());
                }
                final ResultSet<DiscoItem> rs = new ResultSetImpl<DiscoItem>(allItems);
                try {
                    rsmResults = rs.applyRSMDirectives(rsmElement);
                } catch (NullPointerException e) {
                    final IQ itemNotFound = IQ.createResultIQ(packet);
                    itemNotFound.setError(PacketError.Condition.item_not_found);
                    return itemNotFound;
                }

                // add the applicable results to the IQ-result
                for (DiscoItem item : rsmResults) {
                    final Element resultElement = item.getElement();
                    resultElement.setQName(new QName(resultElement.getName(), queryElement.getNamespace()));
                    queryElement.add(resultElement.createCopy());
                }

                // overwrite the 'set' element.
                queryElement.remove(
                        queryElement.element(QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)));
                queryElement.add(rs.generateSetElementFromResults(rsmResults));
            } else {
                // don't apply RSM:
                // Add to the reply all the items provided by the DiscoItemsProvider
                Element item;
                while (itemsItr.hasNext()) {
                    item = itemsItr.next().getElement();
                    item.setQName(new QName(item.getName(), queryElement.getNamespace()));
                    queryElement.add(item.createCopy());
                }
            }
        } else {
            // If the DiscoItemsProvider has no items for the requested name and node 
            // then answer a not found error
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.item_not_found);
        }
    } else {
        // If we didn't find a DiscoItemsProvider then answer a not found error
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.item_not_found);
    }

    return reply;
}