Search in sources :

Example 96 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project Smack by igniterealtime.

the class FromMatchesFilterTest method autoCompareMatchingEntityFullJid.

@Test
public void autoCompareMatchingEntityFullJid() {
    FromMatchesFilter filter = FromMatchesFilter.create(FULL_JID1_R1);
    Stanza packet = StanzaBuilder.buildMessage().build();
    packet.setFrom(FULL_JID1_R1);
    assertTrue(filter.accept(packet));
    packet.setFrom(BASE_JID1);
    assertFalse(filter.accept(packet));
    packet.setFrom(FULL_JID1_R2);
    assertFalse(filter.accept(packet));
    packet.setFrom(BASE_JID2);
    assertFalse(filter.accept(packet));
    packet.setFrom(FULL_JID2);
    assertFalse(filter.accept(packet));
    packet.setFrom(BASE_JID3);
    assertFalse(filter.accept(packet));
}
Also used : Stanza(org.jivesoftware.smack.packet.Stanza) Test(org.junit.Test)

Example 97 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project Smack by igniterealtime.

the class MultiUserChat method changeSubject.

/**
 * Changes the subject within the room. As a default, only users with a role of "moderator"
 * are allowed to change the subject in a room. Although some rooms may be configured to
 * allow a mere participant or even a visitor to change the subject.
 *
 * @param subject the new room's subject to set.
 * @throws XMPPErrorException if someone without appropriate privileges attempts to change the
 *          room subject will throw an error with code 403 (i.e. Forbidden)
 * @throws NoResponseException if there was no response from the server.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public void changeSubject(final String subject) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    MessageBuilder message = buildMessage();
    message.setSubject(subject);
    // Wait for an error or confirmation message back from the server.
    StanzaFilter responseFilter = new AndFilter(fromRoomGroupchatFilter, new StanzaFilter() {

        @Override
        public boolean accept(Stanza packet) {
            Message msg = (Message) packet;
            return subject.equals(msg.getSubject());
        }
    });
    StanzaCollector response = connection.createStanzaCollectorAndSend(responseFilter, message.build());
    // Wait up to a certain number of seconds for a reply.
    response.nextResultOrThrow();
}
Also used : AndFilter(org.jivesoftware.smack.filter.AndFilter) StanzaFilter(org.jivesoftware.smack.filter.StanzaFilter) MessageBuilder(org.jivesoftware.smack.packet.MessageBuilder) Message(org.jivesoftware.smack.packet.Message) Stanza(org.jivesoftware.smack.packet.Stanza) StanzaCollector(org.jivesoftware.smack.StanzaCollector)

Example 98 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project Smack by igniterealtime.

the class JingleSession method updatePacketListener.

/**
 * Install the stanza listener. The listener is responsible for responding
 * to any stanza that we receive...
 */
void updatePacketListener() {
    removeAsyncPacketListener();
    LOGGER.fine("UpdatePacketListener");
    packetListener = new StanzaListener() {

        @Override
        public void processStanza(Stanza packet) {
            try {
                receivePacketAndRespond((IQ) packet);
            } catch (Exception e) {
                LOGGER.log(Level.WARNING, "exception", e);
            }
        }
    };
    packetFilter = new StanzaFilter() {

        @Override
        public boolean accept(Stanza packet) {
            if (packet instanceof IQ) {
                IQ iq = (IQ) packet;
                Jid me = getConnection().getUser();
                if (!iq.getTo().equals(me)) {
                    return false;
                }
                Jid other = getResponder().equals(me) ? getInitiator() : getResponder();
                if (iq.getFrom() == null || !iq.getFrom().equals(other == null ? "" : other)) {
                    return false;
                }
                if (iq instanceof Jingle) {
                    Jingle jin = (Jingle) iq;
                    String sid = jin.getSid();
                    if (sid == null || !sid.equals(getSid())) {
                        LOGGER.fine("Ignored Jingle(SID) " + sid + "|" + getSid() + " :" + iq.toXML());
                        return false;
                    }
                    Jid ini = jin.getInitiator();
                    if (!ini.equals(getInitiator())) {
                        LOGGER.fine("Ignored Jingle(INI): " + iq.toXML());
                        return false;
                    }
                } else {
                    // We accept some non-Jingle IQ packets: ERRORs and ACKs
                    if (iq.getType().equals(IQ.Type.set)) {
                        LOGGER.fine("Ignored Jingle(TYPE): " + iq.toXML());
                        return false;
                    } else if (iq.getType().equals(IQ.Type.get)) {
                        LOGGER.fine("Ignored Jingle(TYPE): " + iq.toXML());
                        return false;
                    }
                }
                return true;
            }
            return false;
        }
    };
    getConnection().addAsyncStanzaListener(packetListener, packetFilter);
}
Also used : Jingle(org.jivesoftware.smackx.jingleold.packet.Jingle) StanzaFilter(org.jivesoftware.smack.filter.StanzaFilter) Jid(org.jxmpp.jid.Jid) Stanza(org.jivesoftware.smack.packet.Stanza) IQ(org.jivesoftware.smack.packet.IQ) StanzaListener(org.jivesoftware.smack.StanzaListener) SmackException(org.jivesoftware.smack.SmackException) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) NoResponseException(org.jivesoftware.smack.SmackException.NoResponseException) XMPPErrorException(org.jivesoftware.smack.XMPPException.XMPPErrorException) XMPPException(org.jivesoftware.smack.XMPPException)

Example 99 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project Smack by igniterealtime.

the class XMPPTCPConnection method loginInternal.

@Override
protected synchronized void loginInternal(String username, String password, Resourcepart resource) throws XMPPException, SmackException, IOException, InterruptedException {
    // Authenticate using SASL
    SSLSession sslSession = secureSocket != null ? secureSocket.getSession() : null;
    streamFeaturesAfterAuthenticationReceived = false;
    authenticate(username, password, config.getAuthzid(), sslSession);
    // Wait for stream features after the authentication.
    // TODO: The name of this synchronization point "maybeCompressFeaturesReceived" is not perfect. It should be
    // renamed to "streamFeaturesAfterAuthenticationReceived".
    waitForConditionOrThrowConnectionException(() -> streamFeaturesAfterAuthenticationReceived, "compress features from server");
    // If compression is enabled then request the server to use stream compression. XEP-170
    // recommends to perform stream compression before resource binding.
    maybeEnableCompression();
    smResumedSyncPoint = SyncPointState.initial;
    smResumptionFailed = null;
    if (isSmResumptionPossible()) {
        smResumedSyncPoint = SyncPointState.request_sent;
        sendNonza(new Resume(clientHandledStanzasCount, smSessionId));
        waitForConditionOrConnectionException(() -> smResumedSyncPoint == SyncPointState.successful || smResumptionFailed != null, "resume previous stream");
        if (smResumedSyncPoint == SyncPointState.successful) {
            // We successfully resumed the stream, be done here
            afterSuccessfulLogin(true);
            return;
        }
        // normal resource binding can be tried.
        assert smResumptionFailed != null;
        LOGGER.fine("Stream resumption failed, continuing with normal stream establishment process: " + smResumptionFailed);
    }
    // We either failed to resume a previous stream management (SM) session, or we did not even try. In any case,
    // mark SM as not enabled. Most importantly, we do this prior calling bindResourceAndEstablishSession(), as the
    // bind IQ may trigger a SM ack request, which would be invalid in the pre resource bound state.
    smEnabledSyncPoint = false;
    List<Stanza> previouslyUnackedStanzas = new LinkedList<Stanza>();
    if (unacknowledgedStanzas != null) {
        // There was a previous connection with SM enabled but that was either not resumable or
        // failed to resume. Make sure that we (re-)send the unacknowledged stanzas.
        unacknowledgedStanzas.drainTo(previouslyUnackedStanzas);
        // Reset unacknowledged stanzas to 'null' to signal that we never send 'enable' in this
        // XMPP session (There maybe was an enabled in a previous XMPP session of this
        // connection instance though). This is used in writePackets to decide if stanzas should
        // be added to the unacknowledged stanzas queue, because they have to be added right
        // after the 'enable' stream element has been sent.
        dropSmState();
    }
    // Now bind the resource. It is important to do this *after* we dropped an eventually
    // existing Stream Management state. As otherwise <bind/> and <session/> may end up in
    // unacknowledgedStanzas and become duplicated on reconnect. See SMACK-706.
    bindResourceAndEstablishSession(resource);
    if (isSmAvailable() && useSm) {
        // Remove what is maybe left from previously stream managed sessions
        serverHandledStanzasCount = 0;
        sendNonza(new Enable(useSmResumption, smClientMaxResumptionTime));
        // XEP-198 3. Enabling Stream Management. If the server response to 'Enable' is 'Failed'
        // then this is a non recoverable error and we therefore throw an exception.
        waitForConditionOrThrowConnectionException(() -> smEnabledSyncPoint, "enabling stream mangement");
        synchronized (requestAckPredicates) {
            if (requestAckPredicates.isEmpty()) {
                // Assure that we have at lest one predicate set up that so that we request acks
                // for the server and eventually flush some stanzas from the unacknowledged
                // stanza queue
                requestAckPredicates.add(Predicate.forMessagesOrAfter5Stanzas());
            }
        }
    }
    // before it is informed about connection success
    if (!stanzaDroppedListeners.isEmpty()) {
        for (Stanza stanza : previouslyUnackedStanzas) {
            for (StanzaListener listener : stanzaDroppedListeners) {
                try {
                    listener.processStanza(stanza);
                } catch (InterruptedException | NotConnectedException | NotLoggedInException e) {
                    LOGGER.log(Level.FINER, "StanzaDroppedListener received exception", e);
                }
            }
        }
    } else {
        for (Stanza stanza : previouslyUnackedStanzas) {
            sendStanzaInternal(stanza);
        }
    }
    afterSuccessfulLogin(false);
}
Also used : NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) Stanza(org.jivesoftware.smack.packet.Stanza) SSLSession(javax.net.ssl.SSLSession) Enable(org.jivesoftware.smack.sm.packet.StreamManagement.Enable) StanzaListener(org.jivesoftware.smack.StanzaListener) NotLoggedInException(org.jivesoftware.smack.SmackException.NotLoggedInException) LinkedList(java.util.LinkedList) Resume(org.jivesoftware.smack.sm.packet.StreamManagement.Resume)

Example 100 with Stanza

use of org.jivesoftware.smack.packet.Stanza in project Smack by igniterealtime.

the class XMPPTCPConnection method processHandledCount.

private void processHandledCount(long handledCount) throws StreamManagementCounterError {
    long ackedStanzasCount = SMUtils.calculateDelta(handledCount, serverHandledStanzasCount);
    final List<Stanza> ackedStanzas = new ArrayList<>(ackedStanzasCount <= Integer.MAX_VALUE ? (int) ackedStanzasCount : Integer.MAX_VALUE);
    for (long i = 0; i < ackedStanzasCount; i++) {
        Stanza ackedStanza = unacknowledgedStanzas.poll();
        // unacknowledged stanza queue. There can be no exception.
        if (ackedStanza == null) {
            throw new StreamManagementCounterError(handledCount, serverHandledStanzasCount, ackedStanzasCount, ackedStanzas);
        }
        ackedStanzas.add(ackedStanza);
    }
    boolean atLeastOneStanzaAcknowledgedListener = false;
    if (!stanzaAcknowledgedListeners.isEmpty()) {
        // If stanzaAcknowledgedListeners is not empty, the we have at least one
        atLeastOneStanzaAcknowledgedListener = true;
    } else {
        // Otherwise we look for a matching id in the stanza *id* acknowledged listeners
        for (Stanza ackedStanza : ackedStanzas) {
            String id = ackedStanza.getStanzaId();
            if (id != null && stanzaIdAcknowledgedListeners.containsKey(id)) {
                atLeastOneStanzaAcknowledgedListener = true;
                break;
            }
        }
    }
    // Only spawn a new thread if there is a chance that some listener is invoked
    if (atLeastOneStanzaAcknowledgedListener) {
        asyncGo(new Runnable() {

            @Override
            public void run() {
                for (Stanza ackedStanza : ackedStanzas) {
                    for (StanzaListener listener : stanzaAcknowledgedListeners) {
                        try {
                            listener.processStanza(ackedStanza);
                        } catch (InterruptedException | NotConnectedException | NotLoggedInException e) {
                            LOGGER.log(Level.FINER, "Received exception", e);
                        }
                    }
                    String id = ackedStanza.getStanzaId();
                    if (StringUtils.isNullOrEmpty(id)) {
                        continue;
                    }
                    StanzaListener listener = stanzaIdAcknowledgedListeners.remove(id);
                    if (listener != null) {
                        try {
                            listener.processStanza(ackedStanza);
                        } catch (InterruptedException | NotConnectedException | NotLoggedInException e) {
                            LOGGER.log(Level.FINER, "Received exception", e);
                        }
                    }
                }
            }
        });
    }
    serverHandledStanzasCount = handledCount;
}
Also used : StreamManagementCounterError(org.jivesoftware.smack.sm.StreamManagementException.StreamManagementCounterError) Stanza(org.jivesoftware.smack.packet.Stanza) ArrayList(java.util.ArrayList) StanzaListener(org.jivesoftware.smack.StanzaListener)

Aggregations

Stanza (org.jivesoftware.smack.packet.Stanza)101 StanzaListener (org.jivesoftware.smack.StanzaListener)24 Test (org.junit.Test)22 IQ (org.jivesoftware.smack.packet.IQ)20 Test (org.junit.jupiter.api.Test)18 XMPPConnection (org.jivesoftware.smack.XMPPConnection)14 Message (org.jivesoftware.smack.packet.Message)14 ArrayList (java.util.ArrayList)11 SmackException (org.jivesoftware.smack.SmackException)11 Jid (org.jxmpp.jid.Jid)11 IOException (java.io.IOException)9 NotConnectedException (org.jivesoftware.smack.SmackException.NotConnectedException)8 StanzaFilter (org.jivesoftware.smack.filter.StanzaFilter)8 Bytestream (org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream)7 DelayInformation (org.jivesoftware.smackx.delay.packet.DelayInformation)7 XMPPErrorException (org.jivesoftware.smack.XMPPException.XMPPErrorException)6 StanzaTypeFilter (org.jivesoftware.smack.filter.StanzaTypeFilter)6 Protocol (org.jivesoftware.util.Protocol)6 EntityFullJid (org.jxmpp.jid.EntityFullJid)6 LinkedList (java.util.LinkedList)5