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.muc.spi.IQOwnerHandler.java

License:Open Source License

/**
 * Handles the IQ packet sent by an owner of the room. Possible actions are:
 * <ul>//from w w w  .  j  ava 2s .  c  o  m
 * <li>Return the list of owners</li>
 * <li>Return the list of admins</li>
 * <li>Change user's affiliation to owner</li>
 * <li>Change user's affiliation to admin</li>
 * <li>Change user's affiliation to member</li>
 * <li>Change user's affiliation to none</li>
 * <li>Destroy the room</li>
 * <li>Return the room configuration within a dataform</li>
 * <li>Update the room configuration based on the sent dataform</li>
 * </ul>
 *
 * @param packet the IQ packet sent by an owner of the room.
 * @param role the role of the user that sent the packet.
 * @throws ForbiddenException if the user does not have enough permissions (ie. is not an owner).
 * @throws ConflictException If the room was going to lose all of its owners.
 */
@SuppressWarnings("unchecked")
public void handleIQ(IQ packet, MUCRole role)
        throws ForbiddenException, ConflictException, CannotBeInvitedException {
    // Only owners can send packets with the namespace "http://jabber.org/protocol/muc#owner"
    if (MUCRole.Affiliation.owner != role.getAffiliation()) {
        throw new ForbiddenException();
    }

    IQ reply = IQ.createResultIQ(packet);
    Element element = packet.getChildElement();

    // Analyze the action to perform based on the included element
    Element formElement = element.element(QName.get("x", "jabber:x:data"));
    if (formElement != null) {
        handleDataFormElement(role, formElement);
    } else {
        Element destroyElement = element.element("destroy");
        if (destroyElement != null) {
            if (((MultiUserChatServiceImpl) room.getMUCService()).getMUCDelegate() != null) {
                if (!((MultiUserChatServiceImpl) room.getMUCService()).getMUCDelegate()
                        .destroyingRoom(room.getName(), role.getUserAddress())) {
                    // Delegate said no, reject destroy request.
                    throw new ForbiddenException();
                }
            }

            JID alternateJID = null;
            final String jid = destroyElement.attributeValue("jid");
            if (jid != null) {
                alternateJID = new JID(jid);
            }
            room.destroyRoom(alternateJID, destroyElement.elementTextTrim("reason"));
        } else {
            // If no element was included in the query element then answer the
            // configuration form
            if (!element.elementIterator().hasNext()) {
                refreshConfigurationFormValues();
                reply.setChildElement(probeResult.createCopy());
            }
            // An unknown and possibly incorrect element was included in the query
            // element so answer a BAD_REQUEST error
            else {
                reply.setChildElement(packet.getChildElement().createCopy());
                reply.setError(PacketError.Condition.bad_request);
            }
        }
    }
    if (reply.getTo() != null) {
        // Send a reply only if the sender of the original packet was from a real JID. (i.e. not
        // a packet generated locally)
        router.route(reply);
    }
}

From source file:org.jivesoftware.openfire.muc.spi.IQOwnerHandler.java

License:Open Source License

private void refreshConfigurationFormValues() {
    room.lock.readLock().lock();// w  ww.jav  a  2  s  .c o m
    try {
        FormField field = configurationForm.getField("muc#roomconfig_roomname");
        field.clearValues();
        field.addValue(room.getNaturalLanguageName());

        field = configurationForm.getField("muc#roomconfig_roomdesc");
        field.clearValues();
        field.addValue(room.getDescription());

        field = configurationForm.getField("muc#roomconfig_changesubject");
        field.clearValues();
        field.addValue((room.canOccupantsChangeSubject() ? "1" : "0"));

        field = configurationForm.getField("muc#roomconfig_maxusers");
        field.clearValues();
        field.addValue(Integer.toString(room.getMaxUsers()));

        field = configurationForm.getField("muc#roomconfig_presencebroadcast");
        field.clearValues();
        for (String roleToBroadcast : room.getRolesToBroadcastPresence()) {
            field.addValue(roleToBroadcast);
        }

        field = configurationForm.getField("muc#roomconfig_publicroom");
        field.clearValues();
        field.addValue((room.isPublicRoom() ? "1" : "0"));

        field = configurationForm.getField("muc#roomconfig_persistentroom");
        field.clearValues();
        field.addValue((room.isPersistent() ? "1" : "0"));

        field = configurationForm.getField("muc#roomconfig_moderatedroom");
        field.clearValues();
        field.addValue((room.isModerated() ? "1" : "0"));

        field = configurationForm.getField("muc#roomconfig_membersonly");
        field.clearValues();
        field.addValue((room.isMembersOnly() ? "1" : "0"));

        field = configurationForm.getField("muc#roomconfig_allowinvites");
        field.clearValues();
        field.addValue((room.canOccupantsInvite() ? "1" : "0"));

        field = configurationForm.getField("muc#roomconfig_passwordprotectedroom");
        field.clearValues();
        field.addValue((room.isPasswordProtected() ? "1" : "0"));

        field = configurationForm.getField("muc#roomconfig_roomsecret");
        field.clearValues();
        field.addValue(room.getPassword());

        field = configurationForm.getField("muc#roomconfig_whois");
        field.clearValues();
        field.addValue((room.canAnyoneDiscoverJID() ? "anyone" : "moderators"));

        field = configurationForm.getField("muc#roomconfig_enablelogging");
        field.clearValues();
        field.addValue((room.isLogEnabled() ? "1" : "0"));

        field = configurationForm.getField("x-muc#roomconfig_reservednick");
        field.clearValues();
        field.addValue((room.isLoginRestrictedToNickname() ? "1" : "0"));

        field = configurationForm.getField("x-muc#roomconfig_canchangenick");
        field.clearValues();
        field.addValue((room.canChangeNickname() ? "1" : "0"));

        field = configurationForm.getField("x-muc#roomconfig_registration");
        field.clearValues();
        field.addValue((room.isRegistrationEnabled() ? "1" : "0"));

        field = configurationForm.getField("muc#roomconfig_roomadmins");
        field.clearValues();
        for (JID jid : room.getAdmins()) {
            if (GroupJID.isGroup(jid)) {
                try {
                    // add each group member to the result (clients don't understand groups)
                    Group group = GroupManager.getInstance().getGroup(jid);
                    for (JID groupMember : group.getAll()) {
                        field.addValue(groupMember);
                    }
                } catch (GroupNotFoundException gnfe) {
                    Log.warn("Invalid group JID in the member list: " + jid);
                }
            } else {
                field.addValue(jid.toString());
            }
        }

        field = configurationForm.getField("muc#roomconfig_roomowners");
        field.clearValues();
        for (JID jid : room.getOwners()) {
            if (GroupJID.isGroup(jid)) {
                try {
                    // add each group member to the result (clients don't understand groups)
                    Group group = GroupManager.getInstance().getGroup(jid);
                    for (JID groupMember : group.getAll()) {
                        field.addValue(groupMember);
                    }
                } catch (GroupNotFoundException gnfe) {
                    Log.warn("Invalid group JID in the member list: " + jid);
                }
            } else {
                field.addValue(jid.toString());
            }
        }

        // Remove the old element
        probeResult.remove(probeResult.element(QName.get("x", "jabber:x:data")));
        // Add the new representation of configurationForm as an element 
        probeResult.add(configurationForm.getElement());

    } finally {
        room.lock.readLock().unlock();
    }
}

From source file:org.jivesoftware.openfire.muc.spi.IQOwnerHandler.java

License:Open Source License

private void init() {
    Element element = DocumentHelper.createElement(QName.get("query", "http://jabber.org/protocol/muc#owner"));

    configurationForm = new DataForm(DataForm.Type.form);
    configurationForm.setTitle(LocaleUtils.getLocalizedString("muc.form.conf.title"));
    List<String> params = new ArrayList<String>();
    params.add(room.getName());/*from  w w w . ja  v a 2 s.  c  o  m*/
    configurationForm.addInstruction(LocaleUtils.getLocalizedString("muc.form.conf.instruction", params));

    configurationForm.addField("FORM_TYPE", null, Type.hidden)
            .addValue("http://jabber.org/protocol/muc#roomconfig");

    configurationForm.addField("muc#roomconfig_roomname",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_roomname"), Type.text_single);

    configurationForm.addField("muc#roomconfig_roomdesc",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_roomdesc"), Type.text_single);

    configurationForm.addField("muc#roomconfig_changesubject",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_changesubject"), Type.boolean_type);

    final FormField maxUsers = configurationForm.addField("muc#roomconfig_maxusers",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_maxusers"), Type.list_single);
    maxUsers.addOption("10", "10");
    maxUsers.addOption("20", "20");
    maxUsers.addOption("30", "30");
    maxUsers.addOption("40", "40");
    maxUsers.addOption("50", "50");
    maxUsers.addOption(LocaleUtils.getLocalizedString("muc.form.conf.none"), "0");

    final FormField broadcast = configurationForm.addField("muc#roomconfig_presencebroadcast",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_presencebroadcast"), Type.list_multi);
    broadcast.addOption(LocaleUtils.getLocalizedString("muc.form.conf.moderator"), "moderator");
    broadcast.addOption(LocaleUtils.getLocalizedString("muc.form.conf.participant"), "participant");
    broadcast.addOption(LocaleUtils.getLocalizedString("muc.form.conf.visitor"), "visitor");

    configurationForm.addField("muc#roomconfig_publicroom",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_publicroom"), Type.boolean_type);

    configurationForm.addField("muc#roomconfig_persistentroom",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_persistentroom"), Type.boolean_type);

    configurationForm.addField("muc#roomconfig_moderatedroom",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_moderatedroom"), Type.boolean_type);

    configurationForm.addField("muc#roomconfig_membersonly",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_membersonly"), Type.boolean_type);

    configurationForm.addField(null, null, Type.fixed)
            .addValue(LocaleUtils.getLocalizedString("muc.form.conf.allowinvitesfixed"));

    configurationForm.addField("muc#roomconfig_allowinvites",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_allowinvites"), Type.boolean_type);

    configurationForm.addField("muc#roomconfig_passwordprotectedroom",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_passwordprotectedroom"), Type.boolean_type);

    configurationForm.addField(null, null, Type.fixed)
            .addValue(LocaleUtils.getLocalizedString("muc.form.conf.roomsecretfixed"));

    configurationForm.addField("muc#roomconfig_roomsecret",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_roomsecret"), Type.text_private);

    final FormField whois = configurationForm.addField("muc#roomconfig_whois",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_whois"), Type.list_single);
    whois.addOption(LocaleUtils.getLocalizedString("muc.form.conf.moderator"), "moderators");
    whois.addOption(LocaleUtils.getLocalizedString("muc.form.conf.anyone"), "anyone");

    configurationForm.addField("muc#roomconfig_enablelogging",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_enablelogging"), Type.boolean_type);

    configurationForm.addField("x-muc#roomconfig_reservednick",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_reservednick"), Type.boolean_type);

    configurationForm.addField("x-muc#roomconfig_canchangenick",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_canchangenick"), Type.boolean_type);

    configurationForm.addField(null, null, Type.fixed)
            .addValue(LocaleUtils.getLocalizedString("muc.form.conf.owner_registration"));

    configurationForm.addField("x-muc#roomconfig_registration",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_registration"), Type.boolean_type);

    configurationForm.addField(null, null, Type.fixed)
            .addValue(LocaleUtils.getLocalizedString("muc.form.conf.roomadminsfixed"));

    configurationForm.addField("muc#roomconfig_roomadmins",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_roomadmins"), Type.jid_multi);

    configurationForm.addField(null, null, Type.fixed)
            .addValue(LocaleUtils.getLocalizedString("muc.form.conf.roomownersfixed"));

    configurationForm.addField("muc#roomconfig_roomowners",
            LocaleUtils.getLocalizedString("muc.form.conf.owner_roomowners"), Type.jid_multi);

    // Create the probeResult and add the basic info together with the configuration form
    probeResult = element;
    probeResult.add(configurationForm.getElement());
}

From source file:org.jivesoftware.openfire.multiplex.MultiplexerPacketHandler.java

License:Open Source License

/**
 * Process IQ packet sent by a connection manager indicating that a new session has
 * been created, should be closed or that a packet was failed to be delivered.
 *
 * @param packet the IQ packet./*w w w.jav  a  2  s  . c om*/
 */
public void handle(Packet packet) {
    if (packet instanceof IQ) {
        IQ iq = (IQ) packet;
        if (iq.getType() == IQ.Type.result) {
            // Do nothing with result packets
        } else if (iq.getType() == IQ.Type.error) {
            // Log the IQ error packet that the connection manager failed to process
            Log.warn("Connection Manager failed to process IQ packet: " + packet.toXML());
        } else if (iq.getType() == IQ.Type.set) {
            Element child = iq.getChildElement();
            String streamID = child.attributeValue("id");
            if (streamID == null) {
                // No stream ID was included so return a bad_request error
                Element extraError = DocumentHelper.createElement(
                        QName.get("id-required", "http://jabber.org/protocol/connectionmanager#errors"));
                sendErrorPacket(iq, PacketError.Condition.bad_request, extraError);
            } else if ("session".equals(child.getName())) {
                Element create = child.element("create");
                if (create != null) {
                    // Get the InetAddress of the client
                    Element hostElement = create.element("host");
                    String hostName = hostElement != null ? hostElement.attributeValue("name") : null;
                    String hostAddress = hostElement != null ? hostElement.attributeValue("address") : null;
                    // Connection Manager wants to create a Client Session
                    boolean created = multiplexerManager.createClientSession(connectionManagerDomain, streamID,
                            hostName, hostAddress);
                    if (created) {
                        sendResultPacket(iq);
                    } else {
                        // Send error to CM. The CM should close the new-borned connection
                        sendErrorPacket(iq, PacketError.Condition.not_allowed, null);
                    }
                } else {
                    ClientSession session = multiplexerManager.getClientSession(connectionManagerDomain,
                            streamID);
                    if (session == null) {
                        // Specified Client Session does not exist
                        sendErrorPacket(iq, PacketError.Condition.item_not_found, null);
                    } else if (child.element("close") != null) {
                        // Connection Manager wants to close a Client Session
                        multiplexerManager.closeClientSession(connectionManagerDomain, streamID);
                        sendResultPacket(iq);
                    } else if (child.element("failed") != null) {
                        // Connection Manager failed to deliver a message
                        // Connection Manager wrapped a packet from a Client Session.
                        List wrappedElements = child.element("failed").elements();
                        if (wrappedElements.size() != 1) {
                            // Wrapper element is wrapping 0 or many items
                            Element extraError = DocumentHelper.createElement(QName.get("invalid-payload",
                                    "http://jabber.org/protocol/connectionmanager#errors"));
                            sendErrorPacket(iq, PacketError.Condition.bad_request, extraError);
                        } else {
                            Element wrappedElement = (Element) wrappedElements.get(0);
                            String tag = wrappedElement.getName();
                            if ("message".equals(tag)) {
                                XMPPServer.getInstance().getOfflineMessageStrategy()
                                        .storeOffline(new Message(wrappedElement));
                                sendResultPacket(iq);
                            } else {
                                Element extraError = DocumentHelper.createElement(QName.get("unknown-stanza",
                                        "http://jabber.org/protocol/connectionmanager#errors"));
                                sendErrorPacket(iq, PacketError.Condition.bad_request, extraError);
                            }
                        }
                    } else {
                        // Unknown IQ packet received so return error to sender
                        sendErrorPacket(iq, PacketError.Condition.bad_request, null);
                    }
                }
            } else {
                // Unknown IQ packet received so return error to sender
                sendErrorPacket(iq, PacketError.Condition.bad_request, null);
            }
        } else {
            // Unknown IQ packet received so return error to sender
            sendErrorPacket(iq, PacketError.Condition.bad_request, null);
        }
    }
}

From source file:org.jivesoftware.openfire.multiplex.MultiplexerPacketHandler.java

License:Open Source License

/**
 * Processes a route packet that is wrapping a stanza sent by a client that is connected
 * to the connection manager.// ww  w  .j  a  va 2 s  .  c  o m
 *
 * @param route the route packet.
 */
public void route(Route route) {
    String streamID = route.getStreamID();
    if (streamID == null) {
        // No stream ID was included so return a bad_request error
        Element extraError = DocumentHelper
                .createElement(QName.get("id-required", "http://jabber.org/protocol/connectionmanager#errors"));
        sendErrorPacket(route, PacketError.Condition.bad_request, extraError);
    }
    LocalClientSession session = multiplexerManager.getClientSession(connectionManagerDomain, streamID);
    if (session == null) {
        // Specified Client Session does not exist
        sendErrorPacket(route, PacketError.Condition.item_not_found, null);
        return;
    }

    SessionPacketRouter router = new SessionPacketRouter(session);
    // Connection Manager already validate JIDs so just skip this expensive operation
    router.setSkipJIDValidation(true);
    try {
        router.route(route.getChildElement());
    } catch (UnknownStanzaException use) {
        Element extraError = DocumentHelper.createElement(
                QName.get("unknown-stanza", "http://jabber.org/protocol/connectionmanager#errors"));
        sendErrorPacket(route, PacketError.Condition.bad_request, extraError);
    } catch (Exception e) {
        Log.error("Error processing wrapped packet: " + route.getChildElement().asXML(), e);
        sendErrorPacket(route, PacketError.Condition.internal_server_error, null);
    }
}

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

License:Open Source License

/**
 * Decide whether a message should be stored offline according to XEP-0160 and XEP-0334.
 *
 * @param message/*from  w w w. j av  a  2  s  . co  m*/
 * @return <code>true</code> if the message should be stored offline, <code>false</code> otherwise.
 */
static boolean shouldStoreMessage(final Message message) {
    // XEP-0334: Implement the <no-store/> hint to override offline storage
    if (message.getChildElement("no-store", "urn:xmpp:hints") != null) {
        return false;
    }

    switch (message.getType()) {
    case chat:
        // XEP-0160: Messages with a 'type' attribute whose value is "chat" SHOULD be stored offline, with the exception of messages that contain only Chat State Notifications (XEP-0085) [7] content

        // Iterate through the child elements to see if we can find anything that's not a chat state notification or
        // real time text notification
        Iterator<?> it = message.getElement().elementIterator();

        while (it.hasNext()) {
            Object item = it.next();

            if (item instanceof Element) {
                Element el = (Element) item;

                if (!el.getNamespaceURI().equals("http://jabber.org/protocol/chatstates")
                        && !(el.getQName().equals(QName.get("rtt", "urn:xmpp:rtt:0")))) {
                    return true;
                }
            }
        }

        return false;

    case groupchat:
    case headline:
        // XEP-0160: "groupchat" message types SHOULD NOT be stored offline
        // XEP-0160: "headline" message types SHOULD NOT be stored offline
        return false;

    case error:
        // XEP-0160: "error" message types SHOULD NOT be stored offline,
        // although a server MAY store advanced message processing errors offline
        if (message.getChildElement("amp", "http://jabber.org/protocol/amp") == null) {
            return false;
        }
        break;

    default:
        // XEP-0160: Messages with a 'type' attribute whose value is "normal" (or messages with no 'type' attribute) SHOULD be stored offline.
        break;
    }
    return true;
}

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

License:Open Source License

/**
 * Generates and processes an IQ stanza that subscribes to a PEP service.
 *
 * @param pepService the PEP service of the owner.
 * @param subscriber the JID of the entity that is subscribing to the PEP service.
 * @param owner      the JID of the owner of the PEP service.
 *//* w w w.  j av a2  s.  c  o  m*/
private void createSubscriptionToPEPService(PEPService pepService, JID subscriber, JID owner) {
    // If `owner` has a PEP service, generate and process a pubsub subscription packet
    // that is equivalent to: (where 'from' field is JID of subscriber and 'to' field is JID of owner)
    //
    //        <iq type='set'
    //            from='nurse@capulet.com/chamber'
    //            to='juliet@capulet.com
    //            id='collsub'>
    //          <pubsub xmlns='http://jabber.org/protocol/pubsub'>
    //            <subscribe jid='nurse@capulet.com'/>
    //            <options>
    //              <x xmlns='jabber:x:data'>
    //                <field var='FORM_TYPE' type='hidden'>
    //                  <value>http://jabber.org/protocol/pubsub#subscribe_options</value>
    //                </field>
    //                <field var='pubsub#subscription_type'>
    //                  <value>items</value>
    //                </field>
    //                <field var='pubsub#subscription_depth'>
    //                  <value>all</value>
    //                </field>
    //              </x>
    //           </options>
    //         </pubsub>
    //        </iq>

    IQ subscriptionPacket = new IQ(IQ.Type.set);
    subscriptionPacket.setFrom(subscriber);
    subscriptionPacket.setTo(owner.toBareJID());

    Element pubsubElement = subscriptionPacket.setChildElement("pubsub", "http://jabber.org/protocol/pubsub");

    Element subscribeElement = pubsubElement.addElement("subscribe");
    subscribeElement.addAttribute("jid", subscriber.toBareJID());

    Element optionsElement = pubsubElement.addElement("options");
    Element xElement = optionsElement.addElement(QName.get("x", "jabber:x:data"));

    DataForm dataForm = new DataForm(xElement);

    FormField formField = dataForm.addField();
    formField.setVariable("FORM_TYPE");
    formField.setType(FormField.Type.hidden);
    formField.addValue("http://jabber.org/protocol/pubsub#subscribe_options");

    formField = dataForm.addField();
    formField.setVariable("pubsub#subscription_type");
    formField.addValue("items");

    formField = dataForm.addField();
    formField.setVariable("pubsub#subscription_depth");
    formField.addValue("all");

    pepServiceManager.process(pepService, subscriptionPacket);
}

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

License:Open Source License

public void sendNotification(Node node, Message message, JID recipientJID) {
    message.setTo(recipientJID);//ww w. j a va 2s .c  o m
    message.setFrom(getAddress());
    message.setID(node.getNodeID() + "__" + recipientJID.toBareJID() + "__" + StringUtils.randomString(5));

    // If the recipient subscribed with a bare JID and this PEPService can retrieve
    // presence information for the recipient, collect all of their full JIDs and
    // send the notification to each below.
    Set<JID> recipientFullJIDs = new HashSet<JID>();
    if (XMPPServer.getInstance().isLocal(recipientJID)) {
        if (recipientJID.getResource() == null) {
            for (ClientSession clientSession : SessionManager.getInstance()
                    .getSessions(recipientJID.getNode())) {
                recipientFullJIDs.add(clientSession.getAddress());
            }
        }
    } else {
        // Since recipientJID is not local, try to get presence info from cached known remote
        // presences.

        // TODO: OF-605 the old code depends on a cache that would contain presence state on all (?!) JIDS on all (?!)
        // remote domains. As we cannot depend on this information to be correct (even if we could ensure that this
        // potentially unlimited amount of data would indeed be manageable in the first place), this code was removed.

        recipientFullJIDs.add(recipientJID);
    }

    if (recipientFullJIDs.isEmpty()) {
        router.route(message);
        return;
    }

    for (JID recipientFullJID : recipientFullJIDs) {
        // Include an Extended Stanza Addressing "replyto" extension specifying the publishing
        // resource. However, only include the extension if the receiver has a presence subscription
        // to the service owner.
        try {
            JID publisher = null;

            // Get the ID of the node that had an item published to or retracted from.
            Element itemsElement = message.getElement().element("event").element("items");
            String nodeID = itemsElement.attributeValue("node");

            // Get the ID of the item that was published or retracted.
            String itemID = null;
            Element itemElement = itemsElement.element("item");
            if (itemElement == null) {
                Element retractElement = itemsElement.element("retract");
                if (retractElement != null) {
                    itemID = retractElement.attributeValue("id");
                }
            } else {
                itemID = itemElement.attributeValue("id");
            }

            // Check if the recipientFullJID is interested in notifications for this node.
            // If the recipient has not yet requested any notification filtering, continue and send
            // the notification.
            EntityCapabilities entityCaps = entityCapsManager.getEntityCapabilities(recipientFullJID);
            if (entityCaps != null) {
                if (!entityCaps.containsFeature(nodeID + "+notify")) {
                    return;
                }
            }

            // Get the full JID of the item publisher from the node that was published to.
            // This full JID will be used as the "replyto" address in the addressing extension.
            if (node.isCollectionNode()) {
                for (Node leafNode : node.getNodes()) {
                    if (leafNode.getNodeID().equals(nodeID)) {
                        publisher = leafNode.getPublishedItem(itemID).getPublisher();

                        // Ensure the recipientJID has access to receive notifications for items published to the leaf node.
                        AccessModel accessModel = leafNode.getAccessModel();
                        if (!accessModel.canAccessItems(leafNode, recipientFullJID, publisher)) {
                            return;
                        }

                        break;
                    }
                }
            } else {
                publisher = node.getPublishedItem(itemID).getPublisher();
            }

            // Ensure the recipient is subscribed to the service owner's (publisher's) presence.
            if (canProbePresence(publisher, recipientFullJID)) {
                Element addresses = DocumentHelper
                        .createElement(QName.get("addresses", "http://jabber.org/protocol/address"));
                Element address = addresses.addElement("address");
                address.addAttribute("type", "replyto");
                address.addAttribute("jid", publisher.toString());

                Message extendedMessage = message.createCopy();
                extendedMessage.addExtension(new PacketExtension(addresses));

                extendedMessage.setTo(recipientFullJID);
                router.route(extendedMessage);
            }
        } catch (IndexOutOfBoundsException e) {
            // Do not add addressing extension to message.
        } catch (UserNotFoundException e) {
            // Do not add addressing extension to message.
            router.route(message);
        } catch (NullPointerException e) {
            try {
                if (canProbePresence(getAddress(), recipientFullJID)) {
                    message.setTo(recipientFullJID);
                }
            } catch (UserNotFoundException e1) {
                // Do nothing
            }
            router.route(message);
        }
    }
}

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

License:Open Source License

/**
 * Processes an IQ stanza of type 'get', which in the context of 'Jabber Search' is a request for available search fields.
 * //from   ww  w. java2 s.  c  o  m
 * @param packet
 *            An IQ stanza of type 'get'
 * @return A result IQ stanza that contains the possbile search fields.
 */
private IQ processGetPacket(IQ packet) {
    if (!packet.getType().equals(IQ.Type.get)) {
        throw new IllegalArgumentException("This method only accepts 'get' typed IQ stanzas as an argument.");
    }
    IQ replyPacket = IQ.createResultIQ(packet);

    Element queryResult = DocumentHelper.createElement(QName.get("query", NAMESPACE_JABBER_IQ_SEARCH));

    String instructions = LocaleUtils.getLocalizedString("advance.user.search.details", "search");

    // non-data form
    queryResult.addElement("instructions").addText(instructions);
    queryResult.addElement("first");
    queryResult.addElement("last");
    queryResult.addElement("nick");
    queryResult.addElement("email");

    DataForm searchForm = new DataForm(DataForm.Type.form);
    searchForm.setTitle(LocaleUtils.getLocalizedString("advance.user.search.title", "search"));
    searchForm.addInstruction(instructions);

    searchForm.addField("FORM_TYPE", null, FormField.Type.hidden).addValue(NAMESPACE_JABBER_IQ_SEARCH);

    searchForm.addField("search", LocaleUtils.getLocalizedString("advance.user.search.search", "search"),
            FormField.Type.text_single).setRequired(true);

    for (String searchField : getFilteredSearchFields()) {
        final FormField field = searchForm.addField();
        field.setVariable(searchField);
        field.setType(FormField.Type.boolean_type);
        field.addValue("1");
        field.setLabel(
                LocaleUtils.getLocalizedString("advance.user.search." + searchField.toLowerCase(), "search"));
        field.setRequired(false);
    }

    queryResult.add(searchForm.getElement());
    replyPacket.setChildElement(queryResult);

    return replyPacket;
}

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

License:Open Source License

/**
 * Processes an IQ stanza of type 'set', which in the context of 'Jabber Search' is a search request.
 * //from w w  w . jav a 2 s  .com
 * @param packet
 *            An IQ stanza of type 'get'
 * @return A result IQ stanza that contains the possbile search fields.
 */
private IQ processSetPacket(IQ packet) {
    if (!packet.getType().equals(IQ.Type.set)) {
        throw new IllegalArgumentException("This method only accepts 'set' typed IQ stanzas as an argument.");
    }

    JID fromJID = packet.getFrom();

    final IQ resultIQ;

    // check if the request complies to the XEP-0055 standards
    if (!isValidSearchRequest(packet)) {
        resultIQ = IQ.createResultIQ(packet);
        resultIQ.setError(Condition.bad_request);
        return resultIQ;
    }

    final Element incomingForm = packet.getChildElement();
    final boolean isDataFormQuery = (incomingForm.element(QName.get("x", "jabber:x:data")) != null);

    final Element rsmElement = incomingForm
            .element(QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));

    if (rsmElement != null) {
        final Element maxElement = rsmElement.element("max");
        final Element startIndexElement = rsmElement.element("index");

        int startIndex = 0;
        if (startIndexElement != null) {
            startIndex = Integer.parseInt(startIndexElement.getTextTrim());
        }

        int max = -1;
        if (maxElement != null) {
            max = Integer.parseInt(maxElement.getTextTrim());
        }

        final Set<User> searchResults = performSearch(incomingForm, startIndex, max);

        if (groupOnly) {
            Collection<Group> groups = GroupManager.getInstance().getGroups(fromJID);
            Set<User> allSearchResults = new HashSet<User>(searchResults);
            searchResults.clear();
            for (User user : allSearchResults) {
                for (Group group : groups) {
                    if (group.isUser(user.getUID())) {
                        searchResults.add(user);
                    }
                }
            }
        }

        // apply RSM
        final List<User> rsmResults;
        final ResultSet<User> rs = new ResultSetImpl<User>(searchResults);
        try {
            rsmResults = rs.applyRSMDirectives(rsmElement);
        } catch (NullPointerException e) {
            final IQ itemNotFound = IQ.createResultIQ(packet);
            itemNotFound.setError(Condition.item_not_found);
            return itemNotFound;
        }
        if (isDataFormQuery) {
            resultIQ = replyDataFormResult(rsmResults, packet);
        } else {
            resultIQ = replyNonDataFormResult(rsmResults, packet);
        }

        // add the additional 'set' element.
        final Element set = rs.generateSetElementFromResults(rsmResults);
        resultIQ.getChildElement().add(set);

    } else {
        final Set<User> searchResults = performSearch(incomingForm);

        if (groupOnly) {
            Collection<Group> groups = GroupManager.getInstance().getGroups(fromJID);
            Set<User> allSearchResults = new HashSet<User>(searchResults);
            searchResults.clear();
            for (User user : allSearchResults) {
                for (Group group : groups) {
                    if (group.isUser(user.getUID())) {
                        searchResults.add(user);
                    }
                }
            }
        }

        // don't apply RSM
        if (isDataFormQuery) {
            resultIQ = replyDataFormResult(searchResults, packet);
        } else {
            resultIQ = replyNonDataFormResult(searchResults, packet);
        }
    }

    return resultIQ;
}