Java Code Examples for org.jxmpp.jid.impl.JidCreate#entityBareFrom()

The following examples show how to use org.jxmpp.jid.impl.JidCreate#entityBareFrom() . 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: ChatManager.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new public Conference Room.
 *
 * @param roomName    the name of the room.
 * @param serviceName the service name to use (ex.conference.jivesoftware.com)
 * @return the new ChatRoom created. If an error occured, null will be returned.
 */
public ChatRoom createConferenceRoom(Localpart roomName, DomainBareJid serviceName) {
    EntityBareJid roomAddress = JidCreate.entityBareFrom(roomName, serviceName);
    final MultiUserChat chatRoom = MultiUserChatManager.getInstanceFor( SparkManager.getConnection()).getMultiUserChat( roomAddress);

    final GroupChatRoom room = UIComponentRegistry.createGroupChatRoom(chatRoom);

    try {
        LocalPreferences pref = SettingsManager.getLocalPreferences();
        Resourcepart nickname = pref.getNickname();
        chatRoom.create(nickname);

        // Send an empty room configuration form which indicates that we want
        // an instant room
        chatRoom.sendConfigurationForm(new Form( DataForm.Type.submit ));
    }
    catch (XMPPException | SmackException | InterruptedException e1) {
        Log.error("Unable to send conference room chat configuration form.", e1);
        return null;
    }

    getChatContainer().addChatRoom(room);
    return room;
}
 
Example 2
Source File: ChatService.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void sendMessage(String roomId, String content) {
	EntityBareJid jid = null;
	try {
		jid = JidCreate.entityBareFrom(roomId);
	} catch (XmppStringprepException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	Chat chat = ChatManager.getInstanceFor(Launcher.connection).chatWith(jid);

	org.jivesoftware.smack.packet.Message message = new org.jivesoftware.smack.packet.Message();
	message.setType(Type.chat);
	message.addExtension(new Receipt());
	message.setBody(content);
	try {
		chat.send(message);
		DebugUtil.debug("chat.sendMessage::" + message.toString());
	} catch (NotConnectedException | InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}
 
Example 3
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 4
Source File: MultiUserChatIntegrationTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@SmackIntegrationTest
public void mucJoinLeaveTest() throws XmppStringprepException, NotAMucServiceException, NoResponseException,
        XMPPErrorException, NotConnectedException, InterruptedException, MucNotJoinedException {
    EntityBareJid mucAddress = JidCreate.entityBareFrom(Localpart.from("smack-inttest-join-leave-" + randomString),
            mucService.getDomain());

    MultiUserChat muc = mucManagerOne.getMultiUserChat(mucAddress);

    muc.join(Resourcepart.from("nick-one"));

    Presence reflectedLeavePresence = muc.leave();

    MUCUser mucUser = MUCUser.from(reflectedLeavePresence);
    assertNotNull(mucUser);

    assertTrue(mucUser.getStatus().contains(MUCUser.Status.PRESENCE_TO_SELF_110));
}
 
Example 5
Source File: TlsTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static void tlsTest(int runs, CharSequence jidCs, String password, String host, int port,
                String tlsPin, boolean shouldThrow) throws XmppStringprepException, KeyManagementException, NoSuchAlgorithmException {
    EntityBareJid jid = JidCreate.entityBareFrom(jidCs);
    for (int i = 0; i < runs; i++) {
        boolean res = tlsTest(jid, password, host, port, tlsPin, shouldThrow);
        if (!res) {
            throw new IllegalStateException();
        }
    }
}
 
Example 6
Source File: RosterVersioningTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
private static Item vaglafItem() throws XmppStringprepException {
    Item item = new Item(JidCreate.entityBareFrom("[email protected]"), "vaglaf the only");
    item.setItemType(ItemType.both);
    item.addGroupName("all");
    item.addGroupName("friends");
    item.addGroupName("partners");
    return item;
}
 
Example 7
Source File: IoT.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static void iotScenario(String dataThingJidString, String dataThingPassword, String readingThingJidString,
        String readingThingPassword, IotScenario scenario) throws Exception {
    final EntityBareJid dataThingJid = JidCreate.entityBareFrom(dataThingJidString);
    final EntityBareJid readingThingJid = JidCreate.entityBareFrom(readingThingJidString);

    final XMPPTCPConnectionConfiguration dataThingConnectionConfiguration = XMPPTCPConnectionConfiguration.builder()
            .setUsernameAndPassword(dataThingJid.getLocalpart(), dataThingPassword)
            .setXmppDomain(dataThingJid.asDomainBareJid()).setSecurityMode(SecurityMode.disabled)
            .enableDefaultDebugger().build();
    final XMPPTCPConnectionConfiguration readingThingConnectionConfiguration = XMPPTCPConnectionConfiguration
            .builder().setUsernameAndPassword(readingThingJid.getLocalpart(), readingThingPassword)
            .setXmppDomain(readingThingJid.asDomainBareJid()).setSecurityMode(SecurityMode.disabled)
            .enableDefaultDebugger().build();

    final XMPPTCPConnection dataThingConnection = new XMPPTCPConnection(dataThingConnectionConfiguration);
    final XMPPTCPConnection readingThingConnection = new XMPPTCPConnection(readingThingConnectionConfiguration);

    dataThingConnection.setReplyTimeout(TIMEOUT);
    readingThingConnection.setReplyTimeout(TIMEOUT);

    dataThingConnection.setUseStreamManagement(false);
    readingThingConnection.setUseStreamManagement(false);

    try {
        dataThingConnection.connect().login();
        readingThingConnection.connect().login();
        scenario.iotScenario(dataThingConnection, readingThingConnection);
    } finally {
        dataThingConnection.disconnect();
        readingThingConnection.disconnect();
    }
}
 
Example 8
Source File: RoomInvitation.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public RoomInvitation parse(XmlPullParser parser,
                int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException,
                IOException {
    final RoomInvitation invitation = new RoomInvitation();
    invitation.type = Type.valueOf(parser.getAttributeValue("", "type"));

    boolean done = false;
    while (!done) {
        parser.next();
        String elementName = parser.getName();
        if (parser.getEventType() == XmlPullParser.Event.START_ELEMENT) {
            if ("session".equals(elementName)) {
                invitation.sessionID = parser.getAttributeValue("", "id");
            }
            else if ("invitee".equals(elementName)) {
                String inviteeString = parser.nextText();
                invitation.invitee = JidCreate.from(inviteeString);
            }
            else if ("inviter".equals(elementName)) {
                String inviterString = parser.nextText();
                invitation.inviter = JidCreate.entityFrom(inviterString);
            }
            else if ("reason".equals(elementName)) {
                invitation.reason = parser.nextText();
            }
            else if ("room".equals(elementName)) {
                String roomString = parser.nextText();
                invitation.room = JidCreate.entityBareFrom(roomString);
            }
        }
        else if (parser.getEventType() == XmlPullParser.Event.END_ELEMENT && ELEMENT_NAME.equals(elementName)) {
            done = true;
        }
    }
    return invitation;
}
 
Example 9
Source File: ParserUtils.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static EntityBareJid getBareJidAttribute(XmlPullParser parser, String name) throws XmppStringprepException {
    final String jidString = parser.getAttributeValue("", name);
    if (jidString == null) {
        return null;
    }
    return JidCreate.entityBareFrom(jidString);
}
 
Example 10
Source File: ConferenceUtils.java    From Spark with Apache License 2.0 5 votes vote down vote up
public static void addUnclosableChatRoom(String jidString) {
    EntityBareJid jid;
       try {
           jid = JidCreate.entityBareFrom(jidString);
       } catch (XmppStringprepException e) {
           throw new IllegalArgumentException(e);
       }
    synchronized (ConferenceUtils.class) {
        unclosableChatRooms.add(jid);
    }
}
 
Example 11
Source File: XmppConnectionManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
private void registerAccount(String username, String password) throws NoResponseException, XMPPErrorException,
                NotConnectedException, InterruptedException, XmppStringprepException {
    if (accountRegistrationConnection == null) {
        throw new IllegalStateException("Account registration not configured");
    }

    switch (sinttestConfiguration.accountRegistration) {
    case serviceAdministration:
        EntityBareJid userJid = JidCreate.entityBareFrom(Localpart.from(username),
                        accountRegistrationConnection.getXMPPServiceDomain());
        adminManager.addUser(userJid, password);
        break;
    case inBandRegistration:
        if (!accountManager.supportsAccountCreation()) {
            throw new UnsupportedOperationException("Account creation/registation is not supported");
        }
        Set<String> requiredAttributes = accountManager.getAccountAttributes();
        if (requiredAttributes.size() > 4) {
            throw new IllegalStateException("Unkown required attributes");
        }
        Map<String, String> additionalAttributes = new HashMap<>();
        additionalAttributes.put("name", "Smack Integration Test");
        additionalAttributes.put("email", "[email protected]");
        Localpart usernameLocalpart = Localpart.from(username);
        accountManager.createAccount(usernameLocalpart, password, additionalAttributes);
        break;
    case disabled:
        throw new IllegalStateException("Account creation no possible");
    }
}
 
Example 12
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void removeGroupMemberAsync(ChatGroup group, Contact contact) {
    String chatRoomJid = group.getAddress().getAddress();
    if (mMUCs.containsKey(chatRoomJid))
    {
        MultiUserChat muc = mMUCs.get(chatRoomJid);
        try {
            EntityBareJid contactJid = JidCreate.entityBareFrom(contact.getAddress().getAddress());
            muc.revokeMembership(contactJid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 13
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 14
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 15
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 16
Source File: RosterDialog.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
    * Method to handle the Add-Button
    */
   private void addContactButton() {
String errorMessage = Res.getString("title.error");
String jid = getJID();

UIManager.put("OptionPane.okButtonText", Res.getString("ok"));

if(jid.length()==0)
{
    JOptionPane.showMessageDialog(dialog, Res.getString("message.invalid.jid.error"),
		Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
	return;
}

String contact = UserManager.escapeJID(jid);
String nickname = nicknameField.getText();
String group = (String) groupBox.getSelectedItem();

Transport transport = null;
if (publicBox.isSelected()) {
    AccountItem item = (AccountItem) accounts.getSelectedItem();
    transport = item.getTransport();
}

if (transport == null) {
    if (!contact.contains("@")) {
	contact = contact + "@"
		+ SparkManager.getConnection().getXMPPServiceDomain();
    }
} else {
    if (!contact.contains("@")) {
	contact = contact + "@" + transport.getXMPPServiceDomain();
    }
}

if (!ModelUtil.hasLength(nickname) && ModelUtil.hasLength(contact)) {
    // Try to load nickname from VCard
    VCard vcard = new VCard();
    try {
		EntityBareJid contactJid = JidCreate.entityBareFrom(contact);
		vcard.load(SparkManager.getConnection(), contactJid);
	nickname = vcard.getNickName();
    } catch (XMPPException | SmackException | XmppStringprepException | InterruptedException e1) {
	Log.error(e1);
    }
    // If no nickname, use first name.
    if (!ModelUtil.hasLength(nickname)) {
	nickname = XmppStringUtils.parseLocalpart(contact);
    }
    nicknameField.setText(nickname);
}

ContactGroup contactGroup = contactList.getContactGroup(group);
boolean isSharedGroup = contactGroup != null
	&& contactGroup.isSharedGroup();

if (isSharedGroup) {
    errorMessage = Res
	    .getString("message.cannot.add.contact.to.shared.group");
} else if (!ModelUtil.hasLength(contact)) {
    errorMessage = Res.getString("message.specify.contact.jid");
} else if (!XmppStringUtils.parseBareJid(contact).contains("@")) {
    errorMessage = Res.getString("message.invalid.jid.error");
} else if (!ModelUtil.hasLength(group)) {
    errorMessage = Res.getString("message.specify.group");
} else if (ModelUtil.hasLength(contact) && ModelUtil.hasLength(group)
	&& !isSharedGroup) {
    addEntry();
    dialog.setVisible(false);
   } else {

    JOptionPane.showMessageDialog(dialog, errorMessage,
	    Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
}
   }
 
Example 17
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 4 votes vote down vote up
@Override
        public void joinChatGroupAsync(Address address, String reason) {

            String chatRoomJid = address.getBareAddress();
            String[] parts = chatRoomJid.split("@");
            String room = parts[0];

            try {

                if (mConnection == null || (!mConnection.isAuthenticated()))
                    return;

//                mBookmarkManager.addBookmarkedConference(address.getUser(),JidCreate.entityBareFrom(chatRoomJid),true,null,null);

                // Create a MultiUserChat using a Connection for a room
                MultiUserChatManager mucMgr = MultiUserChatManager.getInstanceFor(mConnection);
                mucMgr.setAutoJoinOnReconnect(true);
                EntityBareJid crJid = JidCreate.entityBareFrom(chatRoomJid);
                MultiUserChat muc = mucMgr.getMultiUserChat( crJid);

                DiscussionHistory history = new DiscussionHistory();
                history.setMaxStanzas(Integer.MAX_VALUE);
                muc.join(Resourcepart.from(mUser.getName()), null, history, SmackConfiguration.getDefaultPacketReplyTimeout());
                String subject = muc.getSubject();

                if (TextUtils.isEmpty(subject))
                    subject = room;

                ChatGroup chatGroup = mGroups.get(chatRoomJid);

                if (chatGroup == null) {
                    chatGroup = new ChatGroup(address, subject, this);
                    mGroups.put(chatRoomJid, chatGroup);
                }

                mMUCs.put(chatRoomJid, muc);

                addMucListeners(muc, chatGroup);
                loadMembers(muc, chatGroup);

                queryArchive(crJid);

            } catch (Exception e) {
                debug(TAG,"error joining MUC",e);
            }

        }
 
Example 18
Source File: RosterTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Test processing a roster push 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
public void testEmptyGroupRosterPush() throws Throwable {
    final BareJid contactJID = JidCreate.entityBareFrom("[email protected]");
    assertNotNull("Can't get the roster from the provided connection!", roster);
    final StringBuilder sb = new StringBuilder();
    sb.append("<iq id=\"rostertest2\" type=\"set\" ")
            .append("to=\"").append(connection.getUser()).append("\">")
            .append("<query xmlns=\"jabber:iq:roster\">")
            .append("<item jid=\"").append(contactJID).append("\">")
            .append("<group></group>")
            .append("</item>")
            .append("</query>")
            .append("</iq>");
    final XmlPullParser parser = TestUtils.getIQParser(sb.toString());
    final IQ rosterPush = PacketParserUtils.parseIQ(parser);
    initRoster();
    rosterListener.reset();

    // Simulate receiving the roster push
    connection.processStanza(rosterPush);
    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 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 19
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 20
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 4 votes vote down vote up
private boolean loadVCard (ContentResolver resolver, String jid)
{
    try {
            debug(TAG, "loading vcard for: " + jid);

            EntityBareJid bareJid = JidCreate.entityBareFrom(jid);

            VCardManager vCardManager = VCardManager.getInstanceFor(mConnection);
            VCard vCard = vCardManager.loadVCard(bareJid);

            Contact contact = mContactListManager.getContact(bareJid.toString());

            if (!TextUtils.isEmpty(vCard.getNickName()))
            {
                if (!vCard.getNickName().equals(contact.getName()))
                {
                    contact.setName(vCard.getNickName());
                    mContactListManager.doSetContactName(contact.getAddress().getBareAddress(), contact.getName());
                }

            }

            //check for a forwarding address
            if (vCard.getJabberId() != null && (!vCard.getJabberId().equals(bareJid.toString())))
            {
                contact.setForwardingAddress(vCard.getJabberId());

            }
            else
            {
                contact.setForwardingAddress(null);
            }

                // If VCard is loaded, then save the avatar to the personal folder.
            String avatarHash = vCard.getAvatarHash();

            if (avatarHash != null)
            {
                byte[] avatarBytes = vCard.getAvatar();

                if (avatarBytes != null)
                {

                    debug(TAG, "found avatar image in vcard for: " + bareJid.toString());
                    debug(TAG, "start avatar length: " + avatarBytes.length);

                    int rowsUpdated = DatabaseUtils.updateAvatarBlob(resolver, Imps.Avatars.CONTENT_URI, avatarBytes, bareJid.toString());

                    if (rowsUpdated <= 0)
                        DatabaseUtils.insertAvatarBlob(resolver, Imps.Avatars.CONTENT_URI, mProviderId, mAccountId, avatarBytes, avatarHash, bareJid.toString());

                    return true;
                }
            }



    } catch (Exception e) {

        debug(TAG, "err loading vcard: " + e.toString());

        if (e.getMessage() != null)
        {
            String streamErr = e.getMessage();

            if (streamErr != null && (streamErr.contains("404") || streamErr.contains("503")))
            {
                return false;
            }
        }

    }

    return false;
}