Example usage for org.dom4j Element createCopy

List of usage examples for org.dom4j Element createCopy

Introduction

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

Prototype

Element createCopy();

Source Link

Document

Creates a deep copy of this element The new element is detached from its parent, and getParent() on the clone will return null.

Usage

From source file:org.jivesoftware.openfire.handler.IQvCardHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
    IQ result = IQ.createResultIQ(packet);
    IQ.Type type = packet.getType();
    if (type.equals(IQ.Type.set)) {
        try {/* w w  w  .  ja v  a  2  s .  co m*/
            User user = userManager.getUser(packet.getFrom().getNode());
            Element vcard = packet.getChildElement();
            if (vcard != null) {
                VCardManager.getInstance().setVCard(user.getUsername(), vcard);
            }
        } catch (UserNotFoundException e) {
            result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.item_not_found);
        } catch (Exception e) {
            Log.error(e.getMessage(), e);
            result.setError(PacketError.Condition.internal_server_error);
        }
    } else if (type.equals(IQ.Type.get)) {
        JID recipient = packet.getTo();
        // If no TO was specified then get the vCard of the sender of the packet
        if (recipient == null) {
            recipient = packet.getFrom();
        }
        // By default return an empty vCard
        result.setChildElement("vCard", "vcard-temp");
        // Only try to get the vCard values of non-anonymous users
        if (recipient != null) {
            if (recipient.getNode() != null && server.isLocal(recipient)) {
                VCardManager vManager = VCardManager.getInstance();
                Element userVCard = vManager.getVCard(recipient.getNode());
                if (userVCard != null) {
                    // Check if the requester wants to ignore some vCard's fields
                    Element filter = packet.getChildElement().element(QName.get("filter", "vcard-temp-filter"));
                    if (filter != null) {
                        // Create a copy so we don't modify the original vCard
                        userVCard = userVCard.createCopy();
                        // Ignore fields requested by the user
                        for (Iterator toFilter = filter.elementIterator(); toFilter.hasNext();) {
                            Element field = (Element) toFilter.next();
                            Element fieldToRemove = userVCard.element(field.getName());
                            if (fieldToRemove != null) {
                                fieldToRemove.detach();
                            }
                        }
                    }
                    result.setChildElement(userVCard);
                }
            } else {
                result = IQ.createResultIQ(packet);
                result.setChildElement(packet.getChildElement().createCopy());
                result.setError(PacketError.Condition.item_not_found);
            }
        } else {
            result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.item_not_found);
        }
    } else {
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.not_acceptable);
    }
    return result;
}

From source file:org.jivesoftware.openfire.IQRouter.java

License:Open Source License

/**
 * <p>Performs the actual packet routing.</p>
 * <p>You routing is considered 'quick' and implementations may not take
 * excessive amounts of time to complete the routing. If routing will take
 * a long amount of time, the actual routing should be done in another thread
 * so this method returns quickly.</p>
 * <h2>Warning</h2>//  ww  w.  java  2s . c  o m
 * <p>Be careful to enforce concurrency DbC of concurrent by synchronizing
 * any accesses to class resources.</p>
 *
 * @param packet The packet to route
 * @throws NullPointerException If the packet is null
 */
public void route(IQ packet) {
    if (packet == null) {
        throw new NullPointerException();
    }
    JID sender = packet.getFrom();
    ClientSession session = sessionManager.getSession(sender);
    Element childElement = packet.getChildElement(); // may be null
    try {
        // Invoke the interceptors before we process the read packet
        InterceptorManager.getInstance().invokeInterceptors(packet, session, true, false);
        JID to = packet.getTo();
        if (session != null && to != null && session.getStatus() == Session.STATUS_CONNECTED
                && !serverName.equals(to.toString())) {
            // User is requesting this server to authenticate for another server. Return
            // a bad-request error
            IQ reply = IQ.createResultIQ(packet);
            if (childElement != null) {
                reply.setChildElement(childElement.createCopy());
            }
            reply.setError(PacketError.Condition.bad_request);
            session.process(reply);
            Log.warn("User tried to authenticate with this server using an unknown receipient: "
                    + packet.toXML());
        } else if (session == null || session.getStatus() == Session.STATUS_AUTHENTICATED
                || (childElement != null && isLocalServer(to)
                        && ("jabber:iq:auth".equals(childElement.getNamespaceURI())
                                || "jabber:iq:register".equals(childElement.getNamespaceURI())
                                || "urn:ietf:params:xml:ns:xmpp-bind"
                                        .equals(childElement.getNamespaceURI())))) {
            handle(packet);
        } else if (packet.getType() == IQ.Type.get || packet.getType() == IQ.Type.set) {
            IQ reply = IQ.createResultIQ(packet);
            if (childElement != null) {
                reply.setChildElement(childElement.createCopy());
            }
            reply.setError(PacketError.Condition.not_authorized);
            session.process(reply);
        }
        // Invoke the interceptors after we have processed the read packet
        InterceptorManager.getInstance().invokeInterceptors(packet, session, true, true);
    } catch (PacketRejectedException e) {
        if (session != null) {
            // An interceptor rejected this packet so answer a not_allowed error
            IQ reply = new IQ();
            if (childElement != null) {
                reply.setChildElement(childElement.createCopy());
            }
            reply.setID(packet.getID());
            reply.setTo(session.getAddress());
            reply.setFrom(packet.getTo());
            reply.setError(PacketError.Condition.not_allowed);
            session.process(reply);
            // Check if a message notifying the rejection should be sent
            if (e.getRejectionMessage() != null && e.getRejectionMessage().trim().length() > 0) {
                // A message for the rejection will be sent to the sender of the rejected packet
                Message notification = new Message();
                notification.setTo(session.getAddress());
                notification.setFrom(packet.getTo());
                notification.setBody(e.getRejectionMessage());
                session.process(notification);
            }
        }
    }
}

From source file:org.jivesoftware.openfire.net.ComponentStanzaHandler.java

License:Open Source License

@Override
boolean processUnknowPacket(Element doc) throws UnauthorizedException {
    String tag = doc.getName();//  w w w .j  av  a  2 s .  co m
    if ("handshake".equals(tag)) {
        // External component is trying to authenticate
        if (!((LocalComponentSession) session).authenticate(doc.getStringValue())) {
            session.close();
        }
        return true;
    } else if ("error".equals(tag) && "stream".equals(doc.getNamespacePrefix())) {
        session.close();
        return true;
    } else if ("bind".equals(tag)) {
        // Handle subsequent bind packets
        LocalComponentSession componentSession = (LocalComponentSession) session;
        // Get the external component of this session
        ComponentSession.ExternalComponent component = componentSession.getExternalComponent();
        String initialDomain = component.getInitialSubdomain();
        String extraDomain = doc.attributeValue("name");
        String allowMultiple = doc.attributeValue("allowMultiple");
        if (extraDomain == null || "".equals(extraDomain)) {
            // No new bind domain was specified so return a bad_request error
            Element reply = doc.createCopy();
            reply.add(new PacketError(PacketError.Condition.bad_request).getElement());
            connection.deliverRawText(reply.asXML());
        } else if (extraDomain.equals(initialDomain)) {
            // Component is binding initial domain that is already registered
            // Send confirmation that the new domain has been registered
            connection.deliverRawText("<bind/>");
        } else if (extraDomain.endsWith(initialDomain)) {
            // Only accept subdomains under the initial registered domain
            if (allowMultiple != null && component.getSubdomains().contains(extraDomain)) {
                // Domain already in use so return a conflict error
                Element reply = doc.createCopy();
                reply.add(new PacketError(PacketError.Condition.conflict).getElement());
                connection.deliverRawText(reply.asXML());
            } else {
                try {
                    // Get the requested subdomain
                    String subdomain = extraDomain;
                    int index = extraDomain.indexOf(serverName);
                    if (index > -1) {
                        subdomain = extraDomain.substring(0, index - 1);
                    }
                    InternalComponentManager.getInstance().addComponent(subdomain, component);
                    // Send confirmation that the new domain has been registered
                    connection.deliverRawText("<bind/>");
                } catch (ComponentException e) {
                    Log.error("Error binding extra domain: " + extraDomain + " to component: " + component, e);
                    // Return internal server error
                    Element reply = doc.createCopy();
                    reply.add(new PacketError(PacketError.Condition.internal_server_error).getElement());
                    connection.deliverRawText(reply.asXML());
                }
            }
        } else {
            // Return forbidden error since we only allow subdomains of the intial domain
            // to be used by the same external component
            Element reply = doc.createCopy();
            reply.add(new PacketError(PacketError.Condition.forbidden).getElement());
            connection.deliverRawText(reply.asXML());
        }
        return true;
    }
    return false;
}

From source file:org.jivesoftware.openfire.pep.IQPEPHandler.java

License:Open Source License

/**
 * Implements UserItemsProvider, adding PEP related items to a disco#items
 * result.//from w  ww . ja v  a 2s.  c  o m
 */
public Iterator<Element> getUserItems(String name, JID senderJID) {
    ArrayList<Element> items = new ArrayList<Element>();

    String recipientJID = XMPPServer.getInstance().createJID(name, null, true).toBareJID();
    PEPService pepService = pepServiceManager.getPEPService(recipientJID);

    if (pepService != null) {
        CollectionNode rootNode = pepService.getRootCollectionNode();

        Element defaultItem = DocumentHelper.createElement("item");
        defaultItem.addAttribute("jid", recipientJID);

        for (Node node : pepService.getNodes()) {
            // Do not include the root node as an item element.
            if (node == rootNode) {
                continue;
            }

            AccessModel accessModel = node.getAccessModel();
            if (accessModel.canAccessItems(node, senderJID, new JID(recipientJID))) {
                Element item = defaultItem.createCopy();
                item.addAttribute("node", node.getNodeID());
                items.add(item);
            }
        }
    }

    return items.iterator();
}

From source file:org.jivesoftware.openfire.plugin.Xep227Exporter.java

License:Apache License

/**
 * Adding vcard element//from  ww  w  .j a v  a 2s .  c o m
 * 
 * @param userElement
 *            DOM element
 * @param userName
 *            user name
 */
@SuppressWarnings("unchecked")
private void exportVCard(Element userElement, String userName) {
    Element vCard = vCardManager.getVCard(userName);
    if (vCard != null) {
        Element vCardElement = userElement.addElement(V_CARD_NAME, VCARD_TEMP_NS);
        for (Iterator<Element> iterator = vCard.elementIterator(); iterator.hasNext();) {
            Element element = iterator.next();
            vCardElement.add(element.createCopy());

        }
    }
}

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

License:Open Source License

private void getSubscriptionConfiguration(PubSubService service, IQ iq, Element childElement,
        Element optionsElement) {
    String nodeID = optionsElement.attributeValue("node");
    String subID = optionsElement.attributeValue("subid");
    Node node;//from w w  w  . ja  v  a 2  s .  c o m
    if (nodeID == null) {
        if (service.isCollectionNodesSupported()) {
            // Entity requests subscription options of root collection node
            node = service.getRootCollectionNode();
        } else {
            // Service does not have a root collection node so return a nodeid-required error
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("nodeid-required", "http://jabber.org/protocol/pubsub#errors"));
            sendErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
            return;
        }
    } else {
        // Look for the specified 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;
        }
    }
    NodeSubscription subscription;
    if (node.isMultipleSubscriptionsEnabled()) {
        if (subID == null) {
            // No subid was specified and the node supports multiple subscriptions
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("subid-required", "http://jabber.org/protocol/pubsub#errors"));
            sendErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
            return;
        } else {
            // Check if the specified subID belongs to an existing node subscription
            subscription = node.getSubscription(subID);
            if (subscription == null) {
                Element pubsubError = DocumentHelper
                        .createElement(QName.get("invalid-subid", "http://jabber.org/protocol/pubsub#errors"));
                sendErrorPacket(iq, PacketError.Condition.not_acceptable, pubsubError);
                return;
            }
        }
    } else {
        // Check if the specified JID has a subscription with the node
        String jidAttribute = optionsElement.attributeValue("jid");
        if (jidAttribute == null) {
            // No JID was specified so return an error indicating that jid is required
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("jid-required", "http://jabber.org/protocol/pubsub#errors"));
            sendErrorPacket(iq, PacketError.Condition.bad_request, pubsubError);
            return;
        }
        JID subscriberJID = new JID(jidAttribute);
        subscription = node.getSubscription(subscriberJID);
        if (subscription == null) {
            Element pubsubError = DocumentHelper
                    .createElement(QName.get("not-subscribed", "http://jabber.org/protocol/pubsub#errors"));
            sendErrorPacket(iq, PacketError.Condition.unexpected_request, pubsubError);
            return;
        }
    }

    // A subscription was found so check if the user is allowed to get the subscription options
    if (!subscription.canModify(iq.getFrom())) {
        // Requestor is prohibited from getting the subscription options
        sendErrorPacket(iq, PacketError.Condition.forbidden, null);
        return;
    }

    // Return data form containing subscription configuration to the subscriber
    IQ reply = IQ.createResultIQ(iq);
    Element replyChildElement = childElement.createCopy();
    reply.setChildElement(replyChildElement);
    replyChildElement.element("options").add(subscription.getConfigurationForm().getElement());
    router.route(reply);
}

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

License:Open Source License

private void getSubscriptions(PubSubService service, IQ iq, Element childElement) {
    // TODO Assuming that owner is the bare JID (as defined in the JEP). This can be replaced with an explicit owner specified in the packet
    JID owner = iq.getFrom().asBareJID();
    Element subscriptionsElement = childElement.element("subscriptions");

    String nodeID = subscriptionsElement.attributeValue("node");
    Collection<NodeSubscription> subscriptions = new ArrayList<NodeSubscription>();

    if (nodeID == null) {
        // Collect subscriptions of owner for all nodes at the service
        for (Node node : service.getNodes()) {
            subscriptions.addAll(node.getSubscriptions(owner));
        }/*from   w w  w .j a  va  2s . c o  m*/
    } else {
        subscriptions.addAll(service.getNode(nodeID).getSubscriptions(owner));
    }
    // Create reply to send
    IQ reply = IQ.createResultIQ(iq);
    Element replyChildElement = childElement.createCopy();
    reply.setChildElement(replyChildElement);
    Element affiliationsElement = replyChildElement.element("subscriptions");
    // Add information about subscriptions including existing affiliations
    for (NodeSubscription subscription : subscriptions) {
        Element subElement = affiliationsElement.addElement("subscription");
        Node node = subscription.getNode();
        NodeAffiliate nodeAffiliate = subscription.getAffiliate();
        // Do not include the node id when node is the root collection node
        // or the results are for a specific node
        if (!node.isRootCollectionNode() && (nodeID == null)) {
            subElement.addAttribute("node", node.getNodeID());
        }
        subElement.addAttribute("jid", subscription.getJID().toString());
        subElement.addAttribute("subscription", subscription.getState().name());
        if (node.isMultipleSubscriptionsEnabled()) {
            subElement.addAttribute("subid", subscription.getID());
        }
    }
    // Send reply
    router.route(reply);
}

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

License:Open Source License

private void getAffiliations(PubSubService service, IQ iq, Element childElement) {
    // TODO Assuming that owner is the bare JID (as defined in the JEP). This can be replaced with an explicit owner specified in the packet
    JID owner = iq.getFrom().asBareJID();
    // Collect affiliations of owner for all nodes at the service
    Collection<NodeAffiliate> affiliations = new ArrayList<NodeAffiliate>();
    for (Node node : service.getNodes()) {
        NodeAffiliate nodeAffiliate = node.getAffiliate(owner);
        if (nodeAffiliate != null) {
            affiliations.add(nodeAffiliate);
        }/*from   w  w  w .  j  av a2s  .  c om*/
    }
    // Create reply to send
    IQ reply = IQ.createResultIQ(iq);
    Element replyChildElement = childElement.createCopy();
    reply.setChildElement(replyChildElement);
    if (affiliations.isEmpty()) {
        // User does not have any affiliation or subscription with the pubsub service
        reply.setError(PacketError.Condition.item_not_found);
    } else {
        Element affiliationsElement = replyChildElement.element("affiliations");
        // Add information about affiliations without subscriptions
        for (NodeAffiliate affiliate : affiliations) {
            Element affiliateElement = affiliationsElement.addElement("affiliation");
            // Do not include the node id when node is the root collection node
            if (!affiliate.getNode().isRootCollectionNode()) {
                affiliateElement.addAttribute("node", affiliate.getNode().getNodeID());
            }
            affiliateElement.addAttribute("jid", affiliate.getJID().toString());
            affiliateElement.addAttribute("affiliation", affiliate.getAffiliation().name());
        }
    }
    // Send reply
    router.route(reply);
}

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

License:Open Source License

private void getNodeConfiguration(PubSubService service, IQ iq, Element childElement, String nodeID) {
    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;//w w w. j a v a2s  .c o m
    }
    if (!node.isAdmin(iq.getFrom())) {
        // Requesting entity is prohibited from configuring this node. Return forbidden error
        sendErrorPacket(iq, PacketError.Condition.forbidden, null);
        return;
    }

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

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