Java Code Examples for org.jivesoftware.smack.packet.Presence#getType()

The following examples show how to use org.jivesoftware.smack.packet.Presence#getType() . 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: 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 2
Source File: StatusBar.java    From Spark with Apache License 2.0 6 votes vote down vote up
public void changeAvailability(final Presence presence) {
	// SPARK-1524: if we were reconnected because of the error
	// then we get presence with the mode == null. 
	if (presence.getMode() == null)
		return;

	if ((presence.getMode() == currentPresence.getMode()) && (presence.getType() == currentPresence.getType()) && (presence.getStatus().equals(currentPresence.getStatus()))) {
		ExtensionElement pe = presence.getExtension("x", "vcard-temp:x:update");
		if (pe != null) {
			// Update VCard
			loadVCard();
		}
		return;
	}
	currentPresence = presence;

	SwingUtilities.invokeLater(changePresenceRunnable);
}
 
Example 3
Source File: BaseChatActivity.java    From yiim_v2 with GNU General Public License v2.0 6 votes vote down vote up
public void onVoiceBtnClick(View v) {
	if (!getXmppBinder().isAVCallOK()) {
		showProgressDialog(getString(R.string.err_call_check_net));
		getHandler().sendEmptyMessageDelayed(MSG_CHECK_NATWORK_TYPE, 200);
		return;
	}

	Presence pre = getXmppBinder().getXmppConnection().getRoster()
			.getPresence(mUserTo);
	if (pre.getType() != Presence.Type.unavailable) {
		Intent intent = new Intent(
				"com.ikantech.xmppsupoort.jingle.ACTION_CALL");
		intent.setData(Uri.parse("xmpp:" + pre.getFrom()));
		intent.putExtra("isCaller", true);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	} else {
		showMsgDialog(getString(R.string.err_call_user_not_online));
	}
}
 
Example 4
Source File: XmppVcard.java    From yiim_v2 with GNU General Public License v2.0 6 votes vote down vote up
public void updatePresence() {
	try {
		Connection connection = XmppConnectionUtils.getInstance()
				.getConnection();
		if (connection != null && connection.isConnected()
				&& connection.isAuthenticated()) {
			// 在线状态获取
			Presence presence = connection.getRoster().getPresence(mUserId);
			if (presence.getType() != Type.unavailable) {
				setPresence("online");
			} else {
				setPresence("unavailable");
			}
			saveToDatabase();
		}
	} catch (Exception e) {
		// TODO: handle exception
	}
}
 
Example 5
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 6
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 7
Source File: InstantMessagingClient.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Used by Velocity renderer
 * 
 * @param jid
 * @return get a presence for a specific user
 */
protected String getUserPresence(final String jid) {
    final Presence presence = connection.getRoster().getPresence(jid);
    String imageName = "offline"; // default
    // mode == null is equals available!!
    if (presence.getMode() == null && presence.getType() == Presence.Type.available) {
        imageName = Presence.Mode.available.toString();
    }
    if (presence.getMode() != null) {
        imageName = presence.getMode().toString();
    }
    return imageName;
}
 
Example 8
Source File: InstantMessagingClient.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Used by Velocity renderer
 * 
 * @param jid
 * @return get a presence for a specific user
 */
protected String getUserPresence(final String jid) {
    final Presence presence = connection.getRoster().getPresence(jid);
    String imageName = "offline"; // default
    // mode == null is equals available!!
    if (presence.getMode() == null && presence.getType() == Presence.Type.available) {
        imageName = Presence.Mode.available.toString();
    }
    if (presence.getMode() != null) {
        imageName = presence.getMode().toString();
    }
    return imageName;
}
 
Example 9
Source File: OnlineAgents.java    From Spark with Apache License 2.0 5 votes vote down vote up
@Override
public void presenceChanged(Presence presence) {
    BareJid jid = presence.getFrom().asBareJid();
    ContactItem item = contactGroup.getContactItemByJID(jid);

    if (item != null) {
        item.setPresence(presence);
        if (presence.getType() == Presence.Type.unavailable) {
            contactGroup.removeContactItem(item);
        }
        else if (presence.getType() == Presence.Type.available) {
            Icon icon = PresenceManager.getIconFromPresence(presence);
            if (icon == null) {
                icon = FastpathRes.getImageIcon(FastpathRes.GREEN_BALL);
            }
            item.setIcon(icon);
        }
    }
    else {
        if (presence.getType() == Presence.Type.available) {
            EntityBareJid agent = presence.getFrom().asEntityBareJidOrThrow();
            String nickname = SparkManager.getUserManager().getUserNicknameFromJID(agent);
            if (nickname == null) {
                nickname = agent.toString();
            }
            ContactItem contactItem = new ContactItem(nickname,nickname, presence.getFrom().asBareJid());
            contactItem.setPresence(presence);
            contactGroup.addContactItem(contactItem);
        }
    }

    contactGroup.fireContactGroupUpdated();
}
 
Example 10
Source File: Workgroup.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the workgroup is available for receiving new requests. The workgroup will be
 * available only when agents are available for this workgroup.
 *
 * @return true if the workgroup is available for receiving new requests.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public boolean isAvailable() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    Presence directedPresence = connection.getStanzaFactory().buildPresenceStanza()
            .ofType(Presence.Type.available)
            .to(workgroupJID)
            .build();

    StanzaFilter typeFilter = new StanzaTypeFilter(Presence.class);
    StanzaFilter fromFilter = FromMatchesFilter.create(workgroupJID);
    StanzaCollector collector = connection.createStanzaCollectorAndSend(new AndFilter(fromFilter,
            typeFilter), directedPresence);

    Presence response = collector.nextResultOrThrow();
    return Presence.Type.available == response.getType();
}
 
Example 11
Source File: SubscriptionHandler.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
private void processPresence(Presence presence) {
  if (presence.getFrom() == null) return;

  JID jid = new JID(presence.getFrom());

  switch (presence.getType()) {
    case error:
      String message =
          MessageFormat.format(
              "received error presence package from {0}, condition: {1}, message: {2}",
              presence.getFrom(),
              presence.getError().getCondition(),
              presence.getError().getMessage());
      log.warn(message);
      return;

    case subscribed:
      log.debug("contact subscribed to us: " + jid);
      break;

    case unsubscribed:
      log.debug("contact unsubscribed from us: " + jid);
      notifySubscriptionCanceled(jid);
      break;

    case subscribe:
      log.debug("contact requests to subscribe to us: " + jid);
      notifySubscriptionReceived(jid);
      break;

    case unsubscribe:
      log.debug("contact requests to unsubscribe from us: " + jid);
      removeSubscription(jid);
      break;

    default:
      // do nothing
  }
}
 
Example 12
Source File: PresenceManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
public static boolean areEqual(Presence p1, Presence p2) {
    if (p1 == p2)
       return true;
    
    if (p1 == null || p2 == null)
        return false;
    
   return p1.getType() == p2.getType() && p1.getMode() == p2.getMode()
           && p1.getStatus().equals(p2.getStatus());
}
 
Example 13
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 14
Source File: GroupChatRoom.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
 * Handle all presence packets being sent to this Group Chat Room.
 *
 * @param stanza the presence packet.
 */
private void handlePresencePacket( Stanza stanza )
{
    final Presence presence = (Presence) stanza;
    if ( presence.getError() != null )
    {
        return;
    }

    final EntityFullJid from = presence.getFrom().asEntityFullJidIfPossible();
    if (from == null) {
       return;
    }

    final Resourcepart nickname = from.getResourcepart();

    final MUCUser mucUser = stanza.getExtension( "x", "http://jabber.org/protocol/muc#user" );
    final Set<MUCUser.Status> status = new HashSet<>();
    if ( mucUser != null )
    {
        status.addAll( mucUser.getStatus() );
        final Destroy destroy = mucUser.getDestroy();
        if ( destroy != null )
        {
            UIManager.put( "OptionPane.okButtonText", Res.getString( "ok" ) );
            JOptionPane.showMessageDialog( this,
                    Res.getString( "message.room.destroyed", destroy.getReason() ),
                    Res.getString( "title.room.destroyed" ),
                    JOptionPane.INFORMATION_MESSAGE );
            leaveChatRoom();
            return;
        }
    }

    if ( presence.getType() == Presence.Type.unavailable && !status.contains( MUCUser.Status.NEW_NICKNAME_303 ) )
    {
        if ( currentUserList.contains( from ) )
        {
            if ( pref.isShowJoinLeaveMessagesEnabled() )
            {
                getTranscriptWindow().insertNotificationMessage( Res.getString( "message.user.left.room", nickname ), ChatManager.NOTIFICATION_COLOR );
                scrollToBottom();
            }
            currentUserList.remove( from );
        }
    }
    else
    {
        if ( !currentUserList.contains( from ) )
        {
            currentUserList.add( from );
            getChatInputEditor().setEnabled( true );
            if ( pref.isShowJoinLeaveMessagesEnabled() )
            {
                getTranscriptWindow().insertNotificationMessage(
                        Res.getString( "message.user.joined.room", nickname ),
                        ChatManager.NOTIFICATION_COLOR );
                scrollToBottom();
            }
        }
    }
}
 
Example 15
Source File: GatewayButton.java    From Spark with Apache License 2.0 4 votes vote down vote up
public GatewayButton(final Transport transport) {
     setLayout(new GridBagLayout());
     setOpaque(false);

     this.transport = transport;

     final StatusBar statusBar = SparkManager.getWorkspace().getStatusBar();
     final JPanel commandPanel = SparkManager.getWorkspace().getCommandPanel();

     if (PresenceManager.isOnline(transport.getXMPPServiceDomain())) {
         button.setIcon(transport.getIcon());
     }
     else {
         button.setIcon(transport.getInactiveIcon());
     }
     button.setToolTipText(transport.getName());

     commandPanel.add(button);

     button.addMouseListener(new MouseAdapter() {
         @Override
public void mousePressed(MouseEvent mouseEvent) {
             handlePopup(mouseEvent);
         }
     });
     commandPanel.updateUI();
     final Runnable registerThread = () -> {
         // Send directed presence if registered with this transport.
         final boolean isRegistered = TransportUtils.isRegistered(SparkManager.getConnection(), transport);
         if (isRegistered) {
             // Check if auto login is set.
             boolean autoJoin = TransportUtils.autoJoinService(transport.getXMPPServiceDomain());
             if (autoJoin) {
                 Presence oldPresence = statusBar.getPresence();
                 Presence presence = new Presence(oldPresence.getType(), oldPresence.getStatus(), oldPresence.getPriority(), oldPresence.getMode());
                 presence.setTo(transport.getXMPPServiceDomain());
                 try
                 {
                     SparkManager.getConnection().sendStanza(presence);
                 }
                 catch ( SmackException.NotConnectedException | InterruptedException e )
                 {
                     Log.error( "Unable to register.", e );
                 }
             }
         }
     };

     TaskEngine.getInstance().submit(registerThread);
 }
 
Example 16
Source File: XmppVcard.java    From yiim_v2 with GNU General Public License v2.0 4 votes vote down vote up
public static XmppVcard loadByVcard(Context context, Connection connection,
		String user, XmppVcard xmppVcard) {
	XmppVcard ret = null;
	if (xmppVcard != null) {
		ret = xmppVcard;
	} else {
		ret = new XmppVcard(context);
	}
	try {
		VCard vCard = new VCard();
		vCard.load(connection, user);

		Roster roster = connection.getRoster();

		ret.setNickName(vCard.getNickName());

		// 在线状态获取
		Presence presence = roster.getPresence(user);
		if (presence.getType() != Type.unavailable) {
			ret.setPresence("online");
		} else {
			ret.setPresence("unavailable");
		}

		// 加载用户头像
		byte[] avatar = vCard.getAvatar();
		if (avatar != null) {
			YiStoreCache.cacheRawData(user, avatar);
		}

		ret.setGender(vCard.getField(Const.SEX));
		ret.setSign(vCard.getField(Const.SIGN));
		ret.setCountry(vCard.getField(Const.COUNTRY));
		ret.setProvince(vCard.getField(Const.PROVINCE));
		ret.setAddress(vCard.getField(Const.ADDRESS));
		ret.setBirthday(Long.valueOf(vCard.getField(Const.BIRTHDAY)));
		ret.setSecondBirthday(Long.valueOf(vCard
				.getField(Const.SECOND_BIRTHDAY)));
		ret.setOnlineTime(Long.valueOf(vCard.getField(Const.ONLINETIME)));
		ret.setRealName(vCard.getField(Const.REALNAME));
		ret.setBloodGroup(vCard.getField(Const.BLOOD_GROUP));
		ret.setPhone(vCard.getField(Const.PHONE));
		ret.setOccupation(vCard.getField(Const.OCCUPATION));
		ret.setEmail(vCard.getField(Const.EMAIL));

		//通知重新加载好友列表
		Intent intent = new Intent(Const.NOTIFY_RELOAD_ROSTER_ENTRIES);
		context.sendBroadcast(intent);
	} catch (Exception e) {
	}

	return ret;
}
 
Example 17
Source File: PresenceManager.java    From Spark with Apache License 2.0 4 votes vote down vote up
public static boolean isInvisible(Presence presence) {
    return presence != null && presence.getType() == Presence.Type.unavailable 
            && (Res.getString("status.invisible").equalsIgnoreCase(presence.getStatus())
            		|| isNullOrEmpty(presence.getStatus()))
            && Presence.Mode.available == presence.getMode();
}
 
Example 18
Source File: InstantMessagingClient.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * change jabber status. Example: sendPresencePacket(Presence.Type.AVAILABLE, "at meeting...", 1, Presence.Mode.AWAY);
 * 
 * @param type
 * @param status
 * @param priority
 * @param mode
 */
public void sendPresence(final Presence.Type type, String status, final int priority, final Presence.Mode mode) {
    // get rid of "&" because they break xml packages!
    if (status != null) {
        status = status.replaceAll("&", "&amp;");
    }
    if (connection == null || !connection.isConnected()) {
        return;
    }
    if (collaborationDisabled) {
        return;
    }

    setStatus(mode);
    final Presence presence = new Presence(type);
    if (status == null) {
        if (mode == Presence.Mode.available) {
            status = InstantMessagingConstants.PRESENCE_MODE_AVAILABLE;
        } else if (mode == Presence.Mode.away) {
            status = InstantMessagingConstants.PRESENCE_MODE_AWAY;
        } else if (mode == Presence.Mode.chat) {
            status = InstantMessagingConstants.PRESENCE_MODE_CHAT;
        } else if (mode == Presence.Mode.dnd) {
            status = InstantMessagingConstants.PRESENCE_MODE_DND;
        } else if (mode == Presence.Mode.xa) {
            status = InstantMessagingConstants.PRESENCE_MODE_XAWAY;
        }
        presence.setStatus(status);
    } else {
        presence.setStatus(status);
    }
    setStatusMsg(presence.getStatus());
    // setting prio when type == unavailable causes error on IM server
    if (presence.getType() == Presence.Type.available) {
        presence.setPriority(priority);
    }
    if (mode != null) {
        presence.setMode(mode);
    }
    try {
        connection.sendPacket(presence);
    } catch (final RuntimeException ex) {
        log.warn("Error while trying to send Instant Messaging packet for user: " + userInfo.getUsername() + " .Errormessage: ", ex);
    }
}
 
Example 19
Source File: StatusBar.java    From Spark with Apache License 2.0 4 votes vote down vote up
public static Presence copyPresence(Presence presence) {
	return new Presence(presence.getType(), presence.getStatus(), presence.getPriority(), presence.getMode());
}
 
Example 20
Source File: MucEnterConfiguration.java    From Smack with Apache License 2.0 3 votes vote down vote up
/**
 * Set the presence used to join the MUC room.
 * <p>
 * The 'to' value of the given presence will be overridden and the given presence must be of type
 * 'available', otherwise an {@link IllegalArgumentException} will be thrown.
 * <p>
 *
 * @param presence TODO javadoc me please
 * @return a reference to this builder.
 * @deprecated use {@link #withPresence(Consumer)} instead.
 */
@Deprecated
// TODO: Remove in Smack 4.5.
public Builder withPresence(Presence presence) {
    if (presence.getType() != Presence.Type.available) {
        throw new IllegalArgumentException("Presence must be of type 'available'");
    }

    joinPresence = presence;
    return this;
}