Java Code Examples for org.jivesoftware.smack.roster.packet.RosterPacket#addRosterItem()

The following examples show how to use org.jivesoftware.smack.roster.packet.RosterPacket#addRosterItem() . 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: 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 2
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 3
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 4
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 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: 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 7
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 8
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 9
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 10
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 11
Source File: Roster.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new roster item. The server will asynchronously update the roster with the subscription status.
 * <p>
 * There will be no presence subscription request. Consider using
 * {@link #createItemAndRequestSubscription(BareJid, String, String[])} if you also want to request a presence
 * subscription from the contact.
 * </p>
 *
 * @param jid the XMPP address of the contact (e.g. [email protected])
 * @param name the nickname of the user.
 * @param groups the list of group names the entry will belong to, or <code>null</code> if the the roster entry won't
 *        belong to a group.
 * @throws NoResponseException if there was no response from the server.
 * @throws XMPPErrorException if an XMPP exception occurs.
 * @throws NotLoggedInException If not logged in.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @since 4.4.0
 */
public void createItem(BareJid jid, String name, String[] groups) throws NotLoggedInException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    final XMPPConnection connection = getAuthenticatedConnectionOrThrow();

    // Create and send roster entry creation packet.
    RosterPacket rosterPacket = new RosterPacket();
    rosterPacket.setType(IQ.Type.set);
    RosterPacket.Item item = new RosterPacket.Item(jid, name);
    if (groups != null) {
        for (String group : groups) {
            if (group != null && group.trim().length() > 0) {
                item.addGroupName(group);
            }
        }
    }
    rosterPacket.addRosterItem(item);
    connection.createStanzaCollectorAndSend(rosterPacket).nextResultOrThrow();
}
 
Example 12
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 13
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();
}