org.jivesoftware.smack.packet.Presence Java Examples

The following examples show how to use org.jivesoftware.smack.packet.Presence. 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: FriendManager.java    From yiim_v2 with GNU General Public License v2.0 6 votes vote down vote up
private void reRequestAuth(final RosterGroup rosterGroup,
		final TabContactsModel model) {
	getXmppBinder().execute(new Runnable() {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Presence presence = new Presence(Presence.Type.subscribe);
			presence.setTo(model.getUser());
			getXmppBinder().getXmppConnection().sendPacket(presence);
		}
	});
	// XmppAddEntryRunnable runnable = new XmppAddEntryRunnable(
	// mYiFragment.getActivity(), model.getUser(), null);
	// if (rosterGroup.getName() != null
	// && !"unfiled".equals(rosterGroup.getName())) {
	// runnable.setGroupName(rosterGroup.getName());
	// }
	// getXmppBinder().execute(runnable);
}
 
Example #2
Source File: NotificationPlugin.java    From Spark with Apache License 2.0 6 votes vote down vote up
private void registerListener() {
    preferences = SettingsManager.getLocalPreferences();

    // Iterate through all online users and add them to the list.
    ContactList contactList = SparkManager.getWorkspace().getContactList();
    for (ContactGroup contactGroup : contactList.getContactGroups()) {
        for (ContactItem item : contactGroup.getContactItems()) {
            if (item != null && item.getJid() != null && item.getPresence().isAvailable()) {
                BareJid bareJID = item.getJid().asBareJid();
                onlineUsers.add(bareJID);
            }
        }
    }

    // Add Presence Listener
    SparkManager.getConnection().addAsyncStanzaListener(this, new StanzaTypeFilter(Presence.class));
}
 
Example #3
Source File: SendPresence.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public void addUI(JComponent mainPanel, GridBagConstraints labelConstraints, GridBagConstraints editConstraints) {
    addToPanel(mainPanel, labelConstraints, 0, 0, new JLabel("Type: ", JLabel.RIGHT));
    addToPanel(mainPanel, editConstraints, 1, 0, type = new JComboBox<>());
    type.addItem(Presence.Type.available);
    type.addItem(Presence.Type.unavailable);
    type.addItem(Presence.Type.subscribe);
    type.addItem(Presence.Type.unsubscribe);

    addToPanel(mainPanel, labelConstraints, 0, 1, new JLabel("Status: ", JLabel.RIGHT));
    addToPanel(mainPanel, editConstraints, 1, 1, mode = new JComboBox<>());
    mode.addItem(Presence.Mode.available);
    mode.addItem(Presence.Mode.away);
    mode.addItem(Presence.Mode.chat);
    mode.addItem(Presence.Mode.dnd);
    mode.addItem(Presence.Mode.xa);

    addToPanel(mainPanel, labelConstraints, 0, 2, new JLabel("Text: ", JLabel.RIGHT));
    addToPanel(mainPanel, editConstraints, 1, 2, text = new JTextField(20));

    addToPanel(mainPanel, labelConstraints, 0, 3, new JLabel("Recipient: ", JLabel.RIGHT));
    addToPanel(mainPanel, editConstraints, 1, 3, recipient = new JTextField(20));
}
 
Example #4
Source File: SendPresence.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public SampleResult perform(JMeterXMPPSampler sampler, SampleResult res) throws Exception {
    Presence.Type typeVal = Presence.Type.valueOf(sampler.getPropertyAsString(TYPE, Presence.Type.available.toString()));
    Presence.Mode modeVal = Presence.Mode.valueOf(sampler.getPropertyAsString(MODE, Presence.Mode.available.toString()));

    Presence presence = new Presence(typeVal);
    presence.setMode(modeVal);

    String to = sampler.getPropertyAsString(RECIPIENT);
    if (!to.isEmpty()) {
        presence.setTo(to);
    }

    String text = sampler.getPropertyAsString(STATUS_TEXT);
    if (!text.isEmpty()) {
        presence.setStatus(text);
    }

    sampler.getXMPPConnection().sendPacket(presence);
    res.setSamplerData(presence.toXML().toString());
    return res;
}
 
Example #5
Source File: MainWindow.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Closes the current connection and restarts Spark.
 *
 * @param reason the reason for logging out. This can be if user gave no reason.
 */
public void closeConnectionAndInvoke(String reason) {
    final XMPPConnection con = SparkManager.getConnection();
    if (con.isConnected()) {
        if (reason != null) {
            Presence byePresence = new Presence(Presence.Type.unavailable, reason, -1, null);
            try
            {
                ((AbstractXMPPConnection)con).disconnect(byePresence);
            }
            catch ( SmackException.NotConnectedException e )
            {
                Log.error( "Unable to sign out with presence.", e);
                ((AbstractXMPPConnection)con).disconnect();
            }
        }
        else {
            ((AbstractXMPPConnection)con).disconnect();
        }
    }
    if (!restartApplicationWithScript()) {
        restartApplicationWithJava();
    }
}
 
Example #6
Source File: XMPPSession.java    From mangosta-android with Apache License 2.0 6 votes vote down vote up
public void sendPresenceAvailable() {
    if (mXMPPConnection.isAuthenticated()) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Presence presence = new Presence(JidCreate.from(SERVICE_NAME), Presence.Type.available);
                    presence.setMode(Presence.Mode.available);
                    sendStanza(presence);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
 
Example #7
Source File: RosterManager.java    From mangosta-android with Apache License 2.0 6 votes vote down vote up
public void removeContact(String jidString)
        throws SmackException.NotLoggedInException, InterruptedException,
        SmackException.NotConnectedException, XMPPException.XMPPErrorException,
        SmackException.NoResponseException, XmppStringprepException {
    Roster roster = Roster.getInstanceFor(XMPPSession.getInstance().getXMPPConnection());
    if (!roster.isLoaded()) {
        roster.reloadAndWait();
    }

    BareJid jid = JidCreate.bareFrom(jidString);
    roster.removeEntry(roster.getEntry(jid));

    Presence presence = new Presence(Presence.Type.unsubscribe);
    presence.setTo(JidCreate.from(jidString));
    XMPPSession.getInstance().sendStanza(presence);
}
 
Example #8
Source File: RosterManager.java    From mangosta-android with Apache License 2.0 6 votes vote down vote up
public Presence.Type getStatusFromContact(String name) {
    try {
        HashMap<Jid, Presence.Type> buddies = getContacts();

        for (Map.Entry<Jid, Presence.Type> pair : buddies.entrySet()) {
            if (XMPPUtils.fromJIDToUserName(pair.getKey().toString()).equals(name)) {
                return pair.getValue();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return Presence.Type.unavailable;
}
 
Example #9
Source File: XSCHelper.java    From PracticeCode with Apache License 2.0 6 votes vote down vote up
/**
 * 发送当前状态
 *
 * @param status 状态。内部类PRESENCE里有两种状态 ONLINE 和 OFFLINE
 */
public void setPresence(final int status) {
    //如果没有连接,则返回
    if (getConnection() == null) {
        return;
    }
    //新线程里发送状态封包
    new Thread() {
        @Override
        public void run() {
            switch (status) {
                case PRESENCE.ONLINE:
                    getConnection().sendPacket(
                            new Presence(Presence.Type.available));
                    break;
                case PRESENCE.OFFLINE:
                    getConnection().sendPacket(
                            new Presence(Presence.Type.unavailable));
                    break;
                default:
                    break;
            }
        }
    }.start();
}
 
Example #10
Source File: XMPPContactsService.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
private void contactResourceChangedPresence(Presence presence) {
  if (roster == null) return;

  String address = presence.getFrom();
  XMPPContact contact = contacts.get(address);
  if (contact == null) {
    log.error("Should not happen: Contact " + address + " for presence update not found!");
    return;
  }

  JID fullJid = new JID(address);
  if (presence.isAvailable()) {
    handleContactResourceAvailable(contact, fullJid, presence);
  } else {
    handleContactResourceUnavailable(contact, fullJid);
  }
}
 
Example #11
Source File: AgentRoster.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Fires event to listeners.
 */
private void fireEvent(int eventType, Object eventObject) {
    AgentRosterListener[] listeners;
    synchronized (this.listeners) {
        listeners = new AgentRosterListener[this.listeners.size()];
        this.listeners.toArray(listeners);
    }
    for (int i = 0; i < listeners.length; i++) {
        switch (eventType) {
            case EVENT_AGENT_ADDED:
                listeners[i].agentAdded((EntityBareJid) eventObject);
                break;
            case EVENT_AGENT_REMOVED:
                listeners[i].agentRemoved((EntityBareJid) eventObject);
                break;
            case EVENT_PRESENCE_CHANGED:
                listeners[i].presenceChanged((Presence) eventObject);
                break;
        }
    }
}
 
Example #12
Source File: XmppConnection.java    From weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 添加好友 有分组
 * 
 * @param userName
 * @param name
 * @param groupName
 * @return
 */
public boolean addUser(String userName, String name, String groupName) {
	if (getConnection() == null)
		return false;
	try {
		Presence subscription = new Presence(Presence.Type.subscribed);
		subscription.setTo(userName);
		userName += "@" + getConnection().getServiceName();
		getConnection().sendPacket(subscription);
		getConnection().getRoster().createEntry(userName, name, new String[] { groupName });
		return true;
	} catch (Exception e) {
		e.printStackTrace();
		return false;
	}
}
 
Example #13
Source File: InstantMessagingClient.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Used by Velocity renderer
 * 
 * @return a String representing the online buddies out of the number of total buddies
 */
public String buddyCountOnline() {
    int onlineBuddyEntries = connection.getRoster().getEntryCount();
    final int allBuddies = onlineBuddyEntries;
    for (final Iterator l = connection.getRoster().getEntries().iterator(); l.hasNext();) {
        final RosterEntry entry = (RosterEntry) l.next();
        final Presence presence = connection.getRoster().getPresence(entry.getUser());
        if (presence.getType() == Presence.Type.unavailable) {
            onlineBuddyEntries--;
        }
    }
    // final string looks like e.g. "(3/5)"
    final StringBuilder sb = new StringBuilder(10);
    sb.append("(");
    sb.append(onlineBuddyEntries);
    sb.append("/");
    sb.append(allBuddies);
    sb.append(")");
    return sb.toString();
}
 
Example #14
Source File: InstantMessagingClient.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Used by Velocity renderer
 * 
 * @param groupname
 * @return a String representing the online buddies out of the number of total buddies for a single group like (3/5)
 */
protected String buddyCountOnlineForGroup(final String groupname) {
    final RosterGroup rosterGroup = connection.getRoster().getGroup(groupname);
    int buddyEntries = rosterGroup.getEntryCount();
    final int allBuddies = buddyEntries;
    for (final Iterator I = rosterGroup.getEntries().iterator(); I.hasNext();) {
        final RosterEntry entry = (RosterEntry) I.next();
        final Presence presence = connection.getRoster().getPresence(entry.getUser());
        if (presence.getType() == Presence.Type.unavailable) {
            buddyEntries--;
        }
    }
    // final string looks like e.g. "(3/5)"
    final StringBuilder sb = new StringBuilder(10);
    sb.append("(");
    sb.append(buddyEntries);
    sb.append("/");
    sb.append(allBuddies);
    sb.append(")");
    return sb.toString();
}
 
Example #15
Source File: Roster.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a List of Presence objects for all of a user's current presences if no presence information is available,
 * such as when you are not subscribed to the user's presence updates.
 *
 * @param bareJid an XMPP ID, e.g. [email protected].
 * @return a List of Presence objects for all the user's current presences, or an unavailable presence if no
 *         presence information is available.
 */
public List<Presence> getAllPresences(BareJid bareJid) {
    Map<Resourcepart, Presence> userPresences = getPresencesInternal(bareJid);
    List<Presence> res;
    if (userPresences == null) {
        // Create an unavailable presence if none was found
        Presence unavailable = synthesizeUnvailablePresence(bareJid);
        res = new ArrayList<>(Arrays.asList(unavailable));
    } else {
        res = new ArrayList<>(userPresences.values().size());
        for (Presence presence : userPresences.values()) {
            res.add(presence);
        }
    }
    return res;
}
 
Example #16
Source File: GatewayPlugin.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handlePresence(ContactItem item, Presence presence) {
       if (presence.isAvailable()) {
           Domainpart domain = presence.getFrom().getDomain();
           Transport transport = TransportUtils.getTransport(domain.toString());
           if (transport != null) {
               if (presence.getType() == Presence.Type.available) {
                   item.setSpecialIcon(transport.getIcon());
               }
               else {
                   item.setSpecialIcon(transport.getInactiveIcon());
               }
               return false;
           }
       }

       return false;
   }
 
Example #17
Source File: XmppLoginRunnable.java    From yiim_v2 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public XmppResult execute() {
	XmppResult result = createResult();
	try {
		XMPPConnection connection = XmppConnectionUtils.getInstance()
				.getConnection();
		if (connection.isAuthenticated()) {
			XmppConnectionUtils.getInstance().closeConnection();
			connection = XmppConnectionUtils.getInstance().getConnection();
		}
		connection.login(mUserName, mPasswd);
		Presence presence = new Presence(mType, mStatus, 1, mMode);
		connection.sendPacket(presence);

		FileDownloadListener.setRecieveFilePath(YiFileUtils.getStorePath()
				+ "yiim/" + mUserName + "file_recv/");

		result.status = Status.SUCCESS;
	} catch (Exception e) {
		result.obj = e.getMessage();
	}
	return result;
}
 
Example #18
Source File: UserIdlePlugin.java    From Spark with Apache License 2.0 6 votes vote down vote up
private void setIdle() {

		latestPresence = SparkManager.getWorkspace().getStatusBar().getPresence();

		if (latestPresence.getStatus().equals(Res.getString("status.online")) || latestPresence.getStatus().equals(Res.getString("status.free.to.chat"))) {
			statustext = pref.getIdleMessage();
		} else {
			statustext = latestPresence.getStatus();
		}

		if (latestPresence.isAway()) {
			Log.debug("UserIdlePlugin: Presence is already set to away");
		} else {
			Presence statusPresence = new Presence(Presence.Type.available, StringUtils.modifyWildcards(statustext), 0, Presence.Mode.away);
			SparkManager.getSessionManager().changePresence(statusPresence);
			Log.debug("UserIdlePlugin: Setting idle presence");
		}
	}
 
Example #19
Source File: RosterHandler.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
public void onPresenceUpdate(JID jid, Presence.Type type, Optional<String> optStatus) {
    JID myJID = mClient.getOwnJID().orElse(null);
    if (myJID != null && myJID.equals(jid))
        // don't wanna see myself
        return;

    Contact contact = mModel.contacts().get(jid).orElse(null);
    if (contact == null) {
        LOGGER.info("can't find contact with jid: "+jid);
        return;
    }

    if (type == Presence.Type.available) {
        contact.setOnlineStatus(Contact.Online.YES);
    } else if (type == Presence.Type.unavailable) {
        contact.setOnlineStatus(Contact.Online.NO);
    }

    if (optStatus.isPresent())
        contact.setStatusText(optStatus.get());
}
 
Example #20
Source File: MultiUserChatTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
public void testAnonymousParticipant() {
    try {
        // Anonymous user joins the new room
        ConnectionConfiguration connectionConfiguration =
                new ConnectionConfiguration(getHost(), getPort(), getXMPPServiceDomain());
        XMPPTCPConnection anonConnection = new XMPPConnection(connectionConfiguration);
        anonConnection.connect();
        anonConnection.loginAnonymously();
        MultiUserChat muc2 = new MultiUserChat(anonConnection, room);
        muc2.join("testbot2");
        Thread.sleep(400);

        // User1 checks the presence of Anonymous user in the room
        Presence presence = muc.getOccupantPresence(room + "/testbot2");
        assertNotNull("Presence of user2 in room is missing", presence);
        assertTrue(
            "Presence mode of user2 is wrong",
            presence.getMode() == null || presence.getMode() == Presence.Mode.available);

        // Anonymous user leaves the room
        muc2.leave();
        anonConnection.disconnect();
        Thread.sleep(250);
        // User1 checks the presence of Anonymous user in the room
        presence = muc.getOccupantPresence(room + "/testbot2");
        assertNull("Presence of participant testbotII still exists", presence);

    }
    catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example #21
Source File: Roster.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new roster entry and presence subscription. The server will asynchronously update the
 * roster with the subscription status.
 *
 * @param user the user. (e.g. [email protected])
 * @param name the nickname of the user.
 * @param groups the list of group names the entry will belong to, or <tt>null</tt> if the the
 *     roster entry won't belong to a group.
 * @throws XMPPException if an XMPP exception occurs.
 * @throws IllegalStateException if connection is not logged in or logged in anonymously
 */
public void createEntry(String user, String name, String[] groups) throws XMPPException {
  if (!connection.isAuthenticated()) {
    throw new IllegalStateException("Not logged in to server.");
  }
  if (connection.isAnonymous()) {
    throw new IllegalStateException("Anonymous users can't have a roster.");
  }

  // Create and send roster entry creation packet.
  RosterPacket rosterPacket = new RosterPacket();
  rosterPacket.setType(IQ.Type.SET);
  RosterPacket.Item item = new RosterPacket.Item(user, name);
  if (groups != null) {
    for (String group : groups) {
      if (group != null && group.trim().length() > 0) {
        item.addGroupName(group);
      }
    }
  }
  rosterPacket.addRosterItem(item);
  // Wait up to a certain number of seconds for a reply from the server.
  PacketCollector collector =
      connection.createPacketCollector(new PacketIDFilter(rosterPacket.getPacketID()));
  connection.sendPacket(rosterPacket);
  IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
  collector.cancel();
  if (response == null) {
    throw new XMPPException("No response from the server.");
  }
  // If the server replied with an error, throw an exception.
  else if (response.getType() == IQ.Type.ERROR) {
    throw new XMPPException(response.getError());
  }

  // Create a presence subscription packet and send.
  Presence presencePacket = new Presence(Presence.Type.subscribe);
  presencePacket.setTo(user);
  connection.sendPacket(presencePacket);
}
 
Example #22
Source File: XMPPConnectionService.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private void sendAvailablePresenceWithClientIdentifier() {
  String version = EntityCapsManager.getInstanceFor(connection).getCapsVersion();
  CapsExtension caps = new CapsExtension(XMPP_CLIENT_IDENTIFIER, version, CAPS_HASH_ALGORITHM);

  Presence presence = new Presence(Presence.Type.available);
  presence.addExtension(caps);
  connection.sendPacket(presence);
}
 
Example #23
Source File: SendPresence.java    From jmeter-bzm-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public void setGuiFieldsFromSampler(JMeterXMPPSampler sampler) {
    recipient.setText(sampler.getPropertyAsString(RECIPIENT));
    text.setText(sampler.getPropertyAsString(STATUS_TEXT));
    type.setSelectedItem(Presence.Type.valueOf(sampler.getPropertyAsString(TYPE, Presence.Type.available.toString())));
    mode.setSelectedItem(Presence.Mode.valueOf(sampler.getPropertyAsString(MODE, Presence.Mode.available.toString())));
}
 
Example #24
Source File: JabberWorkItemHandlerTest.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
@Test(expected = WorkItemHandlerRuntimeException.class)
public void testSendMessageInvalidParams() throws Exception {
    ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);

    doNothing().when(xmppConnection).connect();
    doNothing().when(xmppConnection).login(anyString(),
                                           anyString());
    doNothing().when(xmppConnection).sendPacket(any(Presence.class));
    doNothing().when(xmppConnection).disconnect();
    when(xmppConnection.getChatManager()).thenReturn(chatManager);
    when(chatManager.createChat(anyString(),
                                anyObject())).thenReturn(chat);

    TestWorkItemManager manager = new TestWorkItemManager();
    WorkItemImpl workItem = new WorkItemImpl();

    JabberWorkItemHandler handler = new JabberWorkItemHandler("", "");
    handler.setConf(connectionConf);
    handler.setConnection(xmppConnection);

    handler.executeWorkItem(workItem,
                            manager);

    assertNotNull(manager.getResults());
    assertEquals(0,
                 manager.getResults().size());
}
 
Example #25
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 #26
Source File: Roster.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new roster entry and presence subscription. The server will asynchronously
 * update the roster with the subscription status.
 *
 * @param user   the user. (e.g. [email protected])
 * @param name   the nickname of the user.
 * @param groups the list of group names the entry will belong to, or <tt>null</tt> if the
 *               the roster entry won't belong to a group.
 * @throws XMPPException if an XMPP exception occurs.
 */
public void createEntry(String user, String name, String[] groups) throws XMPPException {
    // Create and send roster entry creation packet.
    RosterPacket rosterPacket = new RosterPacket();
    rosterPacket.setType(IQ.Type.SET);
    RosterPacket.Item item = new RosterPacket.Item(user, name);
    if (groups != null) {
        for (String group : groups) {
            if (group != null && group.trim().length() > 0) {
                item.addGroupName(group);
            }
        }
    }
    rosterPacket.addRosterItem(item);
    // Wait up to a certain number of seconds for a reply from the server.
    PacketCollector collector = connection.createPacketCollector(
            new PacketIDFilter(rosterPacket.getPacketID()));
    connection.sendPacket(rosterPacket);
    IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
    collector.cancel();
    if (response == null) {
        throw new XMPPException("No response from the server.");
    }
    // If the server replied with an error, throw an exception.
    else if (response.getType() == IQ.Type.ERROR) {
        throw new XMPPException(response.getError());
    }

    // Create a presence subscription packet and send.
    Presence presencePacket = new Presence(Presence.Type.subscribe);
    presencePacket.setTo(user);
    connection.sendPacket(presencePacket);
}
 
Example #27
Source File: RosterSmackTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the creation of a roster and then simulates abrupt termination. Cached presences
 * must go offline. At reconnection, presences must go back to online.
 * <ol>
 *     <li> Create some entries
 *     <li> Breack the connection
 *     <li> Check offline presences
 *     <li> Whait for automatic reconnection
 *     <li> Check online presences
 * </ol>
 */
public void testOfflinePresencesAfterDisconnection() throws Exception {
    // Add a new roster entry
    Roster roster = getConnection(0).getRoster();
    roster.createEntry(getBareJID(1), "gato11", null);
    roster.createEntry(getBareJID(2), "gato12", null);

    // Wait up to 2 seconds to let the server process presence subscriptions
    long initial = System.currentTimeMillis();
    while (System.currentTimeMillis() - initial < 2000 && (
            !roster.getPresence(getBareJID(1)).isAvailable() ||
                    !roster.getPresence(getBareJID(2)).isAvailable())) {
        Thread.sleep(100);
    }

    Thread.sleep(200);

    // Break the connection
    getConnection(0).notifyConnectionError(new Exception("Simulated Error"));

    Presence presence = roster.getPresence(getBareJID(1));
    assertFalse("Unavailable presence not found for offline user", presence.isAvailable());
    assertEquals("Unavailable presence not found for offline user", Presence.Type.unavailable,
            presence.getType());
    // Reconnection should occur in 10 seconds
    Thread.sleep(12200);
    presence = roster.getPresence(getBareJID(1));
    assertTrue("Presence not found for user", presence.isAvailable());
    assertEquals("Presence should be online after a connection reconnection",
            Presence.Type.available, presence.getType());
}
 
Example #28
Source File: LowLevelRosterIntegrationTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@SmackIntegrationTest
public void testPresenceEventListenersOffline(final AbstractXMPPConnection conOne,
        final AbstractXMPPConnection conTwo) throws TimeoutException, Exception {
    IntegrationTestRosterUtil.ensureBothAccountsAreNotInEachOthersRoster(conOne, conTwo);

    final Roster rosterOne = Roster.getInstanceFor(conOne);
    final Roster rosterTwo = Roster.getInstanceFor(conTwo);

    rosterOne.createItem(conTwo.getUser().asBareJid(), "Con Two", null);
    rosterTwo.createItem(conOne.getUser().asBareJid(), "Con One", null);

    IntegrationTestRosterUtil.ensureBothAccountsAreSubscribedToEachOther(conOne, conTwo, timeout);

    final SimpleResultSyncPoint offlineTriggered = new SimpleResultSyncPoint();

    rosterOne.addPresenceEventListener(new AbstractPresenceEventListener() {
        @Override
        public void presenceUnavailable(FullJid jid, Presence presence) {
            if (!jid.equals(conTwo.getUser())) {
                return;
            }
            offlineTriggered.signal();
        }
    });

    // Disconnect conTwo, this should cause an 'unavailable' presence to be send from conTwo to
    // conOne.
    conTwo.disconnect();

    Boolean result = offlineTriggered.waitForResult(timeout);
    if (!result) {
        throw new Exception("presenceUnavailable() was not called");
    }
}
 
Example #29
Source File: StatusBar.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Populates the current Dnd List.
 */
private void buildStatusItemList() {
	for (Presence presence : PresenceManager.getPresences()) {
		Icon icon = PresenceManager.getIconFromPresence(presence);
		StatusItem item = new StatusItem(presence, icon);
		statusList.add(item);
	}

	final Icon availableIcon = PresenceManager.getIconFromPresence(new Presence(Presence.Type.available));

	// Set default presence icon (Avaialble)
	statusPanel.setIcon(availableIcon);
}
 
Example #30
Source File: AgentConversations.java    From Spark with Apache License 2.0 5 votes vote down vote up
private void calculateNumberOfChats(AgentRoster agentRoster) {
    int counter = 0;
    // TODO: CHECK FASTPATH
    for (EntityBareJid agent : agentRoster.getAgents()) {
        Presence presence = agentRoster.getPresence(agent);
        if (presence.isAvailable()) {
            AgentStatus agentStatus = (AgentStatus)presence.getExtension("agent-status", "http://jabber.org/protocol/workgroup");
            if (agentStatus != null) {
                counter += agentStatus.getCurrentChats().size();
            }
        }
    }

    FastpathPlugin.getUI().setTitleForComponent(FpRes.getString("message.current.chats", counter), this);
}