Search in sources :

Example 21 with MessageBuilder

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

the class RosterExchangeManager method send.

/**
 * Sends a roster to userID. All the entries of the roster will be sent to the
 * target user.
 *
 * @param roster the roster to send
 * @param targetUserID the user that will receive the roster entries
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public void send(Roster roster, Jid targetUserID) throws NotConnectedException, InterruptedException {
    XMPPConnection connection = weakRefConnection.get();
    // Create a new message to send the roster
    MessageBuilder messageBuilder = connection.getStanzaFactory().buildMessageStanza().to(targetUserID);
    // Create a RosterExchange Package and add it to the message
    RosterExchange rosterExchange = new RosterExchange(roster);
    messageBuilder.addExtension(rosterExchange);
    // Send the message that contains the roster
    connection.sendStanza(messageBuilder.build());
}
Also used : RosterExchange(org.jivesoftware.smackx.xroster.packet.RosterExchange) MessageBuilder(org.jivesoftware.smack.packet.MessageBuilder) XMPPConnection(org.jivesoftware.smack.XMPPConnection)

Example 22 with MessageBuilder

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

the class MessageRetractionManager method retractMessage.

/**
 * Retract a message by appending a {@link RetractElement} wrapped inside a {@link FasteningElement} which contains
 * the {@link OriginIdElement Origin-ID} of the message that will be retracted to a new message and send it to the
 * server.
 *
 * @param retractedMessageId {@link OriginIdElement OriginID} of the message that the user wants to retract
 * @throws SmackException.NotConnectedException in case the connection is not connected.
 * @throws InterruptedException if the thread gets interrupted.
 */
public void retractMessage(OriginIdElement retractedMessageId) throws SmackException.NotConnectedException, InterruptedException {
    MessageBuilder message = connection().getStanzaFactory().buildMessageStanza();
    addRetractionElementToMessage(retractedMessageId, message);
    connection().sendStanza(message.build());
}
Also used : MessageBuilder(org.jivesoftware.smack.packet.MessageBuilder)

Example 23 with MessageBuilder

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

the class SessionRenegotiationIntegrationTest method sessionRenegotiationTest.

@SuppressWarnings("SynchronizeOnNonFinalField")
@SmackIntegrationTest
public void sessionRenegotiationTest() throws Exception {
    boolean prevRepairProperty = OmemoConfiguration.getRepairBrokenSessionsWithPreKeyMessages();
    OmemoConfiguration.setRepairBrokenSessionsWithPrekeyMessages(true);
    boolean prevCompleteSessionProperty = OmemoConfiguration.getCompleteSessionWithEmptyMessage();
    OmemoConfiguration.setCompleteSessionWithEmptyMessage(false);
    // send PreKeyMessage -> Success
    final String body1 = "P = NP is true for all N,P from the set of complex numbers, where P is equal to 0";
    AbstractOmemoMessageListener.PreKeyMessageListener listener1 = new AbstractOmemoMessageListener.PreKeyMessageListener(body1);
    OmemoMessage.Sent e1 = alice.encrypt(bob.getOwnJid(), body1);
    bob.addOmemoMessageListener(listener1);
    XMPPConnection alicesConnection = alice.getConnection();
    MessageBuilder messageBuilder = alicesConnection.getStanzaFactory().buildMessageStanza();
    alicesConnection.sendStanza(e1.buildMessage(messageBuilder, bob.getOwnJid()));
    listener1.getSyncPoint().waitForResult(10 * 1000);
    bob.removeOmemoMessageListener(listener1);
    // Remove the session on Bobs side.
    synchronized (bob) {
        bob.getOmemoService().getOmemoStoreBackend().removeRawSession(bob.getOwnDevice(), alice.getOwnDevice());
    }
    // Send normal message -> fail, bob repairs session with preKeyMessage
    final String body2 = "P = NP is also true for all N,P from the set of complex numbers, where N is equal to 1.";
    AbstractOmemoMessageListener.PreKeyKeyTransportListener listener2 = new AbstractOmemoMessageListener.PreKeyKeyTransportListener();
    OmemoMessage.Sent e2 = alice.encrypt(bob.getOwnJid(), body2);
    alice.addOmemoMessageListener(listener2);
    messageBuilder = alicesConnection.getStanzaFactory().buildMessageStanza();
    alicesConnection.sendStanza(e2.buildMessage(messageBuilder, bob.getOwnJid()));
    listener2.getSyncPoint().waitForResult(10 * 1000);
    alice.removeOmemoMessageListener(listener2);
    // Send normal message -> success
    final String body3 = "P = NP would be a disaster for the world of cryptography.";
    AbstractOmemoMessageListener.MessageListener listener3 = new AbstractOmemoMessageListener.MessageListener(body3);
    OmemoMessage.Sent e3 = alice.encrypt(bob.getOwnJid(), body3);
    bob.addOmemoMessageListener(listener3);
    messageBuilder = alicesConnection.getStanzaFactory().buildMessageStanza();
    alicesConnection.sendStanza(e3.buildMessage(messageBuilder, bob.getOwnJid()));
    listener3.getSyncPoint().waitForResult(10 * 1000);
    bob.removeOmemoMessageListener(listener3);
    OmemoConfiguration.setRepairBrokenSessionsWithPrekeyMessages(prevRepairProperty);
    OmemoConfiguration.setCompleteSessionWithEmptyMessage(prevCompleteSessionProperty);
}
Also used : XMPPConnection(org.jivesoftware.smack.XMPPConnection) MessageBuilder(org.jivesoftware.smack.packet.MessageBuilder) SmackIntegrationTest(org.igniterealtime.smack.inttest.annotations.SmackIntegrationTest)

Example 24 with MessageBuilder

use of org.jivesoftware.smack.packet.MessageBuilder 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 25 with MessageBuilder

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

the class ChatTest method testProperties.

@SuppressWarnings("deprecation")
@SmackIntegrationTest
public void testProperties() throws Exception {
    org.jivesoftware.smack.chat.Chat newChat = chatManagerOne.createChat(conTwo.getUser());
    StanzaCollector collector = conTwo.createStanzaCollector(new ThreadFilter(newChat.getThreadID()));
    MessageBuilder messageBuilder = StanzaBuilder.buildMessage();
    messageBuilder.setSubject("Subject of the chat");
    messageBuilder.setBody("Body of the chat");
    addProperty(messageBuilder, "favoriteColor", "red");
    addProperty(messageBuilder, "age", 30);
    addProperty(messageBuilder, "distance", 30f);
    addProperty(messageBuilder, "weight", 30d);
    addProperty(messageBuilder, "male", true);
    addProperty(messageBuilder, "birthdate", new Date());
    Message msg = messageBuilder.build();
    newChat.sendMessage(msg);
    Message msg2 = collector.nextResult(2000);
    assertNotNull(msg2, "No message was received");
    assertEquals(msg.getSubject(), msg2.getSubject(), "Subjects are different");
    assertEquals(msg.getBody(), msg2.getBody(), "Bodies are different");
    assertEquals(getProperty(msg, "favoriteColor"), getProperty(msg2, "favoriteColor"), "favoriteColors are different");
    assertEquals(getProperty(msg, "age"), getProperty(msg2, "age"), "ages are different");
    assertEquals(getProperty(msg, "distance"), getProperty(msg2, "distance"), "distances are different");
    assertEquals(getProperty(msg, "weight"), getProperty(msg2, "weight"), "weights are different");
    assertEquals(getProperty(msg, "male"), getProperty(msg2, "male"), "males are different");
    assertEquals(getProperty(msg, "birthdate"), getProperty(msg2, "birthdate"), "birthdates are different");
}
Also used : MessageBuilder(org.jivesoftware.smack.packet.MessageBuilder) Message(org.jivesoftware.smack.packet.Message) ThreadFilter(org.jivesoftware.smack.filter.ThreadFilter) Date(java.util.Date) AbstractSmackIntegrationTest(org.igniterealtime.smack.inttest.AbstractSmackIntegrationTest) SmackIntegrationTest(org.igniterealtime.smack.inttest.annotations.SmackIntegrationTest)

Aggregations

MessageBuilder (org.jivesoftware.smack.packet.MessageBuilder)34 Message (org.jivesoftware.smack.packet.Message)10 XMPPConnection (org.jivesoftware.smack.XMPPConnection)9 Test (org.junit.jupiter.api.Test)8 Test (org.junit.Test)7 SmackIntegrationTest (org.igniterealtime.smack.inttest.annotations.SmackIntegrationTest)5 Stanza (org.jivesoftware.smack.packet.Stanza)3 RosterExchange (org.jivesoftware.smackx.xroster.packet.RosterExchange)3 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)3 Date (java.util.Date)2 DummyConnection (org.jivesoftware.smack.DummyConnection)2 AndFilter (org.jivesoftware.smack.filter.AndFilter)2 XmlElement (org.jivesoftware.smack.packet.XmlElement)2 OpenPgpMessage (org.jivesoftware.smackx.ox.OpenPgpMessage)2 EntityBareJid (org.jxmpp.jid.EntityBareJid)2 File (java.io.File)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Random (java.util.Random)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1