Search in sources :

Example 66 with Stanza

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

the class MamIntegrationTest method mamTest.

@SmackIntegrationTest
public void mamTest() throws TimeoutException, Exception {
    EntityBareJid userOne = conOne.getUser().asEntityBareJid();
    EntityBareJid userTwo = conTwo.getUser().asEntityBareJid();
    final String messageBody = "Test MAM message (" + testRunId + ')';
    Message message = conTwo.getStanzaFactory().buildMessageStanza().to(userTwo).setBody(messageBody).build();
    final String messageId = message.getStanzaId();
    final SimpleResultSyncPoint messageReceived = new SimpleResultSyncPoint();
    final StanzaListener stanzaListener = new StanzaListener() {

        @Override
        public void processStanza(Stanza stanza) {
            Message message = (Message) stanza;
            if (message.getBody().equals(messageBody)) {
                messageReceived.signal();
            }
        }
    };
    conTwo.addAsyncStanzaListener(stanzaListener, MessageWithBodiesFilter.INSTANCE);
    try {
        conOne.sendStanza(message);
        messageReceived.waitForResult(timeout);
    } finally {
        conTwo.removeAsyncStanzaListener(stanzaListener);
    }
    MamQueryArgs mamQueryArgs = MamQueryArgs.builder().setResultPageSizeTo(1).limitResultsToJid(userOne).queryLastPage().build();
    MamQuery mamQuery = mamManagerConTwo.queryArchive(mamQueryArgs);
    assertEquals(1, mamQuery.getMessages().size());
    Message mamMessage = mamQuery.getMessages().get(0);
    assertEquals(messageId, mamMessage.getStanzaId());
    assertEquals(messageBody, mamMessage.getBody());
    assertEquals(conOne.getUser(), mamMessage.getFrom());
    assertEquals(userTwo, mamMessage.getTo());
}
Also used : Message(org.jivesoftware.smack.packet.Message) Stanza(org.jivesoftware.smack.packet.Stanza) StanzaListener(org.jivesoftware.smack.StanzaListener) MamQuery(org.jivesoftware.smackx.mam.MamManager.MamQuery) EntityBareJid(org.jxmpp.jid.EntityBareJid) SimpleResultSyncPoint(org.igniterealtime.smack.inttest.util.SimpleResultSyncPoint) MamQueryArgs(org.jivesoftware.smackx.mam.MamManager.MamQueryArgs) SmackIntegrationTest(org.igniterealtime.smack.inttest.annotations.SmackIntegrationTest) AbstractSmackIntegrationTest(org.igniterealtime.smack.inttest.AbstractSmackIntegrationTest)

Example 67 with Stanza

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

the class XmppConnectionStressTest method run.

public void run(List<? extends XMPPConnection> connections, final long replyTimeoutMillis) throws InterruptedException, NotAllMessagesReceivedException, ErrorsWhileSendingOrReceivingException {
    final MultiMap<XMPPConnection, Message> messages = new MultiMap<>();
    final Random random = new Random(configuration.seed);
    final Map<XMPPConnection, Exception> sendExceptions = new ConcurrentHashMap<>();
    final Map<XMPPConnection, Exception> receiveExceptions = new ConcurrentHashMap<>();
    waitStart = -1;
    for (XMPPConnection fromConnection : connections) {
        MultiMap<XMPPConnection, Message> toConnectionMessages = new MultiMap<>();
        for (XMPPConnection toConnection : connections) {
            for (int i = 0; i < configuration.messagesPerConnection; i++) {
                MessageBuilder messageBuilder = fromConnection.getStanzaFactory().buildMessageStanza();
                messageBuilder.to(toConnection.getUser());
                final int payloadChunkCount;
                if (configuration.maxPayloadChunks == 0) {
                    payloadChunkCount = 0;
                } else {
                    payloadChunkCount = random.nextInt(configuration.maxPayloadChunks) + 1;
                }
                for (int c = 0; c < payloadChunkCount; c++) {
                    int payloadChunkSize = random.nextInt(configuration.maxPayloadChunkSize) + 1;
                    String payloadCunk = StringUtils.randomString(payloadChunkSize, random);
                    JivePropertiesManager.addProperty(messageBuilder, "payload-chunk-" + c, payloadCunk);
                }
                JivePropertiesManager.addProperty(messageBuilder, MESSAGE_NUMBER_PROPERTY, i);
                Message message = messageBuilder.build();
                toConnectionMessages.put(toConnection, message);
            }
        }
        if (configuration.intermixMessages) {
            while (!toConnectionMessages.isEmpty()) {
                int next = random.nextInt(connections.size());
                Message message = null;
                while (message == null) {
                    XMPPConnection toConnection = connections.get(next);
                    message = toConnectionMessages.getFirst(toConnection);
                    next = (next + 1) % connections.size();
                }
                messages.put(fromConnection, message);
            }
        } else {
            for (XMPPConnection toConnection : connections) {
                for (Message message : toConnectionMessages.getAll(toConnection)) {
                    messages.put(fromConnection, message);
                }
            }
        }
    }
    Semaphore receivedSemaphore = new Semaphore(-connections.size() + 1);
    Map<XMPPConnection, Map<EntityFullJid, boolean[]>> receiveMarkers = new ConcurrentHashMap<>(connections.size());
    for (XMPPConnection connection : connections) {
        final Map<EntityFullJid, boolean[]> myReceiveMarkers = new HashMap<>(connections.size());
        receiveMarkers.put(connection, myReceiveMarkers);
        for (XMPPConnection otherConnection : connections) {
            boolean[] fromMarkers = new boolean[configuration.messagesPerConnection];
            myReceiveMarkers.put(otherConnection.getUser(), fromMarkers);
        }
        connection.addSyncStanzaListener(new StanzaListener() {

            @Override
            public void processStanza(Stanza stanza) {
                waitStart = System.currentTimeMillis();
                EntityFullJid from = stanza.getFrom().asEntityFullJidOrThrow();
                Message message = (Message) stanza;
                JivePropertiesExtension extension = JivePropertiesExtension.from(message);
                Integer messageNumber = (Integer) extension.getProperty(MESSAGE_NUMBER_PROPERTY);
                boolean[] fromMarkers = myReceiveMarkers.get(from);
                // Sanity check: All markers before must be true, all markers including the messageNumber marker must be false.
                for (int i = 0; i < fromMarkers.length; i++) {
                    final String inOrderViolation;
                    if (i < messageNumber && !fromMarkers[i]) {
                        // A previous message was missing.
                        inOrderViolation = "not yet message #";
                    } else if (i >= messageNumber && fromMarkers[i]) {
                        // We already received a new message.
                        // TODO: Can it ever happen that this is taken? Wouldn't we prior run into the "a previous
                        // message is missing" case?
                        inOrderViolation = "we already received a later (or the same) message #";
                    } else {
                        continue;
                    }
                    StringBuilder exceptionMessage = new StringBuilder();
                    exceptionMessage.append("We received message #").append(messageNumber).append(" but ");
                    exceptionMessage.append(inOrderViolation);
                    exceptionMessage.append(i);
                    exceptionMessage.append("\nMessage with id ").append(stanza.getStanzaId()).append(" from ").append(from).append(" to ").append(stanza.getTo()).append('\n');
                    exceptionMessage.append("From Markers: ").append(Arrays.toString(fromMarkers)).append('\n');
                    Exception exception = new Exception(exceptionMessage.toString());
                    receiveExceptions.put(connection, exception);
                    // TODO: Current Smack design does not guarantee that the listener won't be invoked again.
                    // This is because the decission to invoke a sync listeners is done at a different place
                    // then invoking the listener.
                    connection.removeSyncStanzaListener(this);
                    receivedSemaphore.release();
                    // TODO: Do not return here?
                    return;
                }
                fromMarkers[messageNumber] = true;
                for (boolean[] markers : myReceiveMarkers.values()) {
                    if (BooleansUtils.contains(markers, false)) {
                        // receivedSemaphore.
                        return;
                    }
                }
                // All markers set to true, this means we received all messages.
                receivedSemaphore.release();
            }
        }, new AndFilter(MessageTypeFilter.NORMAL, new StanzaExtensionFilter(JivePropertiesExtension.ELEMENT, JivePropertiesExtension.NAMESPACE)));
    }
    Semaphore sendSemaphore = new Semaphore(-connections.size() + 1);
    for (XMPPConnection connection : connections) {
        Async.go(() -> {
            List<Message> messagesToSend;
            synchronized (messages) {
                messagesToSend = messages.getAll(connection);
            }
            try {
                for (Message messageToSend : messagesToSend) {
                    connection.sendStanza(messageToSend);
                }
            } catch (NotConnectedException | InterruptedException e) {
                sendExceptions.put(connection, e);
            } finally {
                sendSemaphore.release();
            }
        });
    }
    sendSemaphore.acquire();
    if (waitStart < 0) {
        waitStart = System.currentTimeMillis();
    }
    boolean acquired;
    do {
        long acquireWait = waitStart + replyTimeoutMillis - System.currentTimeMillis();
        acquired = receivedSemaphore.tryAcquire(acquireWait, TimeUnit.MILLISECONDS);
    } while (!acquired && System.currentTimeMillis() < waitStart + replyTimeoutMillis);
    if (!acquired && receiveExceptions.isEmpty() && sendExceptions.isEmpty()) {
        throw new StressTestFailedException.NotAllMessagesReceivedException(receiveMarkers, connections);
    }
    if (!receiveExceptions.isEmpty() || !sendExceptions.isEmpty()) {
        throw new StressTestFailedException.ErrorsWhileSendingOrReceivingException(sendExceptions, receiveExceptions);
    }
// Test successful.
}
Also used : Message(org.jivesoftware.smack.packet.Message) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) StanzaExtensionFilter(org.jivesoftware.smack.filter.StanzaExtensionFilter) StanzaListener(org.jivesoftware.smack.StanzaListener) XMPPConnection(org.jivesoftware.smack.XMPPConnection) Semaphore(java.util.concurrent.Semaphore) MultiMap(org.jivesoftware.smack.util.MultiMap) Random(java.util.Random) MessageBuilder(org.jivesoftware.smack.packet.MessageBuilder) NotAllMessagesReceivedException(org.igniterealtime.smack.XmppConnectionStressTest.StressTestFailedException.NotAllMessagesReceivedException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) EntityFullJid(org.jxmpp.jid.EntityFullJid) Stanza(org.jivesoftware.smack.packet.Stanza) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) NotAllMessagesReceivedException(org.igniterealtime.smack.XmppConnectionStressTest.StressTestFailedException.NotAllMessagesReceivedException) ErrorsWhileSendingOrReceivingException(org.igniterealtime.smack.XmppConnectionStressTest.StressTestFailedException.ErrorsWhileSendingOrReceivingException) JivePropertiesExtension(org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension) AndFilter(org.jivesoftware.smack.filter.AndFilter) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MultiMap(org.jivesoftware.smack.util.MultiMap) ErrorsWhileSendingOrReceivingException(org.igniterealtime.smack.XmppConnectionStressTest.StressTestFailedException.ErrorsWhileSendingOrReceivingException)

Example 68 with Stanza

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

the class RosterTest method initRoster.

/**
 * Initialize the roster according to the example in
 * <a href="http://xmpp.org/rfcs/rfc3921.html#roster-login"
 *     >RFC3921: Retrieving One's Roster on Login</a>.
 *
 * @throws SmackException if Smack detected an exceptional situation.
 * @throws XmppStringprepException if the provided string is invalid.
 */
private void initRoster() throws InterruptedException, SmackException, XmppStringprepException {
    roster.reload();
    while (true) {
        final Stanza sentPacket = connection.getSentPacket();
        if (sentPacket instanceof RosterPacket && ((IQ) sentPacket).getType() == IQ.Type.get) {
            // setup the roster get request
            final RosterPacket rosterRequest = (RosterPacket) sentPacket;
            assertSame("The <query/> element MUST NOT contain any <item/> child elements!", 0, rosterRequest.getRosterItemCount());
            // prepare the roster result
            final RosterPacket rosterResult = new RosterPacket();
            rosterResult.setTo(connection.getUser());
            rosterResult.setType(IQ.Type.result);
            rosterResult.setStanzaId(rosterRequest.getStanzaId());
            // prepare romeo's roster entry
            final Item romeo = new Item(JidCreate.entityBareFrom("romeo@example.net"), "Romeo");
            romeo.addGroupName("Friends");
            romeo.setItemType(ItemType.both);
            rosterResult.addRosterItem(romeo);
            // prepare mercutio's roster entry
            final Item mercutio = new Item(JidCreate.entityBareFrom("mercutio@example.com"), "Mercutio");
            mercutio.setItemType(ItemType.from);
            rosterResult.addRosterItem(mercutio);
            // prepare benvolio's roster entry
            final Item benvolio = new Item(JidCreate.entityBareFrom("benvolio@example.net"), "Benvolio");
            benvolio.setItemType(ItemType.both);
            rosterResult.addRosterItem(benvolio);
            // simulate receiving the roster result and exit the loop
            connection.processStanza(rosterResult);
            break;
        }
    }
    roster.waitUntilLoaded();
    rosterListener.waitUntilInvocationOrTimeout();
}
Also used : Item(org.jivesoftware.smack.roster.packet.RosterPacket.Item) RosterPacket(org.jivesoftware.smack.roster.packet.RosterPacket) Stanza(org.jivesoftware.smack.packet.Stanza) ErrorIQ(org.jivesoftware.smack.packet.ErrorIQ) IQ(org.jivesoftware.smack.packet.IQ)

Example 69 with Stanza

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

the class SimpleXmppConnectionIntegrationTest method createConnectionTest.

@SmackIntegrationTest(connectionCount = 2)
public void createConnectionTest(List<AbstractXMPPConnection> connections) throws TimeoutException, Exception {
    final AbstractXMPPConnection conOne = connections.get(0), conTwo = connections.get(1);
    EntityFullJid userTwo = conTwo.getUser();
    final String messageBody = testRunId + ": Hello from the other side!";
    Message message = conTwo.getStanzaFactory().buildMessageStanza().to(userTwo).setBody(messageBody).build();
    final SimpleResultSyncPoint messageReceived = new SimpleResultSyncPoint();
    final StanzaListener stanzaListener = (Stanza stanza) -> {
        if (((Message) stanza).getBody().equals(messageBody)) {
            messageReceived.signal();
        }
    };
    conTwo.addAsyncStanzaListener(stanzaListener, MessageWithBodiesFilter.INSTANCE);
    try {
        conOne.sendStanza(message);
        messageReceived.waitForResult(timeout);
    } finally {
        conTwo.removeAsyncStanzaListener(stanzaListener);
    }
}
Also used : Message(org.jivesoftware.smack.packet.Message) EntityFullJid(org.jxmpp.jid.EntityFullJid) Stanza(org.jivesoftware.smack.packet.Stanza) StanzaListener(org.jivesoftware.smack.StanzaListener) SimpleResultSyncPoint(org.igniterealtime.smack.inttest.util.SimpleResultSyncPoint) AbstractXMPPConnection(org.jivesoftware.smack.AbstractXMPPConnection) SmackIntegrationTest(org.igniterealtime.smack.inttest.annotations.SmackIntegrationTest)

Example 70 with Stanza

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

the class Offer method accept.

/**
 * Accepts the offer.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public void accept() throws NotConnectedException, InterruptedException {
    Stanza acceptPacket = new AcceptPacket(this.session.getWorkgroupJID());
    connection.sendStanza(acceptPacket);
    // TODO: listen for a reply.
    accepted = true;
}
Also used : Stanza(org.jivesoftware.smack.packet.Stanza)

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