Java Code Examples for org.xmpp.packet.IQ

The following examples show how to use org.xmpp.packet.IQ. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: openfire-ofmeet-plugin   Source File: OfMeetPlugin.java    License: Apache License 2.0 6 votes vote down vote up
public void sessionDestroyed(Session session)
{
    Log.debug("OfMeet Plugin -  sessionDestroyed "+ session.getAddress().toString() + "\n" + ((ClientSession) session).getPresence().toXML());

    boolean skypeAvailable = XMPPServer.getInstance().getPluginManager().getPlugin("ofskype") != null;

    if (OfMeetAzure.skypeids.containsKey(session.getAddress().getNode()))
    {
        String sipuri = OfMeetAzure.skypeids.remove(session.getAddress().getNode());

        IQ iq = new IQ(IQ.Type.set);
        iq.setFrom(session.getAddress());
        iq.setTo(XMPPServer.getInstance().getServerInfo().getXMPPDomain());

        Element child = iq.setChildElement("request", "http://igniterealtime.org/protocol/ofskype");
        child.setText("{'action':'stop_skype_user', 'sipuri':'" + sipuri + "'}");
        XMPPServer.getInstance().getIQRouter().route(iq);

        Log.info("OfMeet Plugin - closing skype session " + sipuri);
    }
}
 
Example 2
Source Project: onos   Source File: XmppPubSubControllerImpl.java    License: Apache License 2.0 6 votes vote down vote up
public static XmppPubSubConstants.Method getMethod(IQ iq) {
    Element pubsubElement = iq.getChildElement();
    Element methodElement = getChildElement(pubsubElement);
    String name = methodElement.getName();
    switch (name) {
        case "subscribe":
            return XmppPubSubConstants.Method.SUBSCRIBE;
        case "unsubscribe":
            return XmppPubSubConstants.Method.UNSUBSCRIBE;
        case "publish":
            return XmppPubSubConstants.Method.PUBLISH;
        case "retract":
            return XmppPubSubConstants.Method.RETRACT;
        default:
            break;
    }
    return null;
}
 
Example 3
Source Project: Whack   Source File: ExternalComponent.java    License: Apache License 2.0 6 votes vote down vote up
public void processPacket(final Packet packet) {
    threadPool.execute(new Runnable() {
        public void run() {
            if (packet instanceof IQ) {
                IQ iq = (IQ) packet;
                IQ.Type iqType = iq.getType();
                if (IQ.Type.result == iqType || IQ.Type.error == iqType) {
                    // The server got an answer to an IQ packet that was sent from the component
                    IQResultListener iqResultListener = resultListeners.remove(iq.getID());
                    resultTimeout.remove(iq.getID());
                    if (iqResultListener != null) {
                        try {
                            iqResultListener.receivedAnswer(iq);
                        }
                        catch (Exception e) {
                             manager.getLog().error("Error processing answer of remote entity", e);
                        }
                        return;
                    }
                }
            }
            component.processPacket(packet);
        }
    });
}
 
Example 4
Source Project: Openfire   Source File: PacketCopier.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed)
        throws PacketRejectedException {
    // Queue intercepted packet only if there are subscribers interested
    if (!subscribers.isEmpty()) {
        boolean queue = false;
        Class packetClass = packet.getClass();
        for (Subscription subscription : subscribers.values()) {
            if (subscription.isPresenceEnabled() && packetClass == Presence.class) {
                queue = true;
            }
            else if (subscription.isMessageEnabled() && packetClass == Message.class) {
                queue = true;
            }
            else if (subscription.isIQEnabled() && packetClass == IQ.class) {
                queue = true;
            }
        }
        if (queue) {
            // Queue packet with extra information and let the background thread process it
            packetQueue.add(new InterceptedPacket(packet, incoming, processed));
        }
    }
}
 
Example 5
Source Project: Openfire   Source File: PubSubModule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(Packet packet) {
    try {
        // Check if the packet is a disco request or a packet with namespace iq:register
        if (packet instanceof IQ) {
            if (engine.process(this, (IQ) packet) == null) {
                process((IQ) packet);
            }
        }
        else if (packet instanceof Presence) {
            engine.process(this, (Presence) packet);
        }
        else {
            engine.process(this, (Message) packet);
        }
    }
    catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        if (packet instanceof IQ) {
            // Send internal server error
            IQ reply = IQ.createResultIQ((IQ) packet);
            reply.setError(PacketError.Condition.internal_server_error);
            send(reply);
        }
    }
}
 
Example 6
Source Project: Openfire   Source File: NodeSubscription.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Configures the subscription based on the sent {@link DataForm} included in the IQ
 * packet sent by the subscriber. If the subscription was pending of configuration
 * then the last published item is going to be sent to the subscriber.<p>
 *
 * The originalIQ parameter may be {@code null} when using this API internally. When no
 * IQ packet was sent then no IQ result will be sent to the sender. The rest of the
 * functionality is the same.
 *
 * @param originalIQ the IQ packet sent by the subscriber to configure his subscription or
 *        null when using this API internally.
 * @param options the data form containing the new subscription configuration.
 */
public void configure(IQ originalIQ, DataForm options) {
    boolean wasUnconfigured = isConfigurationPending();
    // Change the subscription configuration based on the completed form
    configure(options);
    if (originalIQ != null) {
        // Return success response
        node.getService().send(IQ.createResultIQ(originalIQ));
    }

    if (wasUnconfigured) {
        // If subscription is pending then send notification to node owners
        // asking to approve the now configured subscription
        if (isAuthorizationPending()) {
            sendAuthorizationRequest();
        }

        // Send last published item (if node is leaf node and subscription status is ok)
        if (node.isSendItemSubscribe() && isActive()) {
            PublishedItem lastItem = node.getLastPublishedItem();
            if (lastItem != null) {
                sendLastPublishedItem(lastItem);
            }
        }
    }
}
 
Example 7
Source Project: Openfire   Source File: NodeSubscription.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sends the current subscription status to the user that tried to create a subscription to
 * the node. The subscription status is sent to the subsciber after the subscription was
 * created or if the subscriber tries to subscribe many times and the node does not support
 * multpiple subscriptions.
 *
 * @param originalRequest the IQ packet sent by the subscriber to create the subscription.
 */
void sendSubscriptionState(IQ originalRequest) {
    IQ result = IQ.createResultIQ(originalRequest);
    Element child = result.setChildElement("pubsub", "http://jabber.org/protocol/pubsub");
    Element entity = child.addElement("subscription");
    if (!node.isRootCollectionNode()) {
        entity.addAttribute("node", node.getUniqueIdentifier().getNodeId());
    }
    entity.addAttribute("jid", getJID().toString());
    if (node.isMultipleSubscriptionsEnabled()) {
        entity.addAttribute("subid", getID());
    }
    entity.addAttribute("subscription", getState().name());
    Element subscribeOptions = entity.addElement("subscribe-options");
    if (node.isSubscriptionConfigurationRequired() && isConfigurationPending()) {
        subscribeOptions.addElement("required");
    }
    // Send the result
    node.getService().send(result);
}
 
Example 8
Source Project: Openfire   Source File: LeafNode.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sends an IQ result with the list of items published to the node. Item ID and payload
 * may be included in the result based on the node configuration.
 *
 * @param originalRequest the IQ packet sent by a subscriber (or anyone) to get the node items.
 * @param publishedItems the list of published items to send to the subscriber.
 * @param forceToIncludePayload true if the item payload should be include if one exists. When
 *        false the decision is up to the node.
 */
void sendPublishedItems(IQ originalRequest, List<PublishedItem> publishedItems,
        boolean forceToIncludePayload) {
    IQ result = IQ.createResultIQ(originalRequest);
    Element pubsubElem = result.setChildElement("pubsub", "http://jabber.org/protocol/pubsub");
    Element items = pubsubElem.addElement("items");
    items.addAttribute("node", nodeID);
    
    for (PublishedItem publishedItem : publishedItems) {
        Element item = items.addElement("item");
        if (isItemRequired()) {
            item.addAttribute("id", publishedItem.getID());
        }
        if ((forceToIncludePayload || isPayloadDelivered()) &&
                publishedItem.getPayload() != null) {
            item.add(publishedItem.getPayload().createCopy());
        }
    }
    // Send the result
    getService().send(result);
}
 
Example 9
Source Project: Openfire   Source File: Node.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sends the list of affiliations with the node to the owner that sent the IQ
 * request.
 *
 * @param iqRequest IQ request sent by an owner of the node.
 */
void sendAffiliations(IQ iqRequest) {
    IQ reply = IQ.createResultIQ(iqRequest);
    Element childElement = iqRequest.getChildElement().createCopy();
    reply.setChildElement(childElement);
    Element affiliations = childElement.element("affiliations");

    for (NodeAffiliate affiliate : affiliates) {
        if (affiliate.getAffiliation() == NodeAffiliate.Affiliation.none) {
            continue;
        }
        Element entity = affiliations.addElement("affiliation");
        entity.addAttribute("jid", affiliate.getJID().toString());
        entity.addAttribute("affiliation", affiliate.getAffiliation().name());
    }
    // Send reply
    getService().send(reply);
}
 
Example 10
Source Project: Openfire   Source File: Node.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sends the list of subscriptions with the node to the owner that sent the IQ
 * request.
 *
 * @param iqRequest IQ request sent by an owner of the node.
 */
void sendSubscriptions(IQ iqRequest) {
    IQ reply = IQ.createResultIQ(iqRequest);
    Element childElement = iqRequest.getChildElement().createCopy();
    reply.setChildElement(childElement);
    Element subscriptions = childElement.element("subscriptions");

    for (NodeAffiliate affiliate : affiliates) {
        for (NodeSubscription subscription : affiliate.getSubscriptions()) {
            if (subscription.isAuthorizationPending()) {
                continue;
            }
            Element entity = subscriptions.addElement("subscription");
            entity.addAttribute("jid", subscription.getJID().toString());
            //entity.addAttribute("affiliation", affiliate.getAffiliation().name());
            entity.addAttribute("subscription", subscription.getState().name());
            if (isMultipleSubscriptionsEnabled()) {
                entity.addAttribute("subid", subscription.getID());
            }
        }
    }
    // Send reply
    getService().send(reply);
}
 
Example 11
Source Project: jicofo   Source File: ShutdownTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Try to join existing conference - must be allowed
 */
@Test
public void testJoinExistingConferenceDuringShutdown()
    throws Exception
{
    // initiate shutdown
    testShutdownAllowed();

    // Request for active conference - should reply with ready
    ConferenceIq activeConfRequest = new ConferenceIq();
    activeConfRequest.setRoom(roomName);

    IQ result = focusComponent.handleIQSetImpl(
        IQUtils.convert(activeConfRequest));

    assertEquals(result.toXML(), IQ.Type.result, result.getType());

    org.jivesoftware.smack.packet.IQ smackResult
        = IQUtils.convert(result);

    assertTrue(smackResult instanceof ConferenceIq);
    assertEquals(true, ((ConferenceIq)smackResult).isReady());
}
 
Example 12
Source Project: Openfire   Source File: MulticastRouter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sends pending packets of the requested domain but first try to discover if remote server
 * supports multicast service. If we already have cached information about the requested
 * domain then just deliver the packet.
 *
 * @param domain the domain that has pending packets to be sent.
 */
private void sendToRemoteEntity(String domain) {
    // Check if there is cached information about the requested domain
    String multicastService = cache.get(domain);
    if (multicastService != null) {
        sendToRemoteServer(domain, multicastService);
    }
    else {
        // No cached information was found so discover if remote server
        // supports JEP-33 (Extended Stanza Addressing). The reply to the disco
        // request is going to be process in #receivedAnswer(IQ packet)
        IQ iq = new IQ(IQ.Type.get);
        iq.setFrom(server.getServerInfo().getXMPPDomain());
        iq.setTo(domain);
        iq.setChildElement("query", "http://jabber.org/protocol/disco#info");
        // Indicate that we are searching for info of the specified domain
        nodes.put(domain, new CopyOnWriteArrayList<String>());
        // Send the disco#info request to the remote server or component. The reply will be
        // processed by the IQResultListener (interface that this class implements)
        iqRouter.addIQResultListener(iq.getID(), this);
        iqRouter.route(iq);
    }
}
 
Example 13
Source Project: Openfire   Source File: SoftwareVersionManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void resourceBound(Session session) {
     // The server should not send requests to the client before the client session
    // has been established (see IQSessionEstablishmentHandler). Sadly, Openfire
    // does not provide a hook for this. For now, the resource bound event is
    // used instead (which should be immediately followed by session establishment).
    TaskEngine.getInstance().submit( () -> {
        try {
            Thread.sleep(5000); // Let time pass for the session establishment to have occurred.

            IQ versionRequest = new IQ(IQ.Type.get);
            versionRequest.setTo(session.getAddress());
            versionRequest.setFrom(session.getServerName());
            versionRequest.setChildElement("query", "jabber:iq:version");
            session.process(versionRequest);
        } catch (Exception e) {
            Log.error("Exception while trying to query a client for its software version.", e);;
        }
    } );
    
}
 
Example 14
Source Project: Openfire   Source File: UserManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void isRegisteredUserWillReturnFalseForATimeout() {

    final AtomicReference<IQResultListener> iqListener = new AtomicReference<>();
    doAnswer(invocationOnMock -> {
        final IQResultListener listener = invocationOnMock.getArgument(1);
        iqListener.set(listener);
        return null;
    }).when(iqRouter).addIQResultListener(any(), any(), anyLong());

    doAnswer(invocationOnMock -> {
        final IQ iq = invocationOnMock.getArgument(0);
        iqListener.get().answerTimeout(iq.getID());
        return null;
    }).when(iqRouter).route(any());

    final boolean result = userManager.isRegisteredUser(new JID(USER_ID, REMOTE_XMPP_DOMAIN, null));

    assertThat(result, is(false));
    verify(iqRouter).route(any());
}
 
Example 15
Source Project: jicofo   Source File: ShutdownTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Try shutdown from wrong jid
 */
@Test
public void testShutdownForbidden()
    throws Exception
{
    shutdownStartedExpected = false;
    ShutdownIQ shutdownIQ = ShutdownIQ.createGracefulShutdownIQ();

    shutdownIQ.setFrom(JidCreate.from("randomJid1234"));

    IQ result = focusComponent.handleIQSetImpl(
            IQUtils.convert(shutdownIQ));

    assertEquals(result.toXML(), IQ.Type.error, result.getType());
    assertEquals(PacketError.Condition.forbidden,
            result.getError().getCondition());
}
 
Example 16
Source Project: Openfire   Source File: IQSharedGroupHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException {
    IQ result = IQ.createResultIQ(packet);
    String username = packet.getFrom().getNode();
    if (!serverName.equals(packet.getFrom().getDomain()) || username == null) {
        // Users of remote servers are not allowed to get their "shared groups". Users of
        // remote servers cannot have shared groups in this server.
        // Besides, anonymous users do not belong to shared groups so answer an error
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.not_allowed);
        return result;
    }

    Collection<Group> groups = rosterManager.getSharedGroups(username);
    Element sharedGroups = result.setChildElement("sharedgroup",
            "http://www.jivesoftware.org/protocol/sharedgroup");
    for (Group sharedGroup : groups) {
        String displayName = sharedGroup.getProperties().get("sharedRoster.displayName");
        if (displayName != null) {
            sharedGroups.addElement("group").setText(displayName);
        }
    }
    return result;
}
 
Example 17
Source Project: onos   Source File: XmppPubSubControllerImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void notifyListeners(IQ iq) {
    XmppPubSubConstants.Method method = getMethod(iq);
    checkNotNull(method);
    switch (method) {
        case SUBSCRIBE:
            XmppSubscribe subscribe = new XmppSubscribe(iq);
            notifyXmppSubscribe(subscribe);
            break;
        case UNSUBSCRIBE:
            XmppUnsubscribe unsubscribe = new XmppUnsubscribe(iq);
            notifyXmppUnsubscribe(unsubscribe);
            break;
        case PUBLISH:
            XmppPublish publish = new XmppPublish(iq);
            notifyXmppPublish(publish);
            break;
        case RETRACT:
            XmppRetract retract = new XmppRetract(iq);
            notifyXmppRetract(retract);
            break;
        default:
            break;
    }
}
 
Example 18
Source Project: Openfire   Source File: ClientSessionConnection.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * If the Connection Manager or the Client requested to close the connection then just do
 * nothing. But if the server originated the request to close the connection then we need
 * to send to the Connection Manager a packet letting him know that the Client Session needs
 * to be terminated.
 */
@Override
public void closeVirtualConnection() {
    // Figure out who requested the connection to be closed
    StreamID streamID = session.getStreamID();
    if (multiplexerManager.getClientSession(connectionManagerName, streamID) == null) {
        // Client or Connection manager requested to close the session
        // Do nothing since it has already been removed and closed
    }
    else {
        ConnectionMultiplexerSession multiplexerSession =
                multiplexerManager.getMultiplexerSession(connectionManagerName,streamID);
        if (multiplexerSession != null) {
            // Server requested to close the client session so let the connection manager
            // know that he has to finish the client session
            IQ closeRequest = new IQ(IQ.Type.set);
            closeRequest.setFrom(serverName);
            closeRequest.setTo(connectionManagerName);
            Element child = closeRequest.setChildElement("session",
                    "http://jabber.org/protocol/connectionmanager");
            child.addAttribute("id", streamID.getID());
            child.addElement("close");
            multiplexerSession.process(closeRequest);
        }
    }
}
 
Example 19
Source Project: Openfire   Source File: UserManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void isRegisteredUserWillReturnFalseForUnknownRemoteUsers() {

    final AtomicReference<IQResultListener> iqListener = new AtomicReference<>();
    doAnswer(invocationOnMock -> {
        final IQResultListener listener = invocationOnMock.getArgument(1);
        iqListener.set(listener);
        return null;
    }).when(iqRouter).addIQResultListener(any(), any(), anyLong());

    doAnswer(invocationOnMock -> {
        final IQ iq = invocationOnMock.getArgument(0);
        final Element childElement = iq.getChildElement();
        final IQ response = IQ.createResultIQ(iq);
        response.setChildElement(childElement.createCopy());
        response.setError(new PacketError(PacketError.Condition.item_not_found, PacketError.Condition.item_not_found.getDefaultType()));
        iqListener.get().receivedAnswer(response);
        return null;
    }).when(iqRouter).route(any());

    final boolean result = userManager.isRegisteredUser(new JID(USER_ID, REMOTE_XMPP_DOMAIN, null));

    assertThat(result, is(false));
    verify(iqRouter).route(any());
}
 
Example 20
Source Project: openfire-ofmeet-plugin   Source File: JitsiJicofoWrapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void componentInfoReceived( final IQ iq )
{
    Log.trace( "Component info received: {} ", iq );
    final Iterator<Element> iterator = iq.getChildElement().elementIterator( "identity" );
    while ( iterator.hasNext() )
    {
        if ( "JitsiVideobridge".equals( iterator.next().attributeValue( "name" )) )
        {
            Log.info( "Detected a Jitsi Videobridge component: {}.", iq.getFrom() );
            jvbComponents.add( iq.getFrom() );
        }
    }
}
 
Example 21
Source Project: onos   Source File: XmppValidator.java    License: Apache License 2.0 5 votes vote down vote up
public void validate(Packet packet) throws XmppValidationException {
    validateBasicXmpp(packet);
    Element root = packet.getElement();
    if (root.getName().equals(XmppConstants.IQ_QNAME)) {
        validateIQ((IQ) packet);
    } else if (root.getName().equals(XmppConstants.MESSAGE_QNAME)) {
        validateMessage((Message) packet);
    } else if (root.getName().equals(XmppConstants.PRESENCE_QNAME)) {
        validatePresence((Presence) packet);
    }
}
 
Example 22
Source Project: onos   Source File: XmppPublish.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor for XmppPublish class.
 * @param iq XMPP IQ stanza, which XmppPublish is based on.
 */
public XmppPublish(IQ iq) {
    super(iq.getElement());
    this.jabberId = this.fromJID.toString();
    this.nodeID = this.getChildElement().element("publish").attribute("node").getValue();
    this.item = this.getChildElement().element("publish").element("item");
    this.itemID = this.item.attribute("id").getValue();
    this.itemEntry = this.item.element("entry");
    this.itemEntryNamespace = this.itemEntry.getNamespaceURI();
}
 
Example 23
Source Project: Openfire   Source File: LocalMUCRoom.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void send(@Nonnull Packet packet, @Nonnull MUCRole sender) {
    if (packet instanceof Message) {
        broadcast((Message)packet, sender);
    }
    else if (packet instanceof Presence) {
        broadcastPresence((Presence)packet, false, sender);
    }
    else if (packet instanceof IQ) {
        IQ reply = IQ.createResultIQ((IQ) packet);
        reply.setChildElement(((IQ) packet).getChildElement());
        reply.setError(PacketError.Condition.bad_request);
        router.route(reply);
    }
}
 
Example 24
Source Project: Openfire   Source File: MulticastRouter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the Element that contains the multiple recipients.
 *
 * @param packet packet containing the multiple recipients.
 * @return the Element that contains the multiple recipients.
 */
private Element getAddresses(Packet packet) {
    if (packet instanceof IQ) {
        return ((IQ) packet).getChildElement().element("addresses");
    }
    else {
        return packet.getElement().element("addresses");
    }
}
 
Example 25
Source Project: Openfire   Source File: SoftwareServerVersionManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sessionCreated(Session session) {
    try {
        IQ versionRequest = new IQ(IQ.Type.get);
        versionRequest.setTo(session.getAddress());
        versionRequest.setFrom(session.getServerName());
        versionRequest.setChildElement("query", "jabber:iq:version");
        session.process(versionRequest);
    } catch (Exception e) {
        Log.error("Exception while trying to query a server for its software version.", e);;
    }
   
}
 
Example 26
Source Project: Openfire   Source File: EntityCapabilitiesManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether or not the packet received from a disco#info result
 * was valid by comparing its 'ver' hash (identites+features encapsulated
 * hash) with the 'ver' hash of the original caps packet that the
 * disco#info query was sent on behalf of.
 * 
 * @param packet the disco#info result packet.
 * @return true if the packet's generated 'ver' hash matches the 'ver'
 *         hash of the original caps packet.
 */
private boolean isValid(IQ packet) {
    if (packet.getType() != IQ.Type.result)
        return false;

    final EntityCapabilities original = verAttributes.get(packet.getID());
    if (original == null) {
        return false;
    }
    final String newVerHash = generateVerHash(packet, original.getHashAttribute());

    return newVerHash.equals(original.getVerAttribute());
}
 
Example 27
Source Project: Openfire   Source File: InternalComponentManager.java    License: Apache License 2.0 5 votes vote down vote up
void notifyComponentInfo(IQ iq) {
    for (ComponentEventListener listener : listeners) {
        try {
            listener.componentInfoReceived(iq);
        } catch (Exception e) {
            Log.warn("An exception occurred while dispatching a 'componentInfoReceived' event!", e);
        }
    }
}
 
Example 28
Source Project: Openfire   Source File: EntityCapabilitiesManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void receivedAnswer(IQ packet) {
    String packetId = packet.getID();

    if (isValid(packet)) {
        // The packet was validated, so it can be added to the Entity
        // Capabilities cache map.

        // Add the resolved identities and features to the entity 
        // EntityCapabilitiesManager.capabilities object and add it 
        // to the cache map...
        EntityCapabilities caps = verAttributes.get(packetId);

        // Store identities.
        List<String> identities = getIdentitiesFrom(packet);
        for (String identity : identities) {
            caps.addIdentity(identity);
        }

        // Store features.
        List<String> features = getFeaturesFrom(packet);
        for (String feature : features) {
            caps.addFeature(feature);
        }

        Log.trace( "Received response to querying 'ver'. Caps now recognized. Received response from: {}", packet.getFrom() );
        registerCapabilities( packet.getFrom(), caps );
    }

    // Remove cached 'ver' attribute.
    verAttributes.remove(packetId);
}
 
Example 29
Source Project: Openfire   Source File: EntityCapabilitiesManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Extracts a list of features from an IQ packet.
 * 
 * @param packet the packet
 * @return a list of features
 */
private static List<String> getFeaturesFrom(IQ packet) {
    List<String> discoFeatures = new ArrayList<>();
    Element query = packet.getChildElement();
    Iterator<Element> featuresIterator = query.elementIterator("feature");
    if (featuresIterator != null) {
        while (featuresIterator.hasNext()) {
            Element featureElement = featuresIterator.next();
            String discoFeature = featureElement.attributeValue("var");

            discoFeatures.add(discoFeature);
        }
    }
    return discoFeatures;
}
 
Example 30
Source Project: Openfire   Source File: IQEntityTimeHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIQ() {
    IQEntityTimeHandler iqEntityTimeHandler = new IQEntityTimeHandler();
    IQ input = new IQ(IQ.Type.get, "1");
    IQ result = iqEntityTimeHandler.handleIQ(input);
    assertEquals(result.getChildElement().getName(), "time");
    assertEquals(result.getChildElement().getNamespace().getText(), "urn:xmpp:time");
    assertEquals(result.getChildElement().content().size(), 2);
    assertTrue(result.getChildElement().content().get(0) instanceof Element);
    assertTrue(result.getChildElement().content().get(1) instanceof Element);
    assertEquals(((Element) result.getChildElement().content().get(0)).getName(), "tzo");
    assertEquals(((Element) result.getChildElement().content().get(1)).getName(), "utc");
}