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

The following examples show how to use org.jivesoftware.smack.packet.Presence#setTo() . 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: 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 2
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 3
Source File: InstantMessagingClient.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a subscription request to the username answers are handled by the method
 * 
 * @param uname
 * @param groupname
 */
protected void subscribeToUser(final String uname, final String groupname) {
    final Presence presence = new Presence(Presence.Type.subscribe);
    presence.setTo(uname + "@" + jabberServer);
    try {
        connection.sendPacket(presence);

        final RosterPacket rosterPacket = new RosterPacket();
        rosterPacket.setType(IQ.Type.SET);
        final RosterPacket.Item item = new RosterPacket.Item(uname + "@" + jabberServer, uname);
        item.addGroupName(groupname);
        item.setItemType(RosterPacket.ItemType.both);
        rosterPacket.addRosterItem(item);
        connection.sendPacket(rosterPacket);
    } catch (final RuntimeException e) {
        log.warn("Error while trying to send Instant Messaging packet.", e);
    }
}
 
Example 4
Source File: InstantMessagingClient.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a subscription request to the username answers are handled by the method
 * 
 * @param uname
 * @param groupname
 */
protected void subscribeToUser(final String uname, final String groupname) {
    final Presence presence = new Presence(Presence.Type.subscribe);
    presence.setTo(uname + "@" + jabberServer);
    try {
        connection.sendPacket(presence);

        final RosterPacket rosterPacket = new RosterPacket();
        rosterPacket.setType(IQ.Type.SET);
        final RosterPacket.Item item = new RosterPacket.Item(uname + "@" + jabberServer, uname);
        item.addGroupName(groupname);
        item.setItemType(RosterPacket.ItemType.both);
        rosterPacket.addRosterItem(item);
        connection.sendPacket(rosterPacket);
    } catch (final RuntimeException e) {
        log.warn("Error while trying to send Instant Messaging packet.", e);
    }
}
 
Example 5
Source File: MessageTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Will a user recieve a message from another after only sending the user a directed presence,
 * or will Wildfire intercept for offline storage?
 *
 * User1 becomes lines. User0 never sent an available presence to the server but
 * instead sent one to User1. User1 sends a message to User0. Should User0 get the
 * message?
 */
public void testDirectPresence() {
    getConnection(1).sendStanza(new Presence(Presence.Type.available));

    Presence presence = new Presence(Presence.Type.available);
    presence.setTo(getBareJID(1));
    getConnection(0).sendStanza(presence);

    StanzaCollector collector = getConnection(0)
            .createStanzaCollector(new MessageTypeFilter(Message.Type.chat));
    try {
        getConnection(1).getChatManager().createChat(getBareJID(0), null).sendMessage("Test 1");
    }
    catch (XMPPException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    Message message = (Message) collector.nextResult(2500);
    assertNotNull("Message not recieved from remote user", message);
}
 
Example 6
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 7
Source File: RosterManager.java    From mangosta-android with Apache License 2.0 5 votes vote down vote up
public void removeAllContacts()
        throws SmackException.NotLoggedInException, InterruptedException,
        SmackException.NotConnectedException, XMPPException.XMPPErrorException,
        SmackException.NoResponseException {
    Roster roster = Roster.getInstanceFor(XMPPSession.getInstance().getXMPPConnection());
    if (!roster.isLoaded()) {
        roster.reloadAndWait();
    }
    for (RosterEntry entry : roster.getEntries()) {
        roster.removeEntry(entry);
        Presence presence = new Presence(Presence.Type.unsubscribe);
        presence.setTo(entry.getJid());
        XMPPSession.getInstance().sendStanza(presence);
    }
}
 
Example 8
Source File: SubscriptionDialog.java    From Spark with Apache License 2.0 5 votes vote down vote up
private void unsubscribeAndClose()
{
    Presence response = new Presence(Presence.Type.unsubscribe);
    response.setTo(jid);
    try
    {
        SparkManager.getConnection().sendStanza(response);
    }
    catch ( SmackException.NotConnectedException | InterruptedException e )
    {
        Log.warning( "Unable to send stanza unsubscribing from " + jid, e );
    }

    dialog.dispose();
}
 
Example 9
Source File: UriManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
    * Handles the ?subscribe URI
    * 
    * @param uri
    *            the decoded uri
    * @throws Exception
    */
   public void handleSubscribe(URI uri) throws Exception {
// xmpp:[email protected]?subscribe
// Send contact add request
Jid jid = retrieveJID(uri);

Presence response = new Presence(Presence.Type.subscribe);
response.setTo(jid);
SparkManager.getConnection().sendStanza(response);
   }
 
Example 10
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 11
Source File: LeaguePacketListener.java    From League-of-Legends-XMPP-Chat-Library with MIT License 5 votes vote down vote up
private void accept(String from) throws NotConnectedException {
	final Presence newp = new Presence(Presence.Type.subscribed);
	newp.setTo(from);
	connection.sendPacket(newp);
	final Presence subscription = new Presence(Presence.Type.subscribe);
	subscription.setTo(from);
	connection.sendPacket(subscription);
	if (api.isOnline()) {
		api.setOnline();
	}
}
 
Example 12
Source File: PrivacyPresenceHandler.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Send Unavailable (offline status) to jid .
 * 
 * @param jid
 *            JID to send offline status
 * @throws InterruptedException 
 */
public void sendUnavailableTo(Jid jid) throws SmackException.NotConnectedException
{
    Presence pack = new Presence(Presence.Type.unavailable);                                                  
    pack.setTo(jid);
    try {
        SparkManager.getConnection().sendStanza(pack);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 13
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 14
Source File: ClientManagerImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * helper method to trigger a presence update even if the server does not send a presence packet itself (e.g. entering a test but no other buddies are online)
 * 
 * @param username
 */
@Override
public void sendPresenceEvent(final Presence.Type type, final String username) {
    final Presence presence = new Presence(type);
    presence.setTo(username);
    final GenericEventListener listener = listeners.get(username);
    if (listener != null) {
        listener.event(new InstantMessagingEvent(presence, "presence"));
    }
}
 
Example 15
Source File: PrivacyPresenceHandler.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Send my presence for user
 * 
 * @param jid
 *            JID to send presence
 */
public void sendRealPresenceTo(Jid jid) throws SmackException.NotConnectedException
{
    Presence presence = SparkManager.getWorkspace().getStatusBar().getPresence(); 
    Presence pack = new Presence(presence.getType(), presence.getStatus(), 1, presence.getMode()); 
    pack.setTo(jid);
    try {
        SparkManager.getConnection().sendStanza(pack);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 16
Source File: InstantMessagingClient.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Ask an other online user to subscribe to their roster
 * 
 * @param uname
 */
protected void subscribeToUser(final String uname) {
    final Presence presence = new Presence(Presence.Type.subscribe);
    presence.setTo(uname + "@" + jabberServer);
    try {
        connection.sendPacket(presence);
    } catch (final RuntimeException e) {
        log.warn("Error while trying to send Instant Messaging packet.", e);
    }

}
 
Example 17
Source File: LeaguePacketListener.java    From League-of-Legends-XMPP-Chat-Library with MIT License 4 votes vote down vote up
private void decline(String from) throws NotConnectedException {
	final Presence newp = new Presence(Presence.Type.unsubscribed);
	newp.setTo(from);
	connection.sendPacket(newp);
}
 
Example 18
Source File: SubscriptionHandler.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
private void sendPresence(Presence.Type type, String to) {
  Presence presence = new Presence(type);
  presence.setTo(to);
  presence.setFrom(connection.getUser());
  connection.sendPacket(presence);
}
 
Example 19
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 20
Source File: Workspace.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
  * Starts the Loading of all Spark Plugins.
  */
 public void loadPlugins() {
 
     // Send Available status
     SparkManager.getSessionManager().changePresence(statusBox.getPresence());
     
     // Add presence and message listeners
     // we listen for these to force open a 1-1 peer chat window from other operators if
     // one isn't already open
     StanzaFilter workspaceMessageFilter = new StanzaTypeFilter(Message.class);

     // Add the packetListener to this instance
     SparkManager.getSessionManager().getConnection().addAsyncStanzaListener(this, workspaceMessageFilter);

     // Make presence available to anonymous requests, if from anonymous user in the system.
     StanzaListener workspacePresenceListener = stanza -> {
         Presence presence = (Presence)stanza;
         JivePropertiesExtension extension = (JivePropertiesExtension) presence.getExtension( JivePropertiesExtension.NAMESPACE );
         if (extension != null && extension.getProperty("anonymous") != null) {
             boolean isAvailable = statusBox.getPresence().getMode() == Presence.Mode.available;
             Presence reply = new Presence(Presence.Type.available);
             if (!isAvailable) {
                 reply.setType(Presence.Type.unavailable);
             }
             reply.setTo(presence.getFrom());
             try
             {
                 SparkManager.getSessionManager().getConnection().sendStanza(reply);
             }
             catch ( SmackException.NotConnectedException e )
             {
                 Log.warning( "Unable to send presence reply to " + reply.getTo(), e );
             }
         }
     };

     SparkManager.getSessionManager().getConnection().addAsyncStanzaListener(workspacePresenceListener, new StanzaTypeFilter(Presence.class));

     // Until we have better plugin management, will init after presence updates.
     gatewayPlugin = new GatewayPlugin();
     gatewayPlugin.initialize();

     // Load all non-presence related items.
     conferences.loadConferenceBookmarks();
     SearchManager.getInstance();
     transcriptPlugin = new ChatTranscriptPlugin();

     // Load Broadcast Plugin
     broadcastPlugin = new BroadcastPlugin();
     broadcastPlugin.initialize();

     // Load BookmarkPlugin
     bookmarkPlugin = new BookmarkPlugin();
     bookmarkPlugin.initialize();

     // Schedule loading of the plugins after two seconds.
     TaskEngine.getInstance().schedule(new TimerTask() {
         @Override
public void run() {
             final PluginManager pluginManager = PluginManager.getInstance();

             SparkManager.getMainWindow().addMainWindowListener(pluginManager);
             pluginManager.initializePlugins();

             // Subscriptions are always manual
             Roster roster = Roster.getInstanceFor( SparkManager.getConnection() );
             roster.setSubscriptionMode(Roster.SubscriptionMode.manual);
         }
     }, 2000);

     // Check URI Mappings
     SparkManager.getChatManager().handleURIMapping(Spark.ARGUMENTS);
 }