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();
}
}
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());
}
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();
}
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();
}
}
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);
}
}
}
});
}
Aggregations