Example usage for org.dom4j QName get

List of usage examples for org.dom4j QName get

Introduction

In this page you can find the example usage for org.dom4j QName get.

Prototype

public static QName get(String qualifiedName, String uri) 

Source Link

Usage

From source file:org.jivesoftware.openfire.pubsub.PubSubEngine.java

License:Open Source License

/**
 * Checks if the following conditions are satisfied and creates a node
 * - Requester can create nodes/* ww w .  j  a  va 2  s.c o  m*/
 * - Instant node creation is enabled
 * - Node does not already exist
 * - New node configuration is valid
 *
 * NOTE: This method should not reply to the client
 *
 * @param service
 * @param iq
 * @param childElement
 * @param createElement
 * @return
 */
private CreateNodeResponse createNodeHelper(PubSubService service, IQ iq, Element childElement,
        Element createElement) {
    // Get sender of the IQ packet
    JID from = iq.getFrom();
    // Verify that sender has permissions to create nodes
    if (!service.canCreateNode(from)
            || (!UserManager.getInstance().isRegisteredUser(from) && !isComponent(from))) {
        // The user is not allowed to create nodes so return an error
        return new CreateNodeResponse(PacketError.Condition.forbidden, null, null);
    }
    DataForm completedForm = null;
    CollectionNode parentNode = null;
    String nodeID = createElement.attributeValue("node");
    String newNodeID = nodeID;
    if (nodeID == null) {
        // User requested an instant node
        if (!service.isInstantNodeSupported()) {
            // Instant nodes creation is not allowed so return an error
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("nodeid-required", "http://jabber.org/protocol/pubsub#errors"));
            return new CreateNodeResponse(PacketError.Condition.not_acceptable, pubsubError, null);
        }
        do {
            // Create a new nodeID and make sure that the random generated string does not
            // match an existing node. Probability to match an existing node are very very low
            // but they exist :)
            newNodeID = StringUtils.randomString(15);
        } while (service.getNode(newNodeID) != null);
    }
    boolean collectionType = false;
    // Check if user requested to configure the node (using a data form)
    Element configureElement = childElement.element("configure");
    if (configureElement != null) {
        // Get the data form that contains the parent nodeID
        completedForm = getSentConfigurationForm(configureElement);
        if (completedForm != null) {
            // Calculate newNodeID when new node is affiliated with a Collection
            FormField field = completedForm.getField("pubsub#collection");
            if (field != null) {
                List<String> values = field.getValues();
                if (!values.isEmpty()) {
                    String parentNodeID = values.get(0);
                    Node tempNode = service.getNode(parentNodeID);
                    if (tempNode == null) {
                        // Requested parent node was not found so return an error
                        return new CreateNodeResponse(PacketError.Condition.item_not_found, null, null);
                    } else if (!tempNode.isCollectionNode()) {
                        // Requested parent node is not a collection node so return an error
                        return new CreateNodeResponse(PacketError.Condition.not_acceptable, null, null);
                    }
                    parentNode = (CollectionNode) tempNode;
                }
            }
            field = completedForm.getField("pubsub#node_type");
            if (field != null) {
                // Check if user requested to create a new collection node
                List<String> values = field.getValues();
                if (!values.isEmpty()) {
                    collectionType = "collection".equals(values.get(0));
                }
            }
        }
    }
    // If no parent was defined then use the root collection node
    if (parentNode == null && service.isCollectionNodesSupported()) {
        parentNode = service.getRootCollectionNode();
    }
    // Check that the requested nodeID does not exist
    Node existingNode = service.getNode(newNodeID);
    if (existingNode != null) {
        // There is a conflict since a node with the same ID already exists
        return new CreateNodeResponse(PacketError.Condition.conflict, null, null);
    }

    if (collectionType && !service.isCollectionNodesSupported()) {
        // Cannot create a collection node since the service doesn't support it
        Element pubsubError = DocumentHelper
                .createElement(QName.get("unsupported", "http://jabber.org/protocol/pubsub#errors"));
        pubsubError.addAttribute("feature", "collections");
        return new CreateNodeResponse(PacketError.Condition.feature_not_implemented, pubsubError, null);
    }

    if (parentNode != null && !collectionType) {
        // Check if requester is allowed to add a new leaf child node to the parent node
        if (!parentNode.isAssociationAllowed(from)) {
            // User is not allowed to add child leaf node to parent node. Return an error.
            return new CreateNodeResponse(PacketError.Condition.forbidden, null, null);
        }
        // Check if number of child leaf nodes has not been exceeded
        if (parentNode.isMaxLeafNodeReached()) {
            // Max number of child leaf nodes has been reached. Return an error.
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("max-nodes-exceeded", "http://jabber.org/protocol/pubsub#errors"));
            return new CreateNodeResponse(PacketError.Condition.conflict, pubsubError, null);
        }
    }

    // Create and configure the node
    boolean conflict = false;
    Node newNode = null;
    try {
        // TODO Assumed that the owner of the subscription is the bare JID of the subscription JID. Waiting StPeter answer for explicit field.
        JID owner = from.asBareJID();
        synchronized (newNodeID.intern()) {
            if (service.getNode(newNodeID) == null) {
                // Create the node
                if (collectionType) {
                    newNode = new CollectionNode(service, parentNode, newNodeID, from);
                } else {
                    newNode = new LeafNode(service, parentNode, newNodeID, from);
                }
                // Add the creator as the node owner
                newNode.addOwner(owner);
                // Configure and save the node to the backend store
                if (completedForm != null) {
                    newNode.configure(completedForm);
                } else {
                    newNode.saveToDB();
                }

                CacheFactory.doClusterTask(new RefreshNodeTask(newNode));
            } else {
                conflict = true;
            }
        }
        if (conflict) {
            // There is a conflict since a node with the same ID already exists
            return new CreateNodeResponse(PacketError.Condition.conflict, null, null);
        } else {
            // Return success to the node owner
            return new CreateNodeResponse(null, null, newNode);
        }
    } catch (NotAcceptableException e) {
        // Node should have at least one owner. Return not-acceptable error.
        return new CreateNodeResponse(PacketError.Condition.not_acceptable, null, null);
    }
}

From source file:org.jivesoftware.openfire.pubsub.PubSubEngine.java

License:Open Source License

private void getDefaultNodeConfiguration(PubSubService service, IQ iq, Element childElement,
        Element defaultElement) {
    String type = defaultElement.attributeValue("type");
    type = type == null ? "leaf" : type;

    boolean isLeafType = "leaf".equals(type);
    DefaultNodeConfiguration config = service.getDefaultNodeConfiguration(isLeafType);
    if (config == null) {
        // Service does not support the requested node type so return an error
        Element pubsubError = DocumentHelper
                .createElement(QName.get("unsupported", "http://jabber.org/protocol/pubsub#errors"));
        pubsubError.addAttribute("feature", isLeafType ? "leaf" : "collections");
        sendErrorPacket(iq, PacketError.Condition.feature_not_implemented, pubsubError);
        return;/*from w w  w  .jav a2s . c o  m*/
    }

    // Return data form containing default node configuration
    IQ reply = IQ.createResultIQ(iq);
    Element replyChildElement = childElement.createCopy();
    reply.setChildElement(replyChildElement);
    replyChildElement.element("default").add(config.getConfigurationForm().getElement());
    router.route(reply);
}

From source file:org.jivesoftware.openfire.pubsub.PubSubEngine.java

License:Open Source License

private void purgeNode(PubSubService service, IQ iq, Element purgeElement) {
    String nodeID = purgeElement.attributeValue("node");
    if (nodeID == null) {
        // NodeID was not provided. Return bad-request error
        sendErrorPacket(iq, PacketError.Condition.bad_request, null);
        return;//  www . j a v  a  2 s.co  m
    }
    Node node = service.getNode(nodeID);
    if (node == null) {
        // Node does not exist. Return item-not-found error
        sendErrorPacket(iq, PacketError.Condition.item_not_found, null);
        return;
    }
    if (!node.isAdmin(iq.getFrom())) {
        // Requesting entity is prohibited from configuring this node. Return forbidden error
        sendErrorPacket(iq, PacketError.Condition.forbidden, null);
        return;
    }
    if (!((LeafNode) node).isPersistPublishedItems()) {
        // Node does not persist items. Return feature-not-implemented error
        Element pubsubError = DocumentHelper
                .createElement(QName.get("unsupported", "http://jabber.org/protocol/pubsub#errors"));
        pubsubError.addAttribute("feature", "persistent-items");
        sendErrorPacket(iq, PacketError.Condition.feature_not_implemented, pubsubError);
        return;
    }
    if (node.isCollectionNode()) {
        // Node is a collection node. Return feature-not-implemented error
        Element pubsubError = DocumentHelper
                .createElement(QName.get("unsupported", "http://jabber.org/protocol/pubsub#errors"));
        pubsubError.addAttribute("feature", "purge-nodes");
        sendErrorPacket(iq, PacketError.Condition.feature_not_implemented, pubsubError);
        return;
    }

    // Purge the node
    ((LeafNode) node).purge();
    // Return that node purged successfully
    router.route(IQ.createResultIQ(iq));
}

From source file:org.jivesoftware.openfire.pubsub.PubSubEngine.java

License:Open Source License

/**
 * Returns the data form included in the configure element sent by the node owner or
 * <tt>null</tt> if none was included or access model was defined. If the
 * owner just wants to set the access model to use for the node and optionally set the
 * list of roster groups (i.e. contacts present in the node owner roster in the
 * specified groups are allowed to access the node) allowed to access the node then
 * instead of including a data form the owner can just specify the "access" attribute
 * of the configure element and optionally include a list of group elements. In this case,
 * the method will create a data form including the specified data. This is a nice way
 * to accept both ways to configure a node but always returning a data form.
 *
 * @param configureElement the configure element sent by the owner.
 * @return the data form included in the configure element sent by the node owner or
 *         <tt>null</tt> if none was included or access model was defined.
 *///w  w  w.jav a2 s .c  o m
private DataForm getSentConfigurationForm(Element configureElement) {
    DataForm completedForm = null;
    FormField formField;
    Element formElement = configureElement.element(QName.get("x", "jabber:x:data"));
    if (formElement != null) {
        completedForm = new DataForm(formElement);
    }
    String accessModel = configureElement.attributeValue("access");
    if (accessModel != null) {
        if (completedForm == null) {
            // Create a form (i.e. simulate that the user sent a form with roster groups)
            completedForm = new DataForm(DataForm.Type.submit);
            // Add the hidden field indicating that this is a node config form
            formField = completedForm.addField();
            formField.setVariable("FORM_TYPE");
            formField.setType(FormField.Type.hidden);
            formField.addValue("http://jabber.org/protocol/pubsub#node_config");
        }
        if (completedForm.getField("pubsub#access_model") == null) {
            // Add the field that will specify the access model of the node
            formField = completedForm.addField();
            formField.setVariable("pubsub#access_model");
            formField.addValue(accessModel);
        } else {
            Log.debug("PubSubEngine: Owner sent access model in data form and as attribute: "
                    + configureElement.asXML());
        }
        // Check if a list of groups was specified
        List groups = configureElement.elements("group");
        if (!groups.isEmpty()) {
            // Add the field that will contain the specified groups
            formField = completedForm.addField();
            formField.setVariable("pubsub#roster_groups_allowed");
            // Add each group as a value of the groups field
            for (Iterator it = groups.iterator(); it.hasNext();) {
                formField.addValue(((Element) it.next()).getTextTrim());
            }
        }
    }
    return completedForm;
}

From source file:org.jivesoftware.openfire.spi.RoutingTableImpl.java

License:Open Source License

/**
 * Routes packets that are sent to the XMPP domain itself (excluding subdomains).
 * //from w ww  . j  a va  2 s.  com
 * @param jid
 *            the recipient of the packet to route.
 * @param packet
 *            the packet to route.
 * @param fromServer
 *            true if the packet was created by the server. This packets
 *            should always be delivered
 * @throws PacketException
 *             thrown if the packet is malformed (results in the sender's
 *             session being shutdown).
 * @return <tt>true</tt> if the packet was routed successfully,
 *         <tt>false</tt> otherwise.
 */
private boolean routeToLocalDomain(JID jid, Packet packet, boolean fromServer) {
    boolean routed = false;
    Element privateElement = packet.getElement().element(QName.get("private", "urn:xmpp:carbons:2"));
    boolean isPrivate = privateElement != null;
    // The receiving server and SHOULD remove the <private/> element before delivering to the recipient.
    packet.getElement().remove(privateElement);

    if (jid.getResource() == null) {
        // Packet sent to a bare JID of a user
        if (packet instanceof Message) {
            // Find best route of local user
            routed = routeToBareJID(jid, (Message) packet, isPrivate);
        } else {
            throw new PacketException(
                    "Cannot route packet of type IQ or Presence to bare JID: " + packet.toXML());
        }
    } else {
        // Packet sent to local user (full JID)
        ClientRoute clientRoute = usersCache.get(jid.toString());
        if (clientRoute == null) {
            clientRoute = anonymousUsersCache.get(jid.toString());
        }
        if (clientRoute != null) {
            if (!clientRoute.isAvailable() && routeOnlyAvailable(packet, fromServer)
                    && !presenceUpdateHandler.hasDirectPresence(packet.getTo(), packet.getFrom())) {
                Log.debug(
                        "Unable to route packet. Packet should only be sent to available sessions and the route is not available. {} ",
                        packet.toXML());
                routed = false;
            } else {
                if (localRoutingTable.isLocalRoute(jid)) {
                    if (packet instanceof Message) {
                        Message message = (Message) packet;
                        if (message.getType() == Message.Type.chat && !isPrivate) {
                            List<JID> routes = getRoutes(jid.asBareJID(), null);
                            for (JID route : routes) {
                                // The receiving server MUST NOT send a forwarded copy to the full JID the original <message/> stanza was addressed to, as that recipient receives the original <message/> stanza.
                                if (!route.equals(jid)) {
                                    ClientSession clientSession = getClientRoute(route);
                                    if (clientSession.isMessageCarbonsEnabled()) {
                                        Message carbon = new Message();
                                        // The wrapping message SHOULD maintain the same 'type' attribute value;
                                        carbon.setType(message.getType());
                                        // the 'from' attribute MUST be the Carbons-enabled user's bare JID
                                        carbon.setFrom(route.asBareJID());
                                        // and the 'to' attribute MUST be the full JID of the resource receiving the copy
                                        carbon.setTo(route);
                                        // The content of the wrapping message MUST contain a <received/> element qualified by the namespace "urn:xmpp:carbons:2", which itself contains a <forwarded/> element qualified by the namespace "urn:xmpp:forward:0" that contains the original <message/>.
                                        carbon.addExtension(new Received(new Forwarded(message)));

                                        try {
                                            localRoutingTable.getRoute(route.toString()).process(carbon);
                                        } catch (UnauthorizedException e) {
                                            Log.error("Unable to route packet " + packet.toXML(), e);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // This is a route to a local user hosted in this node
                    try {
                        localRoutingTable.getRoute(jid.toString()).process(packet);
                        routed = true;
                    } catch (UnauthorizedException e) {
                        Log.error("Unable to route packet " + packet.toXML(), e);
                    }
                } else {
                    // This is a route to a local user hosted in other node
                    if (remotePacketRouter != null) {
                        routed = remotePacketRouter.routePacket(clientRoute.getNodeID().toByteArray(), jid,
                                packet);
                        if (!routed) {
                            removeClientRoute(jid); // drop invalid client route
                        }
                    }
                }
            }
        }
    }
    return routed;
}

From source file:org.jivesoftware.openfire.websocket.XmppWebSocket.java

License:Open Source License

private void processStanza(Element stanza) {

    try {// w  w  w  . j av  a 2  s  .  c o m
        String tag = stanza.getName();
        if (STREAM_FOOTER.equals(tag)) {
            closeStream(null);
        } else if ("auth".equals(tag)) {
            // User is trying to authenticate using SASL
            startedSASL = true;
            // Process authentication stanza
            xmppSession.incrementClientPacketCount();
            saslStatus = SASLAuthentication.handle(xmppSession, stanza);
        } else if (startedSASL && "response".equals(tag) || "abort".equals(tag)) {
            // User is responding to SASL challenge. Process response
            xmppSession.incrementClientPacketCount();
            saslStatus = SASLAuthentication.handle(xmppSession, stanza);
        } else if (STREAM_HEADER.equals(tag)) {
            // restart the stream
            openStream(stanza.attributeValue(QName.get("lang", XMLConstants.XML_NS_URI), "en"),
                    stanza.attributeValue("from"));
            configureStream();
        } else if (Status.authenticated.equals(saslStatus)) {
            if (router == null) {
                if (isStreamManagementAvailable()) {
                    router = new StreamManagementPacketRouter(xmppSession);
                } else {
                    // fall back for older Openfire installations
                    router = new SessionPacketRouter(xmppSession);
                }
            }
            router.route(stanza);
        } else {
            // require authentication
            Log.warn("Not authorized: " + stanza.asXML());
            sendPacketError(stanza, PacketError.Condition.not_authorized);
        }
    } catch (UnknownStanzaException use) {
        Log.warn("Received invalid stanza: " + stanza.asXML());
        sendPacketError(stanza, PacketError.Condition.bad_request);
    } catch (Exception ex) {
        Log.error("Failed to process incoming stanza: " + stanza.asXML(), ex);
        closeStream(new StreamError(StreamError.Condition.internal_server_error));
    }
}

From source file:org.jivesoftware.openfire.websocket.XmppWebSocket.java

License:Open Source License

private void initiateSession(Element stanza) {

    String host = stanza.attributeValue("to");
    StreamError streamError = null;/*  w  w  w.java 2  s.  co  m*/
    Locale language = Locale
            .forLanguageTag(stanza.attributeValue(QName.get("lang", XMLConstants.XML_NS_URI), "en"));
    if (STREAM_FOOTER.equals(stanza.getName())) {
        // an error occurred while setting up the session
        Log.warn("Client closed stream before session was established");
    } else if (!STREAM_HEADER.equals(stanza.getName())) {
        streamError = new StreamError(StreamError.Condition.unsupported_stanza_type);
        Log.warn("Closing session due to incorrect stream header. Tag: " + stanza.getName());
    } else if (!FRAMING_NAMESPACE.equals(stanza.getNamespace().getURI())) {
        // Validate the stream namespace (https://tools.ietf.org/html/rfc7395#section-3.3.2)
        streamError = new StreamError(StreamError.Condition.invalid_namespace);
        Log.warn("Closing session due to invalid namespace in stream header. Namespace: "
                + stanza.getNamespace().getURI());
    } else if (!validateHost(host)) {
        streamError = new StreamError(StreamError.Condition.host_unknown);
        Log.warn("Closing session due to incorrect hostname in stream header. Host: " + host);
    } else {
        // valid stream; initiate session
        xmppSession = SessionManager.getInstance().createClientSession(wsConnection, language);
        xmppSession.setSessionData("ws", Boolean.TRUE);
    }

    if (xmppSession == null) {
        closeStream(streamError);
    } else {
        openStream(language.toLanguageTag(), stanza.attributeValue("from"));
        configureStream();
    }
}

From source file:org.jivesoftware.wildfire.plugin.VCardExtendedPresencePlugin.java

License:Open Source License

/**
 * Adds nickname information from a given user's vCard NICK field 
 *  to a packet if the packet does not contain nickname information yet.
 *
 * @param packet the packet to modify/*from  ww w .j a  va  2s .c  o  m*/
 * @param user the user whose information is added to the packet 
 */
protected void addNick(Packet packet, String user) {
    // Check if there already is a nickname
    if (packet.getElement().element(QName.get("nick", "http://jabber.org/protocol/nick")) != null)
        return;

    // Add the nickname
    String nick = getNick(user, false);
    if (nick.length() > 0) {
        packet.getElement().addElement("nick", "http://jabber.org/protocol/nick").setText(nick);
    }
}

From source file:org.jivesoftware.wildfire.plugin.VCardExtendedPresencePlugin.java

License:Open Source License

/**
 * Adds the hash of a given user's vCard PHOTO field to a packet if the
 * packet does not contain a photo hash yet.
 *
 * @param packet the packet to modify// w w  w.  jav  a 2 s.c om
 * @param user the user whose information is added to the packet 
 */
protected void addPhotoHash(Packet packet, String user) {
    // Check if there already is an <x> element and/or a photo hash
    Element element = packet.getElement().element(QName.get("x", "vcard-temp:x:update"));
    if (element != null) {
        if (element.element("photo") != null)
            return;
    } else {
        element = packet.getElement().addElement("x", "vcard-temp:x:update");
    }

    // Add the photo hash
    element.addElement("photo").addText(getPhotoHash(user, false));
}

From source file:org.jivesoftware.xmpp.workgroup.Agent.java

License:Open Source License

public Element getAgentInfo() {
    // Create an agent element
    Element element = DocumentHelper.createElement(QName.get("agent", "http://jabber.org/protocol/workgroup"));
    element.addAttribute("jid", getAgentJID().toString());
    // Add the name of the agent
    if (getNickname() != null) {
        element.addElement("name", "http://jivesoftware.com/protocol/workgroup").setText(getNickname());
    }// ww  w  .j av a  2  s  .c om

    return element;
}