use of org.jivesoftware.smack.filter.StanzaExtensionFilter in project Smack by igniterealtime.
the class GroupChatInvitationTest method setUp.
protected void setUp() throws Exception {
super.setUp();
// Register listener for groupchat invitations.
PacketFilter filter = new StanzaExtensionFilter("x", "jabber:x:conference");
collector = getConnection(1).createStanzaCollector(filter);
}
use of org.jivesoftware.smack.filter.StanzaExtensionFilter in project Smack by igniterealtime.
the class XHTMLExtensionTest method testSendComplexXHTMLMessageAndDisplayReceivedXHTMLMessage.
/**
* Low level API test. Test a message with two XHTML bodies and several XHTML tags.
* 1. User_1 will send a message with XHTML to user_2
* 2. User_2 will receive the message and iterate over the XHTML bodies to check if everything
* is fine
* 3. User_1 will wait several seconds for an ACK from user_2, if none is received then
* something is wrong
*/
public void testSendComplexXHTMLMessageAndDisplayReceivedXHTMLMessage() {
// Create a chat for each connection
Chat chat1 = getConnection(0).getChatManager().createChat(getBareJID(1), null);
final StanzaCollector chat2 = getConnection(1).createStanzaCollector(new ThreadFilter(chat1.getThreadID()));
// Create a Listener that listens for Messages with the extension
// "http://jabber.org/protocol/xhtml-im"
// This listener will listen on the conn2 and answer an ACK if everything is ok
PacketFilter packetFilter = new StanzaExtensionFilter("html", "http://jabber.org/protocol/xhtml-im");
PacketListener packetListener = new PacketListener() {
@Override
public void processStanza(Packet packet) {
}
};
getConnection(1).addAsyncPacketListener(packetListener, packetFilter);
// User1 creates a message to send to user2
Message msg = new Message();
msg.setSubject("Any subject you want");
msg.setBody("awesome! As Emerson once said: A foolish consistency is the hobgoblin of little minds.");
// Create an XHTMLExtension and add it to the message
XHTMLExtension xhtmlExtension = new XHTMLExtension();
xhtmlExtension.addBody("<body xml:lang=\"es-ES\"><h1>impresionante!</h1><p>Como Emerson dijo una vez:</p><blockquote><p>Una consistencia ridicula es el espantajo de mentes pequenas.</p></blockquote></body>");
xhtmlExtension.addBody("<body xml:lang=\"en-US\"><h1>awesome!</h1><p>As Emerson once said:</p><blockquote><p>A foolish consistency is the hobgoblin of little minds.</p></blockquote></body>");
msg.addExtension(xhtmlExtension);
// User1 sends the message that contains the XHTML to user2
try {
bodiesSent = xhtmlExtension.getBodiesCount();
bodiesReceived = 0;
chat1.sendMessage(msg);
} catch (Exception e) {
fail("An error occurred sending the message with XHTML");
}
Packet packet = chat2.nextResult(2000);
int received = 0;
Message message = (Message) packet;
assertNotNull("Body is null", message.getBody());
try {
xhtmlExtension = (XHTMLExtension) message.getExtension("html", "http://jabber.org/protocol/xhtml-im");
assertNotNull("Message without extension \"http://jabber.org/protocol/xhtml-im\"", xhtmlExtension);
assertTrue("Message without XHTML bodies", xhtmlExtension.getBodiesCount() > 0);
for (Iterator<String> it = xhtmlExtension.getBodies(); it.hasNext(); ) {
received++;
System.out.println(it.next());
}
bodiesReceived = received;
} catch (ClassCastException e) {
fail("ClassCastException - Most probable cause is that smack providers is " + "misconfigured");
}
// Wait half second so that the complete test can run
assertEquals("Number of sent and received XHTMP bodies does not match", bodiesSent, bodiesReceived);
}
use of org.jivesoftware.smack.filter.StanzaExtensionFilter 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.
}
Aggregations