org.jivesoftware.smack.filter.StanzaIdFilter Java Examples

The following examples show how to use org.jivesoftware.smack.filter.StanzaIdFilter. 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: Gateway.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the fully qualified JID of a user.
 *
 * @param serviceName the service the user belongs to.
 * @param username    the name of the user.
 * @return the JID.
 * @throws InterruptedException 
 */
public static String getJID(DomainBareJid serviceName, String username) throws SmackException.NotConnectedException, InterruptedException
{
    Gateway registration = new Gateway();
    registration.setType(IQ.Type.set);
    registration.setTo(serviceName);
    registration.setUsername(username);

    XMPPConnection con = SparkManager.getConnection();
    StanzaCollector collector = con.createStanzaCollector(new StanzaIdFilter(registration.getStanzaId()));
    try
    {
        con.sendStanza( registration );

        Gateway response = collector.nextResult();
        return response.getJid();
    }
    finally
    {
        collector.cancel();
    }
}
 
Example #2
Source File: AbstractXMPPConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
protected Resourcepart bindResourceAndEstablishSession(Resourcepart resource)
                throws SmackException, InterruptedException, XMPPException {
    // Wait until either:
    // - the servers last features stanza has been parsed
    // - the timeout occurs
    LOGGER.finer("Waiting for last features to be received before continuing with resource binding");
    waitForConditionOrThrowConnectionException(() -> lastFeaturesReceived, "last stream features received from server");

    if (!hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
        // Server never offered resource binding, which is REQUIRED in XMPP client and
        // server implementations as per RFC6120 7.2
        throw new ResourceBindingNotOfferedException();
    }

    // Resource binding, see RFC6120 7.
    // Note that we can not use IQReplyFilter here, since the users full JID is not yet
    // available. It will become available right after the resource has been successfully bound.
    Bind bindResource = Bind.newSet(resource);
    StanzaCollector packetCollector = createStanzaCollectorAndSend(new StanzaIdFilter(bindResource), bindResource);
    Bind response = packetCollector.nextResultOrThrow();
    // Set the connections user to the result of resource binding. It is important that we don't infer the user
    // from the login() arguments and the configurations service name, as, for example, when SASL External is used,
    // the username is not given to login but taken from the 'external' certificate.
    user = response.getJid();
    xmppServiceDomain = user.asDomainBareJid();

    Session.Feature sessionFeature = getFeature(Session.ELEMENT, Session.NAMESPACE);
    // Only bind the session if it's announced as stream feature by the server, is not optional and not disabled
    // For more information see http://tools.ietf.org/html/draft-cridland-xmpp-session-01
    if (sessionFeature != null && !sessionFeature.isOptional()) {
        Session session = new Session();
        packetCollector = createStanzaCollectorAndSend(new StanzaIdFilter(session), session);
        packetCollector.nextResultOrThrow();
    }

    return response.getJid().getResourcepart();
}
 
Example #3
Source File: MultiUserChat.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Leave the chat room.
 *
 * @return the leave presence as reflected by the MUC.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws MucNotJoinedException if not joined to the Multi-User Chat.
 */
public synchronized Presence leave()
                throws NotConnectedException, InterruptedException, NoResponseException, XMPPErrorException, MucNotJoinedException {
    //  Note that this method is intentionally not guarded by
    // "if  (!joined) return" because it should be always be possible to leave the room in case the instance's
    // state does not reflect the actual state.

    final EntityFullJid myRoomJid = this.myRoomJid;
    if (myRoomJid == null) {
        throw new MucNotJoinedException(this);
    }

    // We leave a room by sending a presence packet where the "to"
    // field is in the form "roomName@service/nickname"
    Presence leavePresence = connection.getStanzaFactory().buildPresenceStanza()
            .ofType(Presence.Type.unavailable)
            .to(myRoomJid)
            .build();

    StanzaFilter reflectedLeavePresenceFilter = new AndFilter(
                    StanzaTypeFilter.PRESENCE,
                    new StanzaIdFilter(leavePresence),
                    new OrFilter(
                                    new AndFilter(FromMatchesFilter.createFull(myRoomJid), PresenceTypeFilter.UNAVAILABLE, MUCUserStatusCodeFilter.STATUS_110_PRESENCE_TO_SELF),
                                    new AndFilter(fromRoomFilter, PresenceTypeFilter.ERROR)
                                )
                            );

    // Reset occupant information first so that we are assume that we left the room even if sendStanza() would
    // throw.
    userHasLeft();

    Presence reflectedLeavePresence = connection.createStanzaCollectorAndSend(reflectedLeavePresenceFilter, leavePresence).nextResultOrThrow();

    return reflectedLeavePresence;
}
 
Example #4
Source File: MultiUserChat.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Enter a room, as described in XEP-45 7.2.
 *
 * @param conf the configuration used to enter the room.
 * @return the returned presence by the service after the client send the initial presence in order to enter the room.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws NotAMucServiceException if the entity is not a MUC serivce.
 * @see <a href="http://xmpp.org/extensions/xep-0045.html#enter">XEP-45 7.2 Entering a Room</a>
 */
private Presence enter(MucEnterConfiguration conf) throws NotConnectedException, NoResponseException,
                XMPPErrorException, InterruptedException, NotAMucServiceException {
    final DomainBareJid mucService = room.asDomainBareJid();
    if (!multiUserChatManager.providesMucService(mucService)) {
        throw new NotAMucServiceException(this);
    }
    // We enter a room by sending a presence packet where the "to"
    // field is in the form "roomName@service/nickname"
    Presence joinPresence = conf.getJoinPresence(this);

    // Setup the messageListeners and presenceListeners *before* the join presence is send.
    connection.addStanzaListener(messageListener, fromRoomGroupchatFilter);
    StanzaFilter presenceFromRoomFilter = new AndFilter(fromRoomFilter,
                    StanzaTypeFilter.PRESENCE,
                    PossibleFromTypeFilter.ENTITY_FULL_JID);
    connection.addStanzaListener(presenceListener, presenceFromRoomFilter);
    // @formatter:off
    connection.addStanzaListener(subjectListener,
                    new AndFilter(fromRoomFilter,
                                  MessageWithSubjectFilter.INSTANCE,
                                  new NotFilter(MessageTypeFilter.ERROR),
                                  // According to XEP-0045 ยง 8.1 "A message with a <subject/> and a <body/> or a <subject/> and a <thread/> is a
                                  // legitimate message, but it SHALL NOT be interpreted as a subject change."
                                  new NotFilter(MessageWithBodiesFilter.INSTANCE),
                                  new NotFilter(MessageWithThreadFilter.INSTANCE))
                    );
    // @formatter:on
    connection.addStanzaListener(declinesListener, new AndFilter(fromRoomFilter, DECLINE_FILTER));
    connection.addStanzaSendingListener(presenceInterceptor, new AndFilter(ToMatchesFilter.create(room),
                    StanzaTypeFilter.PRESENCE));
    messageCollector = connection.createStanzaCollector(fromRoomGroupchatFilter);

    // Wait for a presence packet back from the server.
    // @formatter:off
    StanzaFilter responseFilter = new AndFilter(StanzaTypeFilter.PRESENCE,
                    new OrFilter(
                        // We use a bare JID filter for positive responses, since the MUC service/room may rewrite the nickname.
                        new AndFilter(FromMatchesFilter.createBare(getRoom()), MUCUserStatusCodeFilter.STATUS_110_PRESENCE_TO_SELF),
                        // In case there is an error reply, we match on an error presence with the same stanza id and from the full
                        // JID we send the join presence to.
                        new AndFilter(FromMatchesFilter.createFull(joinPresence.getTo()), new StanzaIdFilter(joinPresence), PresenceTypeFilter.ERROR)
                    )
                );
    // @formatter:on
    StanzaCollector presenceStanzaCollector = null;
    Presence presence;
    try {
        // This stanza collector will collect the final self presence from the MUC, which also signals that we have successful entered the MUC.
        StanzaCollector selfPresenceCollector = connection.createStanzaCollectorAndSend(responseFilter, joinPresence);
        StanzaCollector.Configuration presenceStanzaCollectorConfguration = StanzaCollector.newConfiguration().setCollectorToReset(
                        selfPresenceCollector).setStanzaFilter(presenceFromRoomFilter);
        // This stanza collector is used to reset the timeout of the selfPresenceCollector.
        presenceStanzaCollector = connection.createStanzaCollector(presenceStanzaCollectorConfguration);
        presence = selfPresenceCollector.nextResultOrThrow(conf.getTimeout());
    }
    catch (NotConnectedException | InterruptedException | NoResponseException | XMPPErrorException e) {
        // Ensure that all callbacks are removed if there is an exception
        removeConnectionCallbacks();
        throw e;
    }
    finally {
        if (presenceStanzaCollector != null) {
            presenceStanzaCollector.cancel();
        }
    }

    // This presence must be send from a full JID. We use the resourcepart of this JID as nick, since the room may
    // performed roomnick rewriting
    Resourcepart receivedNickname = presence.getFrom().getResourceOrThrow();
    setNickname(receivedNickname);

    // Update the list of joined rooms
    multiUserChatManager.addJoinedRoom(room);
    return presence;
}
 
Example #5
Source File: AccountManager.java    From Smack with Apache License 2.0 4 votes vote down vote up
private StanzaCollector createStanzaCollectorAndSend(IQ req) throws NotConnectedException, InterruptedException {
    return connection().createStanzaCollectorAndSend(new StanzaIdFilter(req.getStanzaId()), req);
}
 
Example #6
Source File: TicTacToePlugin.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
    * Add the TTT-Button to every opening Chatroom
    * and create Listeners for it
    */
   private void addButtonToToolBar() {


_chatRoomListener = new ChatRoomListenerAdapter() {
    @Override
    public void chatRoomOpened(final ChatRoom room) {
	
	if(!(room instanceof ChatRoomImpl))
	{
	    // Don't do anything if this is not a 1on1-Chat
	    return;
	}
	
	final ChatRoomButton sendGameButton = new ChatRoomButton(buttonimg);
	room.getToolBar().addChatRoomButton(sendGameButton);

	final EntityFullJid opponentJID = ((ChatRoomImpl) room).getJID();

	sendGameButton.addActionListener(new ActionListener() {

	    @Override
	    public void actionPerformed(ActionEvent e) {
		
		if(_currentInvitations.contains(opponentJID.asBareJid()))
		{
		    return;
		}
		
		final GameOfferPacket offer = new GameOfferPacket();
		offer.setTo(opponentJID);
		offer.setType(IQ.Type.get );
		
		_currentInvitations.add(opponentJID.asEntityBareJid());
		room.getTranscriptWindow().insertCustomText
		    (TTTRes.getString("ttt.request.sent"), false, false, Color.BLUE);
			try
			{
				SparkManager.getConnection().sendStanza(offer);
			}
			catch ( SmackException.NotConnectedException | InterruptedException e1 )
			{
				Log.warning( "Unable to send offer to " + opponentJID, e1 );
			}

			SparkManager.getConnection().addAsyncStanzaListener(
			new StanzaListener() {
			    @Override
			    public void processStanza(Stanza stanza) {

				GameOfferPacket answer = (GameOfferPacket)stanza;
				answer.setStartingPlayer(offer.isStartingPlayer());
				answer.setGameID(offer.getGameID());
				if (answer.getType() == IQ.Type.result) {
				    // ACCEPT
				    _currentInvitations.remove(opponentJID.asBareJid());
				    
				    room.getTranscriptWindow().insertCustomText
				    (TTTRes.getString("ttt.request.accept"), false, false, Color.BLUE);
				    
				    createTTTWindow(answer, opponentJID);
				} else {
				    // DECLINE
				    room.getTranscriptWindow().insertCustomText
				    (TTTRes.getString("ttt.request.decline"), false, false, Color.RED);
				    _currentInvitations.remove(opponentJID.asBareJid());
				}

			    }
			},
			// TODO: Just filtering by stanza id is insure, should use Smack's IQ send-response mechanisms.
			new StanzaIdFilter(offer));
	    }
	});

    }

    @Override
    public void chatRoomClosed(ChatRoom room) {
	if (room instanceof ChatRoomImpl) {
	    ChatRoomImpl cri = (ChatRoomImpl) room;
	    _currentInvitations.remove(cri.getParticipantJID());
	}
    }
};


SparkManager.getChatManager().addChatRoomListener(_chatRoomListener);

   }