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

The following examples show how to use org.jivesoftware.smack.packet.Presence#isAvailable() . 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: 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 2
Source File: SparkSystemTray.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Change the presence of the tray.
 *
 * @param presence the new presence.
 */
public void changePresence(Presence presence) {
    if (Spark.isMac()) {
        return;
    }

    if (presence.getMode() == Presence.Mode.available || presence.getMode() == Presence.Mode.chat) {
        setTrayIcon(availableIcon);
    }
    else if (presence.getMode() == Presence.Mode.away || presence.getMode() == Presence.Mode.xa) {
        setTrayIcon(awayIcon);
    }
    else {
        setTrayIcon(dndIcon);
    }

    // Get Status Text
    if (presence.isAvailable()) {
        String status = presence.getStatus();
        trayIcon.setToolTip(Default.getString(Default.APPLICATION_NAME) + "\n" + status);
    }
}
 
Example 3
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 4
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);
}
 
Example 5
Source File: OTRManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
@Override
public boolean handlePresence(ContactItem item, Presence presence) {
    if (OTRProperties.getInstance().getOTRCloseOnDisc()) {
        if (!presence.isAvailable() && _activeSessions.containsKey(item.getJID())) {
            _activeSessions.get(item.getJID()).stopSession();
        }
    }
    return false;
}
 
Example 6
Source File: Roster.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a List of all <b>available</b> Presence Objects for the given bare JID. If there are no available
 * presences, then the empty list will be returned.
 *
 * @param bareJid the bare JID from which the presences should be retrieved.
 * @return available presences for the bare JID.
 */
public List<Presence> getAvailablePresences(BareJid bareJid) {
    List<Presence> allPresences = getAllPresences(bareJid);
    List<Presence> res = new ArrayList<>(allPresences.size());
    for (Presence presence : allPresences) {
        if (presence.isAvailable()) {
            // No need to clone presence here, getAllPresences already returns clones
            res.add(presence);
        }
    }
    return res;
}
 
Example 7
Source File: NotificationPlugin.java    From Spark with Apache License 2.0 5 votes vote down vote up
@Override
public void processStanza(Stanza stanza) {
    final Presence presence = (Presence)stanza;
    Jid jid = presence.getFrom();
    if (jid == null) {
        return;
    }

    // Make sure the user is in the contact list.
    ContactItem contactItem = SparkManager.getWorkspace().getContactList().getContactItemByJID(jid);
    if (contactItem == null) {
        return;
    }

    BareJid bareJid = jid.asBareJid();
    boolean isOnline = onlineUsers.contains(jid);

    if (presence.isAvailable()) {
        if (preferences.isOnlineNotificationsOn()) {
            if (!isOnline) {
                notifyUserOnline(bareJid, presence);
            }
        }

        onlineUsers.add(bareJid);
    }
    else {
        if (preferences.isOfflineNotificationsOn() && isOnline) {
            notifyUserOffline(bareJid, presence);
        }

        onlineUsers.remove(bareJid);
    }
}
 
Example 8
Source File: XmppSubscriptionListener.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Listennig for a change in presence of the user, eg: unavailable => available
 *
 * @param presence
 */
@Override
public void presenceChanged(Presence presence) {
    String user = presence.getFrom();
    if (user.contains(xmppUserId) && presence.isAvailable()) {
        isOnline = true;
    }
}
 
Example 9
Source File: SparkTabHandler.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the SparkTab to show it is in a stale state.
 *
 * @param tab      the SparkTab.
 * @param chatRoom the ChatRoom of the SparkTab.
 */
protected void decorateStaleTab(SparkTab tab, ChatRoom chatRoom) {
    tab.setTitleColor(Color.gray);
    tab.setTabFont(tab.getDefaultFont());

    EntityBareJid jid = ((ChatRoomImpl)chatRoom).getParticipantJID();
    Presence presence = PresenceManager.getPresence(jid);

    if (!presence.isAvailable()) {
        tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_UNAVAILABLE_STALE_IMAGE));
    }
    else {
        Presence.Mode mode = presence.getMode();
        if (mode == Presence.Mode.available || mode == null) {
            tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_AVAILABLE_STALE_IMAGE));
        }
        else if (mode == Presence.Mode.away) {
            tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_AWAY_STALE_IMAGE));
        }
        else if (mode == Presence.Mode.chat) {
            tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_FREE_CHAT_STALE_IMAGE));
        }
        else if (mode == Presence.Mode.dnd) {
            tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_DND_STALE_IMAGE));
        }
        else if (mode == Presence.Mode.xa) {
            tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_DND_STALE_IMAGE));
        }
    }

    tab.validateTab();
}
 
Example 10
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 11
Source File: RosterTree.java    From Spark with Apache License 2.0 5 votes vote down vote up
private void changePresence(String user, Presence presence){
    for (Object o : addressMap.keySet()) {
        final JiveTreeNode node = (JiveTreeNode) o;
        final String nodeUser = addressMap.get(node);
        if (user.startsWith(nodeUser)) {
            if (!presence.isAvailable()) {
                node.setIcon(SparkRes.getImageIcon(SparkRes.CLEAR_BALL_ICON));
            } else {
                node.setIcon(SparkRes.getImageIcon(SparkRes.GREEN_BALL));
            }
        }
    }
}
 
Example 12
Source File: PresenceManager.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
    * Returns the icon associated with a users presence.
    *
    * @param presence the users presence.
    * @return the icon associated with it.
    */
   public static Icon getIconFromPresence(Presence presence) {
if (isInvisible(presence)) {
           return SparkRes.getImageIcon(SparkRes.CLEAR_BALL_ICON);
       }

       // Handle offline presence
       if (!presence.isAvailable()) {
           return SparkRes.getImageIcon(SparkRes.CLEAR_BALL_ICON);
       }

       Presence.Mode presenceMode = presence.getMode();
       if (presenceMode == null) {
           presenceMode = Presence.Mode.available;
       }

       Icon icon = null;

       if (presenceMode.equals(Presence.Mode.available)) {
           icon = SparkRes.getImageIcon(SparkRes.GREEN_BALL);
       }
       else if (presenceMode.equals(Presence.Mode.chat)) {
           icon = SparkRes.getImageIcon(SparkRes.FREE_TO_CHAT_IMAGE);
       }
       else if (isOnPhone(presence)) {
           icon = SparkRes.getImageIcon(SparkRes.ON_PHONE_IMAGE);
       }
       else if (presenceMode.equals(Presence.Mode.away)) {
           icon = SparkRes.getImageIcon(SparkRes.IM_AWAY);
       }
       else if (presenceMode.equals(Presence.Mode.dnd)) {
           icon = SparkRes.getImageIcon(SparkRes.IM_DND);
       }
       else if (presenceMode.equals(Presence.Mode.xa)) {
           icon = SparkRes.getImageIcon(SparkRes.IM_AWAY);
       }

       // Check For ContactItem handlers
       Icon handlerIcon = SparkManager.getChatManager().getTabIconForContactHandler(presence);
       if (handlerIcon != null) {
           icon = handlerIcon;
       }


       return icon;
   }
 
Example 13
Source File: OnlineAgents.java    From Spark with Apache License 2.0 4 votes vote down vote up
private String buildTooltip(Presence presence) {
    if (!presence.isAvailable()) {
        return FpRes.getString("message.user.not.logged.in");
    }

    AgentStatus agentStatus = presence.getExtension("agent-status", "http://jabber.org/protocol/workgroup");
    List<AgentStatus.ChatInfo> list = agentStatus.getCurrentChats();

    // Add new ones.
    Iterator<AgentStatus.ChatInfo> iter = list.iterator();
    StringBuilder buf = new StringBuilder();
    buf.append("<html>");
    buf.append("<body>");
    buf.append("<table>");

    while (iter.hasNext()) {
        AgentStatus.ChatInfo chatInfo = iter.next();
        Date startDate = chatInfo.getDate();

        String nickname = chatInfo.getUsername();
        if (!ModelUtil.hasLength(nickname)) {
            nickname = FpRes.getString("message.not.specified");
        }

        String question = chatInfo.getQuestion();
        if (!ModelUtil.hasLength(question)) {
            question = "No question asked";
        }

        String email = chatInfo.getEmail();
        if (!ModelUtil.hasLength(email)) {
            email = FpRes.getString("message.not.specified");
        }

        long startTime = startDate.getTime();
        long rightNow = System.currentTimeMillis();
        long totalTime = rightNow - startTime;
        String durationTime = ModelUtil.getTimeFromLong(totalTime);

        buf.append("<tr><td><b><u>Chatting with ").append(nickname).append("</u></b></td></tr>");
        buf.append("<tr><td>Email: ").append(email).append("</td></tr>");
        buf.append("<tr><td>Question: ").append(question).append("</td></tr>");
        buf.append("<tr><td>Chat Duration: ").append(durationTime).append("</td></tr>");
        buf.append("<tr><td><br></td></tr>");
    }

    if (list.size() == 0) {
        buf.append(FpRes.getString("message.agent.is.not.in.chat"));
    }

    buf.append("</table>");
    buf.append("</body>");
    buf.append("</html>");
    return buf.toString();
}
 
Example 14
Source File: PresenceManager.java    From Spark with Apache License 2.0 4 votes vote down vote up
public static boolean isAvailable(BareJid jid) {
    final Roster roster = Roster.getInstanceFor( SparkManager.getConnection() );
    Presence presence = roster.getPresence(jid);
    return presence.isAvailable() && !presence.isAway();
}
 
Example 15
Source File: MPAuthenticationProvider.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Read the PIN number sent by the user as the reply.
 *
 * @param connection
 * @param userName
 * @return
 */
public boolean getUserResponse(XMPPConnection connection, String userName) {

    String response = null;
    Presence presence = connection.getRoster().getPresence(userName);

    if (presence.isAvailable()) {
        try {

            ChatManager chatManager = connection.getChatManager();
            Chat chat = chatManager.createChat(userName, null);
            PacketFilter filter =
                    new AndFilter(new PacketTypeFilter(Message.class), new FromContainsFilter(userName));
            XmppResponseListener chatListener = new XmppResponseListener();
            connection.addPacketListener(chatListener, filter);

            if (isPINEnabled) {

                chat.sendMessage("Please reply with your PIN Number here.");

                if (log.isInfoEnabled()) {
                    log.info("User PIN is sent to the user and awaiting for the response.");
                }

                while (!chatListener.isResponseReceived()) {
                    Thread.sleep(100);
                }

                response = chatListener.getResponse();

                if (response != null) {
                    return userPIN.contentEquals(response.trim());
                }
            } else {
                chat.sendMessage(
                        "You are about to get authenticated for your OpenID. Do you want to continue: [Yes] or [No]");

                if (log.isInfoEnabled()) {
                    log.info("User PIN is sent to the user and awaiting for the response.");
                }

                while (!chatListener.isResponseReceived()) {
                    Thread.sleep(100);
                }

                response = chatListener.getResponse();

                if (response != null) {
                    if ("YES".equalsIgnoreCase(response.trim())) {
                        return true;
                    } else if ("NO".equalsIgnoreCase(response.trim())) {
                        return false;
                    } else {
                        pinDisabledResponse = false;
                        return false;
                    }
                }
            }

        } catch (Exception e) {
            log.error("Error while getting user response", e);
        }
    } else {
        return false;
    }
    return false;

}
 
Example 16
Source File: MPAuthenticationProvider.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Checking whether the user is available in the contact list.
 *
 * @param roster
 * @param userXmppId
 * @return
 */
public boolean checkforUserAvailability(Roster roster, String userXmppId) {
    boolean isAvailable = false;
    XmppSubscriptionListener listener = new XmppSubscriptionListener(userXmppId);
    roster.addRosterListener(listener);
    Presence presence = roster.getPresence(userXmppId);
    boolean status = isAvailable(roster, userXmppId);

    try {
        if (!status) {
            if (log.isInfoEnabled()) {
                log.info("The User is not subscribed.");
            }
            boolean contactAddStatus = new XmppSubscriber().addContact(roster, userXmppId);
            if (contactAddStatus) {
                if (log.isInfoEnabled()) {
                    log.info("User's Contact is added successfully..");
                }
            } else {
                if (log.isInfoEnabled()) {
                    log.info("Failed to add contact.");
                }
            }

            if (!presence.isAvailable()) {
                while (!listener.isOnline()) {
                    Thread.sleep(5000);
                }
            }
            isAvailable = true;

        } else {

            if (log.isInfoEnabled()) {
                log.info("User is not online..");
            }

            while (!listener.isOnline()) {
                Thread.sleep(5000);
            }
            isAvailable = true;
        }
    } catch (InterruptedException e) {
        log.error("Error while checking user availability", e);
    } finally {
        roster.removeRosterListener(listener);
    }

    return isAvailable;
}
 
Example 17
Source File: MPAuthenticationProvider.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Authenticating a particular user
 *
 * @return true if authentication is successful, and false otherwise.
 */
public boolean authenticate() {
    //creating the connection
    XMPPConnection connection = createConnection();

    //connecting to the server
    boolean connectionStatus = connect(connection);
    if (!connectionStatus) {
        log.info("Failed to connect to the Server");
        return false;
    }

    //signing in
    boolean loginStatus = login(connection);
    if (!loginStatus) {
        log.info("login failed");
        return false;
    }

    Roster roster = connection.getRoster();
    Presence presence = roster.getPresence(userXmppId);

    boolean isAvailable = false;

    if (!presence.isAvailable()) {
        isAvailable = checkforUserAvailability(roster, userXmppId);
    }

    if (!isAvailable) {
        log.info("user is not online");
        return false;
    }

    boolean validation = getUserResponse(connection, userXmppId);

    // Giving a second chance to provide the PIN
    if (!validation && !pinDisabledResponse) {
        validation = getUserResponse(connection, userXmppId);
    }
    return validation;
}
 
Example 18
Source File: PresenceManager.java    From Spark with Apache License 2.0 2 votes vote down vote up
/**
 * Returns true if the user is online and their mode is available or free to chat.
 *
 * @param presence the users presence.
 * @return true if the user is online and their mode is available or free to chat.
 */
public static boolean isAvailable(Presence presence) {
    return presence.isAvailable() && !presence.isAway();
}
 
Example 19
Source File: PresenceManager.java    From Spark with Apache License 2.0 2 votes vote down vote up
/**
 * Returns true if the user is online.
 *
 * @param jidString the jid of the user.
 * @return true if online.
 */
public static boolean isOnline(BareJid jid) {
    final Roster roster = Roster.getInstanceFor( SparkManager.getConnection() );
    Presence presence = roster.getPresence(jid);
    return presence.isAvailable();
}