Search in sources :

Example 16 with NotConnectedException

use of org.jivesoftware.smack.SmackException.NotConnectedException in project Smack by igniterealtime.

the class IntTestUtil method disconnectAndMaybeDelete.

public static void disconnectAndMaybeDelete(XMPPTCPConnection connection, Configuration config) throws InterruptedException {
    try {
        if (!config.isAccountRegistrationPossible()) {
            return;
        }
        Configuration.AccountRegistration accountDeletionMethod = config.accountRegistration;
        AccountManager accountManager = AccountManager.getInstance(connection);
        try {
            if (accountManager.isSupported()) {
                accountDeletionMethod = AccountRegistration.inBandRegistration;
            }
        } catch (NoResponseException | XMPPErrorException | NotConnectedException e) {
            LOGGER.log(Level.WARNING, "Could not test if XEP-0077 account deletion is possible", e);
        }
        switch(accountDeletionMethod) {
            case inBandRegistration:
                deleteViaIbr(connection);
                break;
            case serviceAdministration:
                deleteViaServiceAdministration(connection, config);
                break;
            default:
                throw new AssertionError();
        }
    } finally {
        connection.disconnect();
    }
}
Also used : XMPPErrorException(org.jivesoftware.smack.XMPPException.XMPPErrorException) AccountRegistration(org.igniterealtime.smack.inttest.Configuration.AccountRegistration) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) AccountManager(org.jivesoftware.smackx.iqregister.AccountManager) NoResponseException(org.jivesoftware.smack.SmackException.NoResponseException)

Example 17 with NotConnectedException

use of org.jivesoftware.smack.SmackException.NotConnectedException in project Smack by igniterealtime.

the class EntityCapsTest method testEntityCaps.

@SmackIntegrationTest
public void testEntityCaps() throws XMPPException, InterruptedException, NoResponseException, NotConnectedException, TimeoutException {
    final String dummyFeature = getNewDummyFeature();
    dropWholeEntityCapsCache();
    performActionAndWaitUntilStanzaReceived(new Runnable() {

        @Override
        public void run() {
            sdmTwo.addFeature(dummyFeature);
        }
    }, connection, new AndFilter(PresenceTypeFilter.AVAILABLE, FromMatchesFilter.create(conTwo.getUser())));
    waitUntilTrue(new Condition() {

        @Override
        public boolean evaluate() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
            DiscoverInfo info = sdmOne.discoverInfo(conTwo.getUser());
            return info.containsFeature(dummyFeature);
        }
    });
    DiscoverInfo info = sdmOne.discoverInfo(conTwo.getUser());
    String u1ver = EntityCapsManager.getNodeVersionByJid(conTwo.getUser());
    assertNotNull(u1ver);
    DiscoverInfo entityInfo = EntityCapsManager.CAPS_CACHE.lookup(u1ver);
    assertNotNull(entityInfo);
    assertEquals(info.toXML(), entityInfo.toXML());
}
Also used : AndFilter(org.jivesoftware.smack.filter.AndFilter) DiscoverInfo(org.jivesoftware.smackx.disco.packet.DiscoverInfo) XMPPErrorException(org.jivesoftware.smack.XMPPException.XMPPErrorException) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) NoResponseException(org.jivesoftware.smack.SmackException.NoResponseException) SmackIntegrationTest(org.igniterealtime.smack.inttest.SmackIntegrationTest) AbstractSmackIntegrationTest(org.igniterealtime.smack.inttest.AbstractSmackIntegrationTest)

Example 18 with NotConnectedException

use of org.jivesoftware.smack.SmackException.NotConnectedException in project Smack by igniterealtime.

the class XMPPTCPConnection method shutdown.

private void shutdown(boolean instant) {
    if (disconnectedButResumeable) {
        return;
    }
    // the server
    if (packetWriter != null) {
        LOGGER.finer("PacketWriter shutdown()");
        packetWriter.shutdown(instant);
    }
    LOGGER.finer("PacketWriter has been shut down");
    if (!instant) {
        try {
            // After we send the closing stream element, check if there was already a
            // closing stream element sent by the server or wait with a timeout for a
            // closing stream element to be received from the server.
            @SuppressWarnings("unused") Exception res = closingStreamReceived.checkIfSuccessOrWait();
        } catch (InterruptedException | NoResponseException e) {
            LOGGER.log(Level.INFO, "Exception while waiting for closing stream element from the server " + this, e);
        }
    }
    if (packetReader != null) {
        LOGGER.finer("PacketReader shutdown()");
        packetReader.shutdown();
    }
    LOGGER.finer("PacketReader has been shut down");
    try {
        socket.close();
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "shutdown", e);
    }
    setWasAuthenticated();
    // connected (e.g. sendStanza should not throw a NotConnectedException).
    if (isSmResumptionPossible() && instant) {
        disconnectedButResumeable = true;
    } else {
        disconnectedButResumeable = false;
        // Reset the stream management session id to null, since if the stream is cleanly closed, i.e. sending a closing
        // stream tag, there is no longer a stream to resume.
        smSessionId = null;
    }
    authenticated = false;
    connected = false;
    secureSocket = null;
    reader = null;
    writer = null;
    maybeCompressFeaturesReceived.init();
    compressSyncPoint.init();
    smResumedSyncPoint.init();
    smEnabledSyncPoint.init();
    initalOpenStreamSend.init();
}
Also used : NoResponseException(org.jivesoftware.smack.SmackException.NoResponseException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) FailedNonzaException(org.jivesoftware.smack.XMPPException.FailedNonzaException) XmppStringprepException(org.jxmpp.stringprep.XmppStringprepException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) XMPPException(org.jivesoftware.smack.XMPPException) ConnectionException(org.jivesoftware.smack.SmackException.ConnectionException) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) StreamErrorException(org.jivesoftware.smack.XMPPException.StreamErrorException) NoResponseException(org.jivesoftware.smack.SmackException.NoResponseException) IOException(java.io.IOException) SmackException(org.jivesoftware.smack.SmackException) StreamManagementException(org.jivesoftware.smack.sm.StreamManagementException) AlreadyLoggedInException(org.jivesoftware.smack.SmackException.AlreadyLoggedInException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) StreamIdDoesNotMatchException(org.jivesoftware.smack.sm.StreamManagementException.StreamIdDoesNotMatchException) StreamManagementNotEnabledException(org.jivesoftware.smack.sm.StreamManagementException.StreamManagementNotEnabledException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) SecurityRequiredByServerException(org.jivesoftware.smack.SmackException.SecurityRequiredByServerException) AlreadyConnectedException(org.jivesoftware.smack.SmackException.AlreadyConnectedException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 19 with NotConnectedException

use of org.jivesoftware.smack.SmackException.NotConnectedException in project Smack by igniterealtime.

the class PacketWriterTest method shouldBlockAndUnblockTest.

/**
     * Make sure that stanza(/packet) writer does block once the queue reaches
     * {@link PacketWriter#QUEUE_SIZE} and that
     * {@link PacketWriter#sendStanza(org.jivesoftware.smack.tcp.packet.Packet)} does unblock after the
     * interrupt.
     * 
     * @throws InterruptedException
     * @throws BrokenBarrierException
     * @throws NotConnectedException 
     * @throws XmppStringprepException 
     */
@SuppressWarnings("javadoc")
@Test
public void shouldBlockAndUnblockTest() throws InterruptedException, BrokenBarrierException, NotConnectedException, XmppStringprepException {
    XMPPTCPConnection connection = new XMPPTCPConnection("user", "pass", "example.org");
    final PacketWriter pw = connection.new PacketWriter();
    connection.packetWriter = pw;
    connection.packetReader = connection.new PacketReader();
    connection.setWriter(new BlockingStringWriter());
    pw.init();
    for (int i = 0; i < XMPPTCPConnection.PacketWriter.QUEUE_SIZE; i++) {
        pw.sendStreamElement(new Message());
    }
    final CyclicBarrier barrier = new CyclicBarrier(2);
    shutdown = false;
    prematureUnblocked = false;
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                barrier.await();
                pw.sendStreamElement(new Message());
                // should only return after the pw was interrupted
                if (!shutdown) {
                    prematureUnblocked = true;
                }
            } catch (Exception e) {
            }
            try {
                barrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
            }
        }
    });
    t.start();
    // This barrier is not strictly necessary, but may increases the chances that the threat
    // will block before we call shutdown. Otherwise we may get false positives (which is still
    // better then false negatives).
    barrier.await();
    // Not really cool, but may increases the chances for 't' to block in sendStanza.
    Thread.sleep(250);
    // Set to true for testing purposes, so that shutdown() won't wait packet writer
    pw.shutdownDone.reportSuccess();
    // Shutdown the packetwriter
    pw.shutdown(false);
    shutdown = true;
    barrier.await();
    if (prematureUnblocked) {
        fail("Should not unblock before the thread got shutdown");
    }
    synchronized (t) {
        t.notify();
    }
}
Also used : Message(org.jivesoftware.smack.packet.Message) PacketWriter(org.jivesoftware.smack.tcp.XMPPTCPConnection.PacketWriter) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) XmppStringprepException(org.jxmpp.stringprep.XmppStringprepException) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) CyclicBarrier(java.util.concurrent.CyclicBarrier) Test(org.junit.Test)

Example 20 with NotConnectedException

use of org.jivesoftware.smack.SmackException.NotConnectedException in project Smack by igniterealtime.

the class AbstractXMPPConnection method invokeStanzaCollectorsAndNotifyRecvListeners.

/**
     * Invoke {@link StanzaCollector#processStanza(Stanza)} for every
     * StanzaCollector with the given packet. Also notify the receive listeners with a matching stanza(/packet) filter about the packet.
     *
     * @param packet the stanza(/packet) to notify the StanzaCollectors and receive listeners about.
     */
protected void invokeStanzaCollectorsAndNotifyRecvListeners(final Stanza packet) {
    if (packet instanceof IQ) {
        final IQ iq = (IQ) packet;
        final IQ.Type type = iq.getType();
        switch(type) {
            case set:
            case get:
                final String key = XmppStringUtils.generateKey(iq.getChildElementName(), iq.getChildElementNamespace());
                IQRequestHandler iqRequestHandler = null;
                switch(type) {
                    case set:
                        synchronized (setIqRequestHandler) {
                            iqRequestHandler = setIqRequestHandler.get(key);
                        }
                        break;
                    case get:
                        synchronized (getIqRequestHandler) {
                            iqRequestHandler = getIqRequestHandler.get(key);
                        }
                        break;
                    default:
                        throw new IllegalStateException("Should only encounter IQ type 'get' or 'set'");
                }
                if (iqRequestHandler == null) {
                    if (!replyToUnkownIq) {
                        return;
                    }
                    // If the IQ stanza is of type "get" or "set" with no registered IQ request handler, then answer an
                    // IQ of type 'error' with condition 'service-unavailable'.
                    ErrorIQ errorIQ = IQ.createErrorResponse(iq, XMPPError.getBuilder((XMPPError.Condition.service_unavailable)));
                    try {
                        sendStanza(errorIQ);
                    } catch (InterruptedException | NotConnectedException e) {
                        LOGGER.log(Level.WARNING, "Exception while sending error IQ to unkown IQ request", e);
                    }
                } else {
                    ExecutorService executorService = null;
                    switch(iqRequestHandler.getMode()) {
                        case sync:
                            executorService = singleThreadedExecutorService;
                            break;
                        case async:
                            executorService = cachedExecutorService;
                            break;
                    }
                    final IQRequestHandler finalIqRequestHandler = iqRequestHandler;
                    executorService.execute(new Runnable() {

                        @Override
                        public void run() {
                            IQ response = finalIqRequestHandler.handleIQRequest(iq);
                            if (response == null) {
                                // e.g. to avoid presence leaks.
                                return;
                            }
                            try {
                                sendStanza(response);
                            } catch (InterruptedException | NotConnectedException e) {
                                LOGGER.log(Level.WARNING, "Exception while sending response to IQ request", e);
                            }
                        }
                    });
                    // desired behavior.
                    return;
                }
                break;
            default:
                break;
        }
    }
    // First handle the async recv listeners. Note that this code is very similar to what follows a few lines below,
    // the only difference is that asyncRecvListeners is used here and that the packet listeners are started in
    // their own thread.
    final Collection<StanzaListener> listenersToNotify = new LinkedList<StanzaListener>();
    synchronized (asyncRecvListeners) {
        for (ListenerWrapper listenerWrapper : asyncRecvListeners.values()) {
            if (listenerWrapper.filterMatches(packet)) {
                listenersToNotify.add(listenerWrapper.getListener());
            }
        }
    }
    for (final StanzaListener listener : listenersToNotify) {
        asyncGo(new Runnable() {

            @Override
            public void run() {
                try {
                    listener.processStanza(packet);
                } catch (Exception e) {
                    LOGGER.log(Level.SEVERE, "Exception in async packet listener", e);
                }
            }
        });
    }
    // Loop through all collectors and notify the appropriate ones.
    for (StanzaCollector collector : collectors) {
        collector.processStanza(packet);
    }
    // Notify the receive listeners interested in the packet
    listenersToNotify.clear();
    synchronized (syncRecvListeners) {
        for (ListenerWrapper listenerWrapper : syncRecvListeners.values()) {
            if (listenerWrapper.filterMatches(packet)) {
                listenersToNotify.add(listenerWrapper.getListener());
            }
        }
    }
    // Decouple incoming stanza processing from listener invocation. Unlike async listeners, this uses a single
    // threaded executor service and therefore keeps the order.
    singleThreadedExecutorService.execute(new Runnable() {

        @Override
        public void run() {
            for (StanzaListener listener : listenersToNotify) {
                try {
                    listener.processStanza(packet);
                } catch (NotConnectedException e) {
                    LOGGER.log(Level.WARNING, "Got not connected exception, aborting", e);
                    break;
                } catch (Exception e) {
                    LOGGER.log(Level.SEVERE, "Exception in packet listener", e);
                }
            }
        }
    });
}
Also used : ErrorIQ(org.jivesoftware.smack.packet.ErrorIQ) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) IQ(org.jivesoftware.smack.packet.IQ) ErrorIQ(org.jivesoftware.smack.packet.ErrorIQ) LinkedList(java.util.LinkedList) SecurityRequiredException(org.jivesoftware.smack.SmackException.SecurityRequiredException) XMPPErrorException(org.jivesoftware.smack.XMPPException.XMPPErrorException) AlreadyLoggedInException(org.jivesoftware.smack.SmackException.AlreadyLoggedInException) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) StreamErrorException(org.jivesoftware.smack.XMPPException.StreamErrorException) NoResponseException(org.jivesoftware.smack.SmackException.NoResponseException) IOException(java.io.IOException) AlreadyConnectedException(org.jivesoftware.smack.SmackException.AlreadyConnectedException) SecurityRequiredByClientException(org.jivesoftware.smack.SmackException.SecurityRequiredByClientException) ResourceBindingNotOfferedException(org.jivesoftware.smack.SmackException.ResourceBindingNotOfferedException) IQRequestHandler(org.jivesoftware.smack.iqrequest.IQRequestHandler) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService)

Aggregations

NotConnectedException (org.jivesoftware.smack.SmackException.NotConnectedException)22 NoResponseException (org.jivesoftware.smack.SmackException.NoResponseException)11 XMPPException (org.jivesoftware.smack.XMPPException)11 XMPPErrorException (org.jivesoftware.smack.XMPPException.XMPPErrorException)9 SmackException (org.jivesoftware.smack.SmackException)6 IOException (java.io.IOException)5 XMPPConnection (org.jivesoftware.smack.XMPPConnection)5 MultiUserChat (org.jivesoftware.smackx.muc.MultiUserChat)3 KeyManagementException (java.security.KeyManagementException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 LinkedList (java.util.LinkedList)2 ChatManager (org.jivesoftware.smack.ChatManager)2 AlreadyConnectedException (org.jivesoftware.smack.SmackException.AlreadyConnectedException)2 AlreadyLoggedInException (org.jivesoftware.smack.SmackException.AlreadyLoggedInException)2 StreamErrorException (org.jivesoftware.smack.XMPPException.StreamErrorException)2 AndFilter (org.jivesoftware.smack.filter.AndFilter)2 DiscoverInfo (org.jivesoftware.smackx.disco.packet.DiscoverInfo)2 NotAMucServiceException (org.jivesoftware.smackx.muc.MultiUserChatException.NotAMucServiceException)2 XmppStringprepException (org.jxmpp.stringprep.XmppStringprepException)2 InetAddress (java.net.InetAddress)1