org.jivesoftware.smack.roster.packet.RosterPacket Java Examples

The following examples show how to use org.jivesoftware.smack.roster.packet.RosterPacket. 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 File: RosterGroup.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Removes a roster entry from this group. If the entry does not belong to any other group
 * then it will be considered as unfiled, therefore it will be added to the list of unfiled
 * entries.
 * Note that this is a synchronous call -- Smack must wait for the server
 * to receive the updated roster.
 *
 * @param entry a roster entry.
 * @throws XMPPErrorException if an error occurred while trying to remove the entry from the group.
 * @throws NoResponseException if there was no response from the server.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public void removeEntry(RosterEntry entry) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    // Only remove the entry if it's in the entry list.
    // Remove the entry locally, if we wait for RosterPacketListenerProcess>>Packet(Packet)
    // to take place the entry will exist in the group until a packet is received from the
    // server.
    synchronized (entries) {
        if (entries.contains(entry)) {
            RosterPacket packet = new RosterPacket();
            packet.setType(IQ.Type.set);
            RosterPacket.Item item = RosterEntry.toRosterItem(entry);
            item.removeGroupName(this.getName());
            packet.addRosterItem(item);
            // Wait up to a certain number of seconds for a reply from the server.
            connection().createStanzaCollectorAndSend(packet).nextResultOrThrow();
        }
    }
}
 
Example #2
Source File: RosterTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that roster pushes with invalid from are ignored.
 * @throws XmppStringprepException if the provided string is invalid.
 *
 * @see <a href="http://xmpp.org/rfcs/rfc6121.html#roster-syntax-actions-push">RFC 6121, Section 2.1.6</a>
 */
@Test
public void testIgnoreInvalidFrom() throws XmppStringprepException {
    final BareJid spammerJid = JidCreate.entityBareFrom("[email protected]");
    RosterPacket packet = new RosterPacket();
    packet.setType(Type.set);
    packet.setTo(connection.getUser());
    packet.setFrom(JidCreate.entityBareFrom("[email protected]"));
    packet.addRosterItem(new Item(spammerJid, "Cool products!"));

    final String requestId = packet.getStanzaId();
    // Simulate receiving the roster push
    connection.processStanza(packet);

    // Smack should reply with an error IQ
    ErrorIQ errorIQ = connection.getSentPacket();
    assertEquals(requestId, errorIQ.getStanzaId());
    assertEquals(Condition.service_unavailable, errorIQ.getError().getCondition());

    assertNull("Contact was added to roster", Roster.getInstanceFor(connection).getEntry(spammerJid));
}
 
Example #3
Source File: RosterEntry.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the name associated with this entry.
 *
 * @param name the name.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public synchronized void setName(String name) throws NotConnectedException, NoResponseException, XMPPErrorException, InterruptedException {
    // Do nothing if the name hasn't changed.
    if (name != null && name.equals(getName())) {
        return;
    }

    RosterPacket packet = new RosterPacket();
    packet.setType(IQ.Type.set);

    // Create a new roster item with the current RosterEntry and the *new* name. Note that we can't set the name of
    // RosterEntry right away, as otherwise the updated event wont get fired, because equalsDeep would return true.
    packet.addRosterItem(toRosterItem(this, name));
    connection().createStanzaCollectorAndSend(packet).nextResultOrThrow();

    // We have received a result response to the IQ set, the name was successfully changed
    item.setName(name);
}
 
Example #4
Source File: Roster.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Removes a roster entry from the roster. The roster entry will also be removed from the
 * unfiled entries or from any roster group where it could belong and will no longer be part
 * of the roster. Note that this is a synchronous call -- Smack must wait for the server
 * to send an updated subscription status.
 *
 * @param entry a roster entry.
 * @throws XMPPErrorException if an XMPP error occurs.
 * @throws NotLoggedInException if not logged in.
 * @throws NoResponseException SmackException if there was no response from the server.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public void removeEntry(RosterEntry entry) throws NotLoggedInException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    final XMPPConnection connection = getAuthenticatedConnectionOrThrow();

    // Only remove the entry if it's in the entry list.
    // The actual removal logic takes place in RosterPacketListenerProcess>>Packet(Packet)
    if (!entries.containsKey(entry.getJid())) {
        return;
    }
    RosterPacket packet = new RosterPacket();
    packet.setType(IQ.Type.set);
    RosterPacket.Item item = RosterEntry.toRosterItem(entry);
    // Set the item type as REMOVE so that the server will delete the entry
    item.setItemType(RosterPacket.ItemType.remove);
    packet.addRosterItem(item);
    connection.createStanzaCollectorAndSend(packet).nextResultOrThrow();
}
 
Example #5
Source File: RosterTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Remove all roster entries by iterating trough {@link Roster#getEntries()}
 * and simulating receiving roster pushes from the server.
 *
 * @param connection the dummy connection of which the provided roster belongs to.
 * @param roster the roster (or buddy list) which should be initialized.
 */
public static void removeAllRosterEntries(DummyConnection connection, Roster roster) {
    for (RosterEntry entry : roster.getEntries()) {
        // prepare the roster push packet
        final RosterPacket rosterPush = new RosterPacket();
        rosterPush.setType(Type.set);
        rosterPush.setTo(connection.getUser());

        // prepare the buddy's item entry which should be removed
        final RosterPacket.Item item = new RosterPacket.Item(entry.getJid(), entry.getName());
        item.setItemType(ItemType.remove);
        rosterPush.addRosterItem(item);

        // simulate receiving the roster push
        connection.processStanza(rosterPush);
    }
}
 
Example #6
Source File: ContactList.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a single user to the ContactList.
 *
 * @param entry the <code>RosterEntry</code> of the the user.
 */
private void addUser(RosterEntry entry) {
    ContactItem newContactItem = UIComponentRegistry.createContactItem(entry.getName(), null, entry.getJid());

    if (entry.getType() == RosterPacket.ItemType.none || entry.getType() == RosterPacket.ItemType.from) {
        // Ignore, since the new user is pending to be added.
        for (RosterGroup group : entry.getGroups()) {
            ContactGroup contactGroup = getContactGroup(group.getName());
            if (contactGroup == null) {
                contactGroup = addContactGroup(group.getName());
            }

            boolean isPending = entry.getType() == RosterPacket.ItemType.none || entry.getType() == RosterPacket.ItemType.from
                && entry.isSubscriptionPending();
            if (isPending) {
                contactGroup.setVisible(true);
            }
            contactGroup.addContactItem(newContactItem);

        }
        return;
    }
    else {
        moveToOffline(newContactItem);
    }

    // Update users icon
    Presence presence = Roster.getInstanceFor( SparkManager.getConnection() ).getPresence(entry.getJid());
    try {
        updateUserPresence(presence);
    }
    catch (Exception e) {
        Log.error(e);
    }
}
 
Example #7
Source File: RosterPacketProvider.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public RosterPacket parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException {
    RosterPacket roster = new RosterPacket();
    String version = parser.getAttributeValue("", "ver");
    roster.setVersion(version);

    outerloop: while (true) {
        XmlPullParser.Event eventType = parser.next();
        switch (eventType) {
        case START_ELEMENT:
            String startTag = parser.getName();
            switch (startTag) {
            case "item":
                RosterPacket.Item item = parseItem(parser);
                roster.addRosterItem(item);
                break;
            }
            break;
        case END_ELEMENT:
            String endTag = parser.getName();
            switch (endTag) {
            case IQ.QUERY_ELEMENT:
                if (parser.getDepth() == initialDepth) {
                    break outerloop;
                }
            }
            break;
        default:
            // Catch all for incomplete switch (MissingCasesInEnumSwitch) statement.
            break;
        }
    }
    return roster;
}
 
Example #8
Source File: RosterGroup.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a roster entry to this group. If the entry was unfiled then it will be removed from
 * the unfiled list and will be added to this group.
 * Note that this is a synchronous call -- Smack must wait for the server
 * to receive the updated roster.
 *
 * @param entry a roster entry.
 * @throws XMPPErrorException if an error occurred while trying to add the entry to the group.
 * @throws NoResponseException if there was no response from the server.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public void addEntry(RosterEntry entry) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    // Only add the entry if it isn't already in the list.
    synchronized (entries) {
        if (!entries.contains(entry)) {
            RosterPacket packet = new RosterPacket();
            packet.setType(IQ.Type.set);
            RosterPacket.Item item = RosterEntry.toRosterItem(entry);
            item.addGroupName(getName());
            packet.addRosterItem(item);
            // Wait up to a certain number of seconds for a reply from the server.
            connection().createStanzaCollectorAndSend(packet).nextResultOrThrow();
        }
    }
}
 
Example #9
Source File: RosterGroup.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the name of the group. Changing the group's name is like moving all the group entries
 * of the group to a new group specified by the new name. Since this group won't have entries
 * it will be removed from the roster. This means that all the references to this object will
 * be invalid and will need to be updated to the new group specified by the new name.
 *
 * @param name the name of the group.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public void setName(String name) throws NotConnectedException, NoResponseException, XMPPErrorException, InterruptedException {
    synchronized (entries) {
        for (RosterEntry entry : entries) {
            RosterPacket packet = new RosterPacket();
            packet.setType(IQ.Type.set);
            RosterPacket.Item item = RosterEntry.toRosterItem(entry);
            item.removeGroupName(this.name);
            item.addGroupName(name);
            packet.addRosterItem(item);
            connection().createStanzaCollectorAndSend(packet).nextResultOrThrow();
        }
    }
}
 
Example #10
Source File: Roster.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Ignore ItemTypes as of RFC 6121, 2.1.2.5.
 *
 * This is used by {@link RosterPushListener} and {@link RosterResultListener}.
 * */
private static boolean hasValidSubscriptionType(RosterPacket.Item item) {
    switch (item.getItemType()) {
        case none:
        case from:
        case to:
        case both:
            return true;
        default:
            return false;
    }
}
 
Example #11
Source File: Roster.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Reloads the entire roster from the server. This is an asynchronous operation,
 * which means the method will return immediately, and the roster will be
 * reloaded at a later point when the server responds to the reload request.
 * @throws NotLoggedInException If not logged in.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public void reload() throws NotLoggedInException, NotConnectedException, InterruptedException {
    final XMPPConnection connection = getAuthenticatedConnectionOrThrow();

    RosterPacket packet = new RosterPacket();
    if (rosterStore != null && isRosterVersioningSupported()) {
        packet.setVersion(rosterStore.getRosterVersion());
    }
    rosterState = RosterState.loading;

    SmackFuture<IQ, Exception> future = connection.sendIqRequestAsync(packet);

    future.onSuccess(new RosterResultListener()).onError(new ExceptionCallback<Exception>() {

        @Override
        public void processException(Exception exception) {
            rosterState = RosterState.uninitialized;
            Level logLevel;
            if (exception instanceof NotConnectedException) {
                logLevel = Level.FINE;
            } else {
                logLevel = Level.SEVERE;
            }
            LOGGER.log(logLevel, "Exception reloading roster", exception);
            for (RosterLoadedListener listener : rosterLoadedListeners) {
                listener.onRosterLoadingFailed(exception);
            }
        }

    });
}
 
Example #12
Source File: RosterEntry.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a roster entry with the given name to a roster item. As per RFC 6121 ยง 2.1.2.2., clients MUST NOT include
 * the 'ask' attribute, thus set {@code includeAskAttribute} to {@code false}.
 *
 * @param entry the roster entry.
 * @param name the name of the roster item.
 * @param includeAskAttribute whether or not to include the 'ask' attribute.
 * @return the roster item.
 */
private static RosterPacket.Item toRosterItem(RosterEntry entry, String name, boolean includeAskAttribute) {
    RosterPacket.Item item = new RosterPacket.Item(entry.getJid(), name);
    item.setItemType(entry.getType());
    if (includeAskAttribute) {
        item.setSubscriptionPending(entry.isSubscriptionPending());
    }
    item.setApproved(entry.isApproved());
    // Set the correct group names for the item.
    for (RosterGroup group : entry.getGroups()) {
        item.addGroupName(group.getName());
    }
    return item;
}
 
Example #13
Source File: RosterTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        while (true) {
            final Stanza packet = connection.getSentPacket();
            if (packet instanceof RosterPacket && ((IQ) packet).getType() == Type.set) {
                final RosterPacket rosterRequest = (RosterPacket) packet;

                // Prepare and process the roster push
                final RosterPacket rosterPush = new RosterPacket();
                final Item item = rosterRequest.getRosterItems().iterator().next();
                if (item.getItemType() != ItemType.remove) {
                    item.setItemType(ItemType.none);
                }
                rosterPush.setType(Type.set);
                rosterPush.setTo(connection.getUser());
                rosterPush.addRosterItem(item);
                connection.processStanza(rosterPush);

                // Create and process the IQ response
                final IQ response = IQ.createResultIQ(rosterRequest);
                connection.processStanza(response);

                // Verify the roster update request
                if (rosterRequest.getRosterItemCount() != 1) {
                    throw new AssertionError("A roster set MUST contain one and only one <item/> element.");
                }
                verifyUpdateRequest(rosterRequest);
                break;
            }
        }
    }
    catch (Throwable e) {
        exception = e;
        fail(e.getMessage());
    }
}
 
Example #14
Source File: RosterVersioningTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that a non-empty roster result empties the store.
 * @throws SmackException if Smack detected an exceptional situation.
 * @throws XMPPException if an XMPP protocol error was received.
 * @throws XmppStringprepException if the provided string is invalid.
 */
@Test(timeout = 5000)
public void testOtherVersionStored() throws XMPPException, SmackException, XmppStringprepException {
    Item vaglafItem = vaglafItem();

    // We expect that the roster request is the only packet sent. This is not part of the specification,
    // but a shortcut in the test implementation.
    Stanza sentPacket = connection.getSentPacket();
    if (sentPacket instanceof RosterPacket) {
        RosterPacket sentRP = (RosterPacket) sentPacket;
        RosterPacket answer = new RosterPacket();
        answer.setStanzaId(sentRP.getStanzaId());
        answer.setType(Type.result);
        answer.setTo(sentRP.getFrom());

        answer.setVersion("newVersion");
        answer.addRosterItem(vaglafItem);

        rosterListener.reset();
        connection.processStanza(answer);
        rosterListener.waitUntilInvocationOrTimeout();
    } else {
        assertTrue("Expected to get a RosterPacket ", false);
    }

    Roster roster = Roster.getInstanceFor(connection);
    assertEquals("Size of roster", 1, roster.getEntries().size());
    RosterEntry entry = roster.getEntry(vaglafItem.getJid());
    assertNotNull("Roster contains vaglaf entry", entry);
    assertEquals("vaglaf entry in roster equals the sent entry", vaglafItem, RosterEntry.toRosterItem(entry));

    RosterStore store = roster.getRosterStore();
    assertEquals("Size of store", 1, store.getEntries().size());
    Item item = store.getEntry(vaglafItem.getJid());
    assertNotNull("Store contains vaglaf entry", item);
    assertEquals("vaglaf entry in store equals the sent entry", vaglafItem, item);
}
 
Example #15
Source File: RosterVersioningTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
private static void populateStore(RosterStore store) throws IOException {
    store.addEntry(new RosterPacket.Item(JidCreate.entityBareFrom("[email protected]"), "geoff hurley"), "");

    RosterPacket.Item item = new RosterPacket.Item(JidCreate.entityBareFrom("[email protected]"), "joe stevens");
    item.addGroupName("friends");
    item.addGroupName("partners");
    store.addEntry(item, "");

    item = new RosterPacket.Item(JidCreate.entityBareFrom("[email protected]"), "higgins mcmann");
    item.addGroupName("all");
    item.addGroupName("friends");
    store.addEntry(item, "v96");
}
 
Example #16
Source File: RosterVersioningTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
private void answerWithEmptyRosterResult() {
    // We expect that the roster request is the only packet sent. This is not part of the specification,
    // but a shortcut in the test implementation.
    Stanza sentPacket = connection.getSentPacket();
    if (sentPacket instanceof RosterPacket) {
        final IQ emptyIQ = IQ.createResultIQ((RosterPacket) sentPacket);
        connection.processStanza(emptyIQ);
    } else {
        assertTrue("Expected to get a RosterPacket ", false);
    }
}
 
Example #17
Source File: ClientUtils.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
private static Contact.Subscription rosterToModelSubscription(
        boolean subscriptionPending, RosterPacket.ItemType type) {
    if (type == RosterPacket.ItemType.both ||
            type == RosterPacket.ItemType.to ||
            type == RosterPacket.ItemType.remove)
        return Contact.Subscription.SUBSCRIBED;

    if (subscriptionPending)
        return Contact.Subscription.PENDING;

    return Contact.Subscription.UNSUBSCRIBED;
}
 
Example #18
Source File: ContactList.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the users presence.
 *
 * @param presence the user to update.
 * @throws Exception if there is a problem while updating the user's presence.
 */
private synchronized void updateUserPresence(Presence presence) throws Exception {
    if (presence.getError() != null) {
        // We ignore this.
        return;
    }

    final Roster roster = Roster.getInstanceFor( SparkManager.getConnection() );

    final BareJid bareJID = presence.getFrom().asBareJid();

    RosterEntry entry = roster.getEntry(bareJID);
    boolean isPending = entry != null && (entry.getType() == RosterPacket.ItemType.none || entry.getType() == RosterPacket.ItemType.from)
        && entry.isSubscriptionPending();

    // If online, check to see if they are in the offline group.
    // If so, remove from offline group and add to all groups they
    // belong to.

    if (presence.getType() == Presence.Type.available && offlineGroup.getContactItemByJID(bareJID) != null || ( presence.getFrom().toString().contains( "workgroup." ) )) {
        changeOfflineToOnline(bareJID, entry, presence);
    }
    else if (presence.getType() == Presence.Type.available) {
        updateContactItemsPresence(presence, entry, bareJID);
    }
    else if (presence.getType() == Presence.Type.unavailable && !isPending) {
        // If not available, move to offline group.
        Presence rosterPresence = PresenceManager.getPresence(bareJID);
        if (!rosterPresence.isAvailable()) {
            moveToOfflineGroup(presence, bareJID);
        }
        else {
            updateContactItemsPresence(rosterPresence, entry, bareJID);
        }
    }
    
}
 
Example #19
Source File: QBFriendListHelper.java    From q-municate-android with Apache License 2.0 5 votes vote down vote up
private boolean isInvited(int userId) {
    QBRosterEntry rosterEntry = roster.getEntry(userId);
    if (rosterEntry == null) {
        return false;
    }
    boolean isSubscribedToUser = rosterEntry.getType() == RosterPacket.ItemType.from;
    boolean isBothSubscribed = rosterEntry.getType() == RosterPacket.ItemType.both;
    return isSubscribedToUser || isBothSubscribed;
}
 
Example #20
Source File: RosterTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize the roster according to the example in
 * <a href="http://xmpp.org/rfcs/rfc3921.html#roster-login"
 *     >RFC3921: Retrieving One's Roster on Login</a>.
 *
 * @throws SmackException if Smack detected an exceptional situation.
 * @throws XmppStringprepException if the provided string is invalid.
 */
private void initRoster() throws InterruptedException, SmackException, XmppStringprepException {
    roster.reload();
    while (true) {
        final Stanza sentPacket = connection.getSentPacket();
        if (sentPacket instanceof RosterPacket && ((IQ) sentPacket).getType() == Type.get) {
            // setup the roster get request
            final RosterPacket rosterRequest = (RosterPacket) sentPacket;
            assertSame("The <query/> element MUST NOT contain any <item/> child elements!",
                    0,
                    rosterRequest.getRosterItemCount());

            // prepare the roster result
            final RosterPacket rosterResult = new RosterPacket();
            rosterResult.setTo(connection.getUser());
            rosterResult.setType(Type.result);
            rosterResult.setStanzaId(rosterRequest.getStanzaId());

            // prepare romeo's roster entry
            final Item romeo = new Item(JidCreate.entityBareFrom("[email protected]"), "Romeo");
            romeo.addGroupName("Friends");
            romeo.setItemType(ItemType.both);
            rosterResult.addRosterItem(romeo);

            // prepare mercutio's roster entry
            final Item mercutio = new Item(JidCreate.entityBareFrom("[email protected]"), "Mercutio");
            mercutio.setItemType(ItemType.from);
            rosterResult.addRosterItem(mercutio);

            // prepare benvolio's roster entry
            final Item benvolio = new Item(JidCreate.entityBareFrom("[email protected]"), "Benvolio");
            benvolio.setItemType(ItemType.both);
            rosterResult.addRosterItem(benvolio);

            // simulate receiving the roster result and exit the loop
            connection.processStanza(rosterResult);
            break;
        }
    }
    roster.waitUntilLoaded();
    rosterListener.waitUntilInvocationOrTimeout();
}
 
Example #21
Source File: RosterTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Test if adding an user with an empty group is equivalent with providing
 * no group.
 *
 * @throws Throwable in case a throwable is thrown.
 * @see <a href="http://www.igniterealtime.org/issues/browse/SMACK-294">SMACK-294</a>
 */
@Test(timeout = 5000)
public void testAddEmptyGroupEntry() throws Throwable {
    // Constants for the new contact
    final BareJid contactJID = JidCreate.entityBareFrom("[email protected]");
    final String contactName = "Nurse";
    final String[] contactGroup = {""};

    // Setup
    assertNotNull("Can't get the roster from the provided connection!", roster);
    initRoster();
    rosterListener.reset();

    // Adding the new roster item
    final RosterUpdateResponder serverSimulator = new RosterUpdateResponder() {
        @Override
        void verifyUpdateRequest(final RosterPacket updateRequest) {
            final Item item = updateRequest.getRosterItems().iterator().next();
            assertSame("The provided JID doesn't match the requested!",
                    contactJID,
                    item.getJid());
            assertSame("The provided name doesn't match the requested!",
                    contactName,
                    item.getName());
            assertSame("Shouldn't provide an empty group element!",
                    0,
                    item.getGroupNames().size());

        }
    };
    serverSimulator.start();
    roster.createItemAndRequestSubscription(contactJID, contactName, contactGroup);
    serverSimulator.join();

    // Check if an error occurred within the simulator
    final Throwable exception = serverSimulator.getException();
    if (exception != null) {
        throw exception;
    }
    rosterListener.waitUntilInvocationOrTimeout();

    // Verify the roster entry of the new contact
    final RosterEntry addedEntry = roster.getEntry(contactJID);
    assertNotNull("The new contact wasn't added to the roster!", addedEntry);
    assertTrue("The roster listener wasn't invoked for the new contact!",
            rosterListener.getAddedAddresses().contains(contactJID));
    assertSame("Setup wrong name for the new contact!",
            contactName,
            addedEntry.getName());
    assertSame("Setup wrong default subscription status!",
            ItemType.none,
            addedEntry.getType());
    assertSame("The new contact shouldn't be member of any group!",
            0,
            addedEntry.getGroups().size());

    // Verify the unchanged roster items
    verifyRomeosEntry(roster.getEntry(JidCreate.entityBareFrom("[email protected]")));
    verifyMercutiosEntry(roster.getEntry(JidCreate.entityBareFrom("[email protected]")));
    verifyBenvoliosEntry(roster.getEntry(JidCreate.entityBareFrom("[email protected]")));
    assertSame("Wrong number of roster entries.", 4, roster.getEntries().size());
}
 
Example #22
Source File: DataFormProvider.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public DataForm parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException {
    DataForm.Type dataFormType = DataForm.Type.fromString(parser.getAttributeValue("", "type"));
    DataForm.Builder dataForm = DataForm.builder();
    dataForm.setType(dataFormType);

    String formType = null;

    outerloop: while (true) {
        XmlPullParser.Event eventType = parser.next();
        switch (eventType) {
        case START_ELEMENT:
            String name = parser.getName();
            String namespace = parser.getNamespace();
            XmlEnvironment elementXmlEnvironment = XmlEnvironment.from(parser, xmlEnvironment);
            switch (name) {
            case "instructions":
                dataForm.addInstruction(parser.nextText());
                break;
            case "title":
                dataForm.setTitle(parser.nextText());
                break;
            case "field":
                FormField formField = parseField(parser, elementXmlEnvironment, formType, dataFormType);

                TextSingleFormField hiddenFormTypeField = formField.asHiddenFormTypeFieldIfPossible();
                if (hiddenFormTypeField != null) {
                    if (formType != null) {
                        throw new SmackParsingException("Multiple hidden form type fields");
                    }
                    formType = hiddenFormTypeField.getValue();
                }

                dataForm.addField(formField);
                break;
            case "item":
                DataForm.Item item = parseItem(parser, elementXmlEnvironment, formType, dataFormType);
                dataForm.addItem(item);
                break;
            case "reported":
                DataForm.ReportedData reported = parseReported(parser, elementXmlEnvironment, formType, dataFormType);
                dataForm.setReportedData(reported);
                break;
            // See XEP-133 Example 32 for a corner case where the data form contains this extension.
            case RosterPacket.ELEMENT:
                if (namespace.equals(RosterPacket.NAMESPACE)) {
                    dataForm.addExtensionElement(RosterPacketProvider.INSTANCE.parse(parser));
                }
                break;
            // See XEP-141 Data Forms Layout
            case DataLayout.ELEMENT:
                if (namespace.equals(DataLayout.NAMESPACE)) {
                    dataForm.addExtensionElement(DataLayoutProvider.parse(parser));
                }
                break;
            }
            break;
        case END_ELEMENT:
            if (parser.getDepth() == initialDepth) {
                break outerloop;
            }
            break;
        default:
            // Catch all for incomplete switch (MissingCasesInEnumSwitch) statement.
            break;
        }
    }
    return dataForm.build();
}
 
Example #23
Source File: RosterTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Test deleting a roster item according to the example in
 * <a href="http://xmpp.org/rfcs/rfc3921.html#roster-delete"
 *     >RFC3921: Deleting a Roster Item</a>.
 * @throws Throwable if throwable is thrown.
 */
@Test
public void testDeleteRosterItem() throws Throwable {
    // The contact which should be deleted
    final BareJid contactJID = JidCreate.entityBareFrom("[email protected]");

    // Setup
    assertNotNull("Can't get the roster from the provided connection!", roster);
    initRoster();
    rosterListener.reset();

    // Delete a roster item
    final RosterUpdateResponder serverSimulator = new RosterUpdateResponder() {
        @Override
        void verifyUpdateRequest(final RosterPacket updateRequest) {
            final Item item = updateRequest.getRosterItems().iterator().next();
            assertEquals("The provided JID doesn't match the requested!",
                    contactJID,
                    item.getJid());
        }
    };
    serverSimulator.start();
    roster.removeEntry(roster.getEntry(contactJID));
    serverSimulator.join();

    // Check if an error occurred within the simulator
    final Throwable exception = serverSimulator.getException();
    if (exception != null) {
        throw exception;
    }
    rosterListener.waitUntilInvocationOrTimeout();

    // Verify
    final RosterEntry deletedEntry = roster.getEntry(contactJID);
    assertNull("The contact wasn't deleted from the roster!", deletedEntry);
    assertTrue("The roster listener wasn't invoked for the deleted contact!",
            rosterListener.getDeletedAddresses().contains(contactJID));
    verifyMercutiosEntry(roster.getEntry(JidCreate.entityBareFrom("[email protected]")));
    verifyBenvoliosEntry(roster.getEntry(JidCreate.entityBareFrom("[email protected]")));
    assertSame("Wrong number of roster entries (" + roster.getEntries() + ").",
            2,
            roster.getEntries().size());
}
 
Example #24
Source File: RosterTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Test updating a roster item according to the example in
 * <a href="http://xmpp.org/rfcs/rfc3921.html#roster-update"
 *     >RFC3921: Updating a Roster Item</a>.
 *
 * @throws Throwable in case a throwable is thrown.
 */
@Test
public void testUpdateRosterItem() throws Throwable {
    // Constants for the updated contact
    final BareJid contactJID = JidCreate.entityBareFrom("[email protected]");
    final String contactName = "Romeo";
    final String[] contactGroups = {"Friends", "Lovers"};

    // Setup
    assertNotNull("Can't get the roster from the provided connection!", roster);
    initRoster();
    rosterListener.reset();

    // Updating the roster item
    final RosterUpdateResponder serverSimulator = new RosterUpdateResponder() {
        @Override
        void verifyUpdateRequest(final RosterPacket updateRequest) {
            final Item item = updateRequest.getRosterItems().iterator().next();
            assertEquals("The provided JID doesn't match the requested!",
                    contactJID,
                    item.getJid());
            assertSame("The provided name doesn't match the requested!",
                    contactName,
                    item.getName());
            assertTrue("The updated contact doesn't belong to the requested groups ("
                    + contactGroups[0] + ")!",
                    item.getGroupNames().contains(contactGroups[0]));
            assertTrue("The updated contact doesn't belong to the requested groups ("
                    + contactGroups[1] + ")!",
                    item.getGroupNames().contains(contactGroups[1]));
            assertSame("The provided group number doesn't match the requested!",
                    contactGroups.length,
                    item.getGroupNames().size());
        }
    };
    serverSimulator.start();
    roster.createGroup(contactGroups[1]).addEntry(roster.getEntry(contactJID));
    serverSimulator.join();

    // Check if an error occurred within the simulator
    final Throwable exception = serverSimulator.getException();
    if (exception != null) {
        throw exception;
    }
    rosterListener.waitUntilInvocationOrTimeout();

    // Verify the roster entry of the updated contact
    final RosterEntry addedEntry = roster.getEntry(contactJID);
    assertNotNull("The contact was deleted from the roster!", addedEntry);
    assertTrue("The roster listener wasn't invoked for the updated contact!",
            rosterListener.getUpdatedAddresses().contains(contactJID));
    assertSame("Setup wrong name for the changed contact!",
            contactName,
            addedEntry.getName());
    assertTrue("The updated contact doesn't belong to the requested groups ("
            + contactGroups[0] + ")!",
            roster.getGroup(contactGroups[0]).contains(addedEntry));
    assertTrue("The updated contact doesn't belong to the requested groups ("
            + contactGroups[1] + ")!",
            roster.getGroup(contactGroups[1]).contains(addedEntry));
    assertSame("The updated contact should be member of two groups!",
            contactGroups.length,
            addedEntry.getGroups().size());

    // Verify the unchanged roster items
    verifyMercutiosEntry(roster.getEntry(JidCreate.entityBareFrom("[email protected]")));
    verifyBenvoliosEntry(roster.getEntry(JidCreate.entityBareFrom("[email protected]")));
    assertSame("Wrong number of roster entries (" + roster.getEntries() + ").",
            3,
            roster.getEntries().size());
}
 
Example #25
Source File: RosterTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Test adding a roster item according to the example in
 * <a href="http://xmpp.org/rfcs/rfc3921.html#roster-add"
 *     >RFC3921: Adding a Roster Item</a>.
 *
 * @throws Throwable in case a throwable is thrown.
 */
@Test
public void testAddRosterItem() throws Throwable {
    // Constants for the new contact
    final BareJid contactJID = JidCreate.entityBareFrom("[email protected]");
    final String contactName = "Nurse";
    final String[] contactGroup = {"Servants"};

    // Setup
    assertNotNull("Can't get the roster from the provided connection!", roster);
    initRoster();
    rosterListener.reset();

    // Adding the new roster item
    final RosterUpdateResponder serverSimulator = new RosterUpdateResponder() {
        @Override
        void verifyUpdateRequest(final RosterPacket updateRequest) {
            final Item item = updateRequest.getRosterItems().iterator().next();
            assertEquals("The provided JID doesn't match the requested!",
                    contactJID,
                    item.getJid());
            assertSame("The provided name doesn't match the requested!",
                    contactName,
                    item.getName());
            assertSame("The provided group number doesn't match the requested!",
                    contactGroup.length,
                    item.getGroupNames().size());
            assertSame("The provided group doesn't match the requested!",
                    contactGroup[0],
                    item.getGroupNames().iterator().next());
        }
    };
    serverSimulator.start();
    roster.createItemAndRequestSubscription(contactJID, contactName, contactGroup);
    serverSimulator.join();

    // Check if an error occurred within the simulator
    final Throwable exception = serverSimulator.getException();
    if (exception != null) {
        throw exception;
    }
    rosterListener.waitUntilInvocationOrTimeout();

    // Verify the roster entry of the new contact
    final RosterEntry addedEntry = roster.getEntry(contactJID);
    assertNotNull("The new contact wasn't added to the roster!", addedEntry);
    assertTrue("The roster listener wasn't invoked for the new contact!",
            rosterListener.getAddedAddresses().contains(contactJID));
    assertSame("Setup wrong name for the new contact!",
            contactName,
            addedEntry.getName());
    assertSame("Setup wrong default subscription status!",
            ItemType.none,
            addedEntry.getType());
    assertSame("The new contact should be member of exactly one group!",
            1,
            addedEntry.getGroups().size());
    assertSame("Setup wrong group name for the added contact!",
            contactGroup[0],
            addedEntry.getGroups().iterator().next().getName());

    // Verify the unchanged roster items
    verifyRomeosEntry(roster.getEntry(JidCreate.entityBareFrom("[email protected]")));
    verifyMercutiosEntry(roster.getEntry(JidCreate.entityBareFrom("[email protected]")));
    verifyBenvoliosEntry(roster.getEntry(JidCreate.entityBareFrom("[email protected]")));
    assertSame("Wrong number of roster entries.", 4, roster.getEntries().size());
}
 
Example #26
Source File: SubscriptionPreApprovalTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    try {
        while (true) {
            final Stanza packet = connection.getSentPacket();
            if (packet instanceof RosterPacket && ((IQ) packet).getType() == Type.set) {
                final RosterPacket rosterRequest = (RosterPacket) packet;

                // Prepare and process the roster push
                final RosterPacket rosterPush = new RosterPacket();
                final Item item = rosterRequest.getRosterItems().iterator().next();
                if (item.getItemType() != ItemType.remove) {
                    item.setItemType(ItemType.none);
                }
                rosterPush.setType(Type.set);
                rosterPush.setTo(connection.getUser());
                rosterPush.addRosterItem(item);
                connection.processStanza(rosterPush);

                // Create and process the IQ response
                final IQ response = IQ.createResultIQ(rosterRequest);
                connection.processStanza(response);

                // Verify the roster update request
                if (rosterRequest.getRosterItemCount() != 1) {
                    throw new AssertionError("A roster set MUST contain one and only one <item/> element.");
                }
                verifyRosterUpdateRequest(rosterRequest);
                break;
            }
            else if (packet instanceof Presence && ((Presence) packet).getType() == Presence.Type.subscribed) {
                final Presence approval = (Presence) packet;
                verifyPreApprovalRequest(approval);
            }
        }
    }
    catch (Throwable e) {
        exception = e;
        fail(e.getMessage());
    }
}
 
Example #27
Source File: UserFriendUtils.java    From q-municate-android with Apache License 2.0 4 votes vote down vote up
public static boolean isNoneFriend(QBRosterEntry rosterEntry) {
    return RosterPacket.ItemType.none.equals(rosterEntry.getType())
            || RosterPacket.ItemType.from.equals(rosterEntry.getType());
}
 
Example #28
Source File: SubscriptionPreApprovalTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Test
public void testPreApproveAndCreate() throws Throwable {
    final BareJid contactJID = JidCreate.bareFrom("[email protected]");
    final String contactName = "PreApproval";
    final String[] contactGroup = {};
    connection.enableStreamFeature(SubscriptionPreApproval.INSTANCE);

    final PreApproveAndCreateEntryResponder serverSimulator = new PreApproveAndCreateEntryResponder() {
        @Override
        void verifyRosterUpdateRequest(final RosterPacket updateRequest) {
            final Item item = updateRequest.getRosterItems().iterator().next();
            assertSame("The provided JID doesn't match the requested!",
                    contactJID,
                    item.getJid());
            assertSame("The provided name doesn't match the requested!",
                    contactName,
                    item.getName());
            assertSame("The provided group number doesn't match the requested!",
                    0,
                    item.getGroupNames().size());
        }

        @Override
        void verifyPreApprovalRequest(Presence preApproval) {
            assertSame("The provided name doesn't match the requested!",
                    contactJID,
                    preApproval.getTo());
            assertSame("The provided presence type is incorrect!",
                    Presence.Type.subscribed,
                    preApproval.getType());
        }
    };
    serverSimulator.start();
    roster.preApproveAndCreateEntry(contactJID, contactName, contactGroup);
    serverSimulator.join();

    // Check if an error occurred within the simulator
    final Throwable exception = serverSimulator.getException();
    if (exception != null) {
        throw exception;
    }
    rosterListener.waitUntilInvocationOrTimeout();

    // Verify the roster entry of the new contact
    final RosterEntry addedEntry = roster.getEntry(contactJID);
    assertNotNull("The new contact wasn't added to the roster!", addedEntry);
    assertTrue("The roster listener wasn't invoked for the new contact!",
            rosterListener.getAddedAddresses().contains(contactJID));
    assertSame("Setup wrong name for the new contact!",
            contactName,
            addedEntry.getName());
    assertSame("Setup wrong default subscription status!",
            ItemType.none,
            addedEntry.getType());
    assertSame("The new contact should be member of exactly one group!",
            0,
            addedEntry.getGroups().size());
}
 
Example #29
Source File: RosterEntry.java    From Smack with Apache License 2.0 4 votes vote down vote up
static RosterPacket.Item toRosterItem(RosterEntry entry, boolean includeAskAttribute) {
    return toRosterItem(entry, entry.getName(), includeAskAttribute);
}
 
Example #30
Source File: UserFriendUtils.java    From q-municate-android with Apache License 2.0 4 votes vote down vote up
public static boolean isOutgoingFriend(QBRosterEntry rosterEntry) {
    return RosterPacket.ItemStatus.subscribe.equals(rosterEntry.getStatus());
}